Last updated: 2025-07-26

Checks: 6 1

Knit directory: Machine-learning-e-redes-neurais-artificiais-no-melhoramento-genetico-do-cafeeiro/

This reproducible R Markdown analysis was created with workflowr (version 1.7.1). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


The R Markdown file has unstaged changes. To know which version of the R Markdown file created these results, you’ll want to first commit it to the Git repo. If you’re still working on the analysis, you can ignore this warning. When you’re finished, you can run wflow_publish to commit the R Markdown file and build the HTML.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20250709) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 82b3f68. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rproj.user/
    Ignored:    analysis/modelos_mistos_dados_reais.Rmd
    Ignored:    data/dados_reais/Fenótipos 2014_2015_2016_C.arabica (1).xlsx
    Ignored:    data/dados_reais/Fenótipos 2014_2015_2016_C.arabica.xlsx
    Ignored:    data/dados_reais/FiltStep1_minQ10.0_minDP3_DPrange15-maxMeanDepth750_miss0.4_maf0.01_mac1_EMB_291701_SNPs_Raw.vcf.012.012
    Ignored:    data/dados_reais/FiltStep1_minQ10.0_minDP3_DPrange15-maxMeanDepth750_miss0.4_maf0.01_mac1_EMB_291701_SNPs_Raw.vcf.012.012.indv
    Ignored:    data/dados_reais/FiltStep1_minQ10.0_minDP3_DPrange15-maxMeanDepth750_miss0.4_maf0.01_mac1_EMB_291701_SNPs_Raw.vcf.012.012.pos
    Ignored:    data/dados_reais/FiltStep1_minQ10_minDP3_DPrange15-750_miss0.4_maf0.01_mac1_EMB_291701_filt1_snps_RAW.012.indv.txt
    Ignored:    data/dados_reais/FiltStep1_minQ10_minDP3_DPrange15-750_miss0.4_maf0.01_mac1_EMB_291701_filt1_snps_RAW.012.pos.txt
    Ignored:    data/dados_reais/FiltStep1_minQ10_minDP3_DPrange15-750_miss0.4_maf0.01_mac1_EMB_291701_filt1_snps_RAW.012.txt
    Ignored:    data/dados_reais/fpls-09-01934.pdf
    Ignored:    data/dados_reais/plants-13-01876-v2.pdf
    Ignored:    output/BLUPS_par_mmer.Rdata
    Ignored:    output/blups_all_wide.csv
    Ignored:    output/mean_pheno.csv
    Ignored:    output/real_results_consolidated_10r_3f.xlsx
    Ignored:    output/real_results_consolidated_5r_5f.xlsx
    Ignored:    output/result_sommer_pl_geracao_random.RDS
    Ignored:    output/result_sommer_random.RDS

Untracked files:
    Untracked:  data/dados_reais/geno_real.rds
    Untracked:  data/dados_reais/pheno_real.rds
    Untracked:  data/dados_reais/pos_geno_real.rds
    Untracked:  output/gwas_combined_results.rds
    Untracked:  output/gwas_results.rds
    Untracked:  output/importance_ML.rds
    Untracked:  output/results_cv_GBLUP_a.rds
    Untracked:  output/results_cv_GBLUP_ad.rds
    Untracked:  output/results_cv_GBLUP_ade.rds
    Untracked:  output/simulated_results_consolidated.xlsx

Unstaged changes:
    Modified:   analysis/_site.yml
    Modified:   analysis/gwas_dados_reais.Rmd
    Modified:   analysis/gwas_dados_simulados.Rmd
    Modified:   analysis/gws_dados_reais.Rmd
    Modified:   analysis/gws_dados_simulados.Rmd

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/gws_dados_simulados.Rmd) and HTML (docs/gws_dados_simulados.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd 60e67cf WevertonGomesCosta 2025-07-24 chance dados_simulados.Rmd to gws ans gwas_dados_simulados.Rmd

Bibliotecas

library(cvTools)
library(kableExtra)
library(parallel)
library(doParallel)
library(foreach)
library(sommer)
library(earth)
library(rpart)
library(randomForest)
library(gbm)
library(neuralnet)
library(ANN2)
library(tidyverse)
library(caret)

Carregamento dos Dados

Dados Fenotípicos

pheno <- read.table("data/dados_simulados/DG#gen_F2_Vfen.txt", header = FALSE) %>%
  rownames_to_column(var = "ID") %>%
  mutate(ID = as.factor(ID))

Dados Genotípicos

geno <- read.table("data/dados_simulados/genoma_mapa.txt", header = FALSE)
colnames(geno) <- 1:ncol(geno)
geno <- t(geno)

Preparação para Validação Cruzada

nfolds <- 5
nrept  <- 5
traits <- colnames(pheno)[-1]

set.seed(123)
# Alinhamento de IDs
pheno <- pheno[order(pheno$ID), ]
geno  <- geno[order(rownames(geno)), ]
stopifnot(all(rownames(geno) == as.character(pheno$ID)))
geno <- geno - 1

# Generating fold list
fold.list <- vector("list", length = nrept)
for (r in seq_len(nrept)) {
  folds <- cvFolds(
    n = nrow(pheno),
    K = nfolds,
    R = r,
    type = "random"
  )
  df <- cbind(folds$which, folds$subsets)
  fold.list[[r]] <- split(df[, 2], df[, 1])
}

1. G-BLUP

O modelo G-BLUP (Genomic Best Linear Unbiased Prediction) é uma abordagem amplamente utilizada para predição genômica, que considera tanto os efeitos aditivos quanto os efeitos de dominância dos marcadores genéticos. Neste estudo, implementamos três variantes do G-BLUP: Aditivo, Aditivo-Dominante e Aditivo-Dominante-Epistástico.

O modelo é implementado utilizando a função mmes do pacote sommer, que permite ajustar modelos mistos com estruturas de parentesco complexas. A validação cruzada é realizada para avaliar a acurácia preditiva do modelo.

1.1 G-BLUP Aditivo

Para o modelo G-BLUP aditivo, utilizamos a matriz de parentesco aditivo (K) calculada a partir dos dados genotípicos. Este modelo assume que os efeitos dos marcadores são puramente aditivos, sem considerar interações de dominância ou epistasia.

K <- A.mat(geno)
cl <- makeCluster(max(1, detectCores() - 1))
registerDoParallel(cl)

combos <- expand.grid(
  trait = traits,
  rep = seq_len(nrept),
  fold = seq_len(nfolds),
  stringsAsFactors = FALSE
)

results_cv_GBLUP_a <- foreach(
  idx = seq_len(nrow(combos)),
  .packages = c("sommer", "dplyr", "tibble"),
  .combine = bind_rows
) %dopar% {
  # Extração dos parâmetros do grid
  tr <- combos$trait[idx]
  r <- combos$rep[idx]
  f <- combos$fold[idx]
  
  # Seleção dos dados fenotípicos e matrizes de parentesco
  ph <- pheno[,c("ID", all_of(tr))]
  K1 <- K[ph$ID, ph$ID]
  td <- ph
  
  # Definição dos índices de validação cruzada
  val_idx <- fold.list[[r]][[f]]
  td[val_idx, tr] <- NA
  
  # Ajuste do modelo G-BLUP aditivo
  fit <- mmes(
    fixed = as.formula(paste(tr, "~ 1")),
    random = ~ vsm(ism(ID), Gu = K1),
    data = td,
    rcov = ~ units
  )
  
  # Predição e métricas
  pred <- data.frame(yhat = fit$u + fit$b[[1]], ph)
  
  # Cálculo dos GEBVs para treino e validação
  pred_T <- pred[!(pred$ID %in% val_idx), "yhat"]
  truth_T <- pred[[tr]][!(pred$ID %in% val_idx)]
  pred_V <- pred[pred$ID %in% val_idx, "yhat"]
  truth_V <- pred[[tr]][pred$ID %in% val_idx]
  
  # Criação do tibble com os resultados
  tibble(
    Trait = tr,
    Rep = r,
    Fold = f,
    R2_Train = round(cor(pred_T, truth_T), 4),
    R2_Valid = round(cor(pred_V, truth_V), 4),
    RMSE_Train = round(sqrt(mean((pred_T - truth_T)^2)), 4),
    RMSE_Valid = round(sqrt(mean((pred_V - truth_V)^2)), 4),
    GEBV_T = list(pred_T),
    GEBV_V = list(pred_V)
  )
}

stopCluster(cl)

saveRDS(results_cv_GBLUP_a, file = "output/results_cv_GBLUP_a.rds")

1.2 G-BLUP Aditivo-Dominante

Para o modelo G-BLUP aditivo-dominante, utilizamos a matriz de parentesco aditivo-dominante (K) que considera tanto os efeitos aditivos quanto os de dominância dos marcadores genéticos. Este modelo é mais complexo e pode capturar interações entre alelos.

K <- A.mat(geno)
D <- D.mat(geno)
cl <- makeCluster(max(1, detectCores() - 1))
registerDoParallel(cl)

combos_ad <- expand.grid(
  trait = traits,
  rep = seq_len(nrept),
  fold = seq_len(nfolds),
  stringsAsFactors = FALSE
)

results_cv_GBLUP_ad <- foreach(
  idx = seq_len(nrow(combos_ad)),
  .packages = c("sommer", "dplyr", "tibble"),
  .combine = bind_rows
) %dopar% {
  idx=1
  # Extração dos parâmetros do grid
  tr <- combos_ad$trait[idx]
  r <- combos_ad$rep[idx]
  f <- combos_ad$fold[idx]
  
  # Seleção dos dados fenotípicos e matrizes de parentesco
  ph <- pheno[,c("ID", all_of(tr))]
  K1 <- K[ph$ID, ph$ID]
  D1 <- D[ph$ID, ph$ID]
  
  # Criação dos IDs para os efeitos aditivo e dominante
  td <- ph
  td$IDD <- td$ID
  
  # Definição dos índices de validação cruzada
  val_idx <- fold.list[[r]][[f]]
  td[val_idx, tr] <- NA
  
  # Ajuste do modelo G-BLUP aditivo-dominante
  fit <- mmes(
    fixed = as.formula(paste(tr, "~ 1")),
    random = ~ vsm(ism(ID), Gu = K1) + vsm(ism(IDD), Gu = D1),
    data = td,
    rcov = ~ units
  )
  
  # Extração dos preditos e verdadeiros valores
  pred_a <- fit$uList$`vsm(ism(ID), Gu = K1`
  pred_d <- fit$uList$`vsm(ism(IDD), Gu = D1`
  
  # Soma dos preditos aditivos e dominantes
  pred <- pred_a + pred_d + fit$b[[1]]
  truth <- ph[[tr]]
  
  # Predição e métricas
  pred <- data.frame(pred, ph)
  
  # Cálculo dos GEBVs para treino e validação
  pred_T <- pred[-val_idx, "mu"]
  truth_T <- pred[[tr]][-val_idx]
  pred_V <- pred[val_idx, "mu"]
  truth_V <- pred[[tr]][val_idx]
  
  # Criação do tibble com os resultados
  tibble(
    Trait = tr,
    Rep = r,
    Fold = f,
    R2_Train = round(cor(pred_T, truth_T), 4),
    R2_Valid = round(cor(pred_V, truth_V), 4),
    RMSE_Train = round(sqrt(mean((pred_T - truth_T)^2)), 4),
    RMSE_Valid = round(sqrt(mean((pred_V - truth_V)^2)), 4),
    GEBV_T = list(pred_T),
    GEBV_V = list(pred_V)
  )
}

stopCluster(cl)

saveRDS(results_cv_GBLUP_ad, file = "output/results_cv_GBLUP_ad.rds")

1.3 G-BLUP Aditivo-Dominante-Epistástico

Para o modelo G-BLUP aditivo-dominante-epistástico, utilizamos a matriz de parentesco que inclui efeitos epistáticos. Este modelo é o mais complexo e pode capturar interações entre múltiplos marcadores.

K <- A.mat(geno)
D <- D.mat(geno)
E <- E.mat(geno)
cl <- makeCluster(max(1, detectCores() - 1))
registerDoParallel(cl)

combos_ade <- expand.grid(
  trait = traits,
  rep = seq_len(nrept),
  fold = seq_len(nfolds),
  stringsAsFactors = FALSE
)

results_cv_GBLUP_ade <- foreach(
  idx = seq_len(nrow(combos_ade)),
  .packages = c("sommer", "dplyr", "tibble"),
  .combine = bind_rows
) %dopar% {
  # Extração dos parâmetros do grid
  tr <- combos_ade$trait[idx]
  r <- combos_ade$rep[idx]
  f <- combos_ade$fold[idx]
  
  # Seleção dos dados fenotípicos e matrizes de parentesco
  ph <- pheno[,c("ID", all_of(tr))]
  K1 <- K[ph$ID, ph$ID]
  D1 <- D[ph$ID, ph$ID]
  E1 <- E[ph$ID, ph$ID]
  
  # Criação dos IDs para os efeitos aditivo, dominante e epistático 
  td <- ph
  td$IDD <- td$ID
  td$IDE <- td$ID
  
  # Definição dos índices de validação cruzada
  val_idx <- fold.list[[r]][[f]]
  td[val_idx, tr] <- NA
  
  # Ajuste do modelo G-BLUP aditivo-dominante-epistástico
  fit <- mmes(
    fixed = as.formula(paste(tr, "~ 1")),
    random = ~ vsm(ism(ID), Gu = K1) + vsm(ism(IDD), Gu = D1) + vsm(ism(IDE), Gu = E1),
    data = td,
    rcov = ~ units
  )
  
  # Extração dos preditos e verdadeiros valores
  pred_a <- fit$uList$`vsm(ism(ID), Gu = K1`
  pred_d <- fit$uList$`vsm(ism(IDD), Gu = D1`
  pred_e <- fit$uList$`vsm(ism(IDE), Gu = E1`
  
  # Soma dos preditos aditivos e dominantes
  pred <- pred_a + pred_d + pred_e + fit$b[[1]]
  truth <- ph[[tr]]
  
  # Predição e métricas
  pred <- data.frame(pred, ph)
  
  # Cálculo dos GEBVs para treino e validação
  pred_T <- pred[-val_idx, "mu"]
  truth_T <- pred[[tr]][-val_idx]
  pred_V <- pred[val_idx, "mu"]
  truth_V <- pred[[tr]][val_idx]
  
  # Criação do tibble com os resultados
  tibble(
    Trait = tr,
    Rep = r,
    Fold = f,
    R2_Train = round(cor(pred_T, truth_T), 4),
    R2_Valid = round(cor(pred_V, truth_V), 4),
    RMSE_Train = round(sqrt(mean((pred_T - truth_T)^2)), 4),
    RMSE_Valid = round(sqrt(mean((pred_V - truth_V)^2)), 4),
    GEBV_T = list(pred_T),
    GEBV_V = list(pred_V)
  )
}

stopCluster(cl)

saveRDS(results_cv_GBLUP_ade, file = "output/results_cv_GBLUP_ade.rds")

2. MARS

2.1 MARS 1

cl <- makeCluster(max(1, detectCores() - 1))
registerDoParallel(cl)

combos_mars <- expand.grid(
  trait = traits,
  rep = seq_len(nrept),
  fold = seq_len(nfolds),
  stringsAsFactors = FALSE
)

results_cv_MARS_1 <- foreach(
  idx = seq_len(nrow(combos_mars)),
  .packages = c("earth", "dplyr", "tibble"),
  .combine = bind_rows
) %dopar% {
  
  tr <- combos_mars$trait[idx]
  r <- combos_mars$rep[idx]
  f <- combos_mars$fold[idx]
  
  valid_idx <- fold.list[[r]][[f]]
  train_idx <- setdiff(seq_len(nrow(pheno)), valid_idx)
  
  yT <- pheno[train_idx, tr]
  xT <- geno[train_idx, ]
  yV <- pheno[valid_idx, tr]
  xV <- geno[valid_idx, ]
  
  fit <- earth(x = xT, y = yT, degree = 1)
  
  pred_T <- predict(fit, xT)
  pred_V <- predict(fit, xV)
  
  # Extrair importância das variáveis
  imp <- evimp(fit, trim = FALSE)
  
  # Seleciona colunas relevantes e converte para data.frame
  imp_df <- as.data.frame(imp[, c("rss", "nsubsets")])  # rss: Overall importance
  
  # Adiciona informações de repetição e fold, mantendo nomes dos marcadores
  imp_df$marker <- rownames(imp_df)
  imp_df$Rep <- r
  imp_df$Fold <- f
  
  # Ajusta nomes das colunas e remove sufixo indesejado dos marcadores
  imp_df <- imp_df %>%
    select(Overall = rss, marker, Rep, Fold) %>%
    mutate(marker = stringr::str_replace_all(marker, "-unused", ""))
   
  gc() 
  
  tibble(
    Trait = tr,
    Degree = 1,
    Rep = r,
    Fold = f,
    R2_Train = round(cor(pred_T, yT), 4),
    R2_Valid = round(cor(pred_V, yV), 4),
    RMSE_Train = round(sqrt(mean((pred_T - yT)^2)), 4),
    RMSE_Valid = round(sqrt(mean((pred_V - yV)^2)), 4),
    GEBV_T = list(pred_T),
    GEBV_V = list(pred_V),
    imp = list(imp_df)
  )
}

stopCluster(cl)

saveRDS(results_cv_MARS_1, file = "output/results_cv_MARS_1.rds")

2.2 MARS 2

cl <- makeCluster(max(1, detectCores() - 1))
registerDoParallel(cl)

combos_mars <- expand.grid(
  trait = traits,
  rep = seq_len(nrept),
  fold = seq_len(nfolds),
  stringsAsFactors = FALSE
)

results_cv_MARS_2 <- foreach(
  idx = seq_len(nrow(combos_mars)),
  .packages = c("earth", "dplyr", "tibble"),
  .combine = bind_rows
) %dopar% {
  
  tr <- combos_mars$trait[idx]
  r <- combos_mars$rep[idx]
  f <- combos_mars$fold[idx]
  
  valid_idx <- fold.list[[r]][[f]]
  train_idx <- setdiff(seq_len(nrow(pheno)), valid_idx)
  
  yT <- pheno[train_idx, tr]
  xT <- geno[train_idx, ]
  yV <- pheno[valid_idx, tr]
  xV <- geno[valid_idx, ]
  
  fit <- earth(x = xT, y = yT, degree = 2)
  
  pred_T <- predict(fit, xT)
  pred_V <- predict(fit, xV)
  
  # Extrair importância das variáveis
  imp <- evimp(fit, trim = FALSE)
  
  # Seleciona colunas relevantes e converte para data.frame
  imp_df <- as.data.frame(imp[, c("rss", "nsubsets")])  # rss: Overall importance
  
  # Adiciona informações de repetição e fold, mantendo nomes dos marcadores
  imp_df$marker <- rownames(imp_df)
  imp_df$Rep <- r
  imp_df$Fold <- f
  
  # Ajusta nomes das colunas e remove sufixo indesejado dos marcadores
  imp_df <- imp_df %>%
    select(Overall = rss, marker, Rep, Fold) %>%
    mutate(marker = stringr::str_replace_all(marker, "-unused", ""))
  
  gc()  
  
  tibble(
    Trait = tr,
    Degree = 2,
    Rep = r,
    Fold = f,
    R2_Train = round(cor(pred_T, yT), 4),
    R2_Valid = round(cor(pred_V, yV), 4),
    RMSE_Train = round(sqrt(mean((pred_T - yT)^2)), 4),
    RMSE_Valid = round(sqrt(mean((pred_V - yV)^2)), 4),
    GEBV_T = list(pred_T),
    GEBV_V = list(pred_V),
    imp = list(imp_df)
  )
}

stopCluster(cl)

saveRDS(results_cv_MARS_2, file = "output/results_cv_MARS_2.rds")

2.3 MARS 3

cl <- makeCluster(max(1, detectCores() - 1))
registerDoParallel(cl)

combos_mars <- expand.grid(
  trait = traits,
  rep = seq_len(nrept),
  fold = seq_len(nfolds),
  stringsAsFactors = FALSE
)

results_cv_MARS_3 <- foreach(
  idx = seq_len(nrow(combos_mars)),
  .packages = c("earth", "dplyr", "tibble"),
  .combine = bind_rows
) %dopar% {
  
  tr <- combos_mars$trait[idx]
  r <- combos_mars$rep[idx]
  f <- combos_mars$fold[idx]
  
  valid_idx <- fold.list[[r]][[f]]
  train_idx <- setdiff(seq_len(nrow(pheno)), valid_idx)
  
  yT <- pheno[train_idx, tr]
  xT <- geno[train_idx, ]
  yV <- pheno[valid_idx, tr]
  xV <- geno[valid_idx, ]
  
  fit <- earth(x = xT, y = yT, degree = 3)
  
  pred_T <- predict(fit, xT)
  pred_V <- predict(fit, xV)
  
  # Extrair importância das variáveis
  imp <- evimp(fit, trim = FALSE)
  
  # Seleciona colunas relevantes e converte para data.frame
  imp_df <- as.data.frame(imp[, c("rss", "nsubsets")])  # rss: Overall importance
  
  # Adiciona informações de repetição e fold, mantendo nomes dos marcadores
  imp_df$marker <- rownames(imp_df)
  imp_df$Rep <- r
  imp_df$Fold <- f
  
  # Ajusta nomes das colunas e remove sufixo indesejado dos marcadores
  imp_df <- imp_df %>%
    select(Overall = rss, marker, Rep, Fold) %>%
    mutate(marker = stringr::str_replace_all(marker, "-unused", ""))
  
  gc()  
  
  tibble(
    Trait = tr,
    Degree = 3,
    Rep = r,
    Fold = f,
    R2_Train = round(cor(pred_T, yT), 4),
    R2_Valid = round(cor(pred_V, yV), 4),
    RMSE_Train = round(sqrt(mean((pred_T - yT)^2)), 4),
    RMSE_Valid = round(sqrt(mean((pred_V - yV)^2)), 4),
    GEBV_T = list(pred_T),
    GEBV_V = list(pred_V),
    imp = list(imp_df)
  )
}

stopCluster(cl)

saveRDS(results_cv_MARS_3, file = "output/results_cv_MARS_3.rds")

3. Decision Tree

cl <- makeCluster(max(1, detectCores() - 1))
registerDoParallel(cl)

combos_dt <- expand.grid(
  trait = traits,
  rep = seq_len(nrept),
  fold = seq_len(nfolds),
  stringsAsFactors = FALSE
)

results_cv_DT <- foreach(
  idx = seq_len(nrow(combos_dt)),
  .packages = c("rpart", "dplyr", "tibble", "caret"),
  .combine = bind_rows
) %dopar% {
  tr <- combos_dt$trait[idx]
  r <- combos_dt$rep[idx]
  f <- combos_dt$fold[idx]
  
  valid_idx <- fold.list[[r]][[f]]
  train_idx <- setdiff(seq_len(nrow(pheno)), valid_idx)
  
  yT <- pheno[[tr]][train_idx]  # vetor
  xT <- data.frame(geno[train_idx, ])
  yV <- pheno[[tr]][valid_idx]
  xV <- data.frame(geno[valid_idx, ])
  
  fit <- rpart(yT ~ ., data = xT)
  
  pred_T <- predict(fit, xT)
  pred_V <- predict(fit, xV)
  
  imp_df <- data.frame(varImp(fit, scale = TRUE, value = "rss"))
  # Adiciona informações de repetição e fold, mantendo nomes dos marcadores
  imp_df$marker <- rownames(imp_df)
  imp_df$Rep <- r
  imp_df$Fold <- f
  
  gc()
  
  tibble(
    Trait = tr,
    Rep = r,
    Fold = f,
    R2_Train = round(cor(pred_T, yT), 3),
    R2_Valid = round(cor(pred_V, yV), 3),
    RMSE_Train = round(sqrt(mean((pred_T - yT)^2)), 3),
    RMSE_Valid = round(sqrt(mean((pred_V - yV)^2)), 3),
    GEBV_T = list(pred_T),
    GEBV_V = list(pred_V),
    imp = list(imp_df)
  )
}

stopCluster(cl)

saveRDS(results_cv_DT, file = "output/results_cv_DT.rds")

4. Bagging

cl <- makeCluster(max(1, detectCores() - 1))
registerDoParallel(cl)

combos_bag <- expand.grid(
  trait = traits,
  rep = seq_len(nrept),
  fold = seq_len(nfolds),
  stringsAsFactors = FALSE
)

results_cv_Bag <- foreach(
  idx = seq_len(nrow(combos_bag)),
  .packages = c("randomForest", "dplyr", "tibble", "caret"),
  .combine = bind_rows
) %dopar% {
  tr <- combos_bag$trait[idx]
  r <- combos_bag$rep[idx]
  f <- combos_bag$fold[idx]
  
  valid_idx <- fold.list[[r]][[f]]
  train_idx <- setdiff(seq_len(nrow(pheno)), valid_idx)
  
  yT <- pheno[[tr]][train_idx]  # vetor
  xT <- geno[train_idx, ]
  yV <- pheno[[tr]][valid_idx]
  xV <- geno[valid_idx, ]
  
  fit <- randomForest(x = xT, y = yT, mtry = ncol(xT))

  pred_T <- predict(fit, xT)
  pred_V <- predict(fit, xV)
  
  imp_df <- data.frame(varImp(fit, scale = TRUE, value = "rss"))
  # Adiciona informações de repetição e fold, mantendo nomes dos marcadores
  imp_df$marker <- rownames(imp_df)
  imp_df$Rep <- r
  imp_df$Fold <- f
  
  gc()
  
  tibble(
    Trait = tr,
    Rep = r,
    Fold = f,
    R2_Train = round(cor(pred_T, yT), 3),
    R2_Valid = round(cor(pred_V, yV), 3),
    RMSE_Train = round(sqrt(mean((pred_T - yT)^2)), 3),
    RMSE_Valid = round(sqrt(mean((pred_V - yV)^2)), 3),
    GEBV_T = list(pred_T),
    GEBV_V = list(pred_V),
    imp = list(imp_df)
  )
}

stopCluster(cl)

saveRDS(results_cv_Bag, file = "output/results_cv_Bag.rds")

5. Random Forest

cl <- makeCluster(max(1, detectCores() - 1))
registerDoParallel(cl)

combos_rf <- expand.grid(
  trait = traits,
  rep = seq_len(nrept),
  fold = seq_len(nfolds),
  stringsAsFactors = FALSE
)

results_cv_RF <- foreach(
  idx = seq_len(nrow(combos_rf)),
  .packages = c("randomForest", "dplyr", "tibble", "caret"),
  .combine = bind_rows
) %dopar% {
  tr <- combos_rf$trait[idx]
  r <- combos_rf$rep[idx]
  f <- combos_rf$fold[idx]
  
  valid_idx <- fold.list[[r]][[f]]
  train_idx <- setdiff(seq_len(nrow(pheno)), valid_idx)
  
  yT <- pheno[[tr]][train_idx]  # vetor
  xT <- geno[train_idx, ]
  yV <- pheno[[tr]][valid_idx]
  xV <- geno[valid_idx, ]
  
  fit <- randomForest(xT, yT, mtry = floor(ncol(xT) / 3), ntree = 500)
  
  pred_T <- predict(fit, xT)
  pred_V <- predict(fit, xV)
  
  imp_df <- data.frame(varImp(fit, scale = TRUE, value = "rss"))
  # Adiciona informações de repetição e fold, mantendo nomes dos marcadores
  imp_df$marker <- rownames(imp_df)
  imp_df$Rep <- r
  imp_df$Fold <- f
  
  gc()
  
  tibble(
    Trait = tr,
    Rep = r,
    Fold = f,
    R2_Train = round(cor(pred_T, yT), 3),
    R2_Valid = round(cor(pred_V, yV), 3),
    RMSE_Train = round(sqrt(mean((pred_T - yT)^2)), 3),
    RMSE_Valid = round(sqrt(mean((pred_V - yV)^2)), 3),
    GEBV_T = list(pred_T),
    GEBV_V = list(pred_V),
    imp = list(imp_df)
  )
}

stopCluster(cl)

saveRDS(results_cv_RF, file = "output/results_cv_RF.rds")

6. Boosting (GBM)

cl <- makeCluster(max(1, detectCores() - 1))
registerDoParallel(cl)

combos_gbm <- expand.grid(
  trait = traits,
  rep = seq_len(nrept),
  fold = seq_len(nfolds),
  stringsAsFactors = FALSE
)

results_cv_GBM <- foreach(
  idx = seq_len(nrow(combos_gbm)),
  .packages = c("gbm", "dplyr", "tibble", "caret"),
  .combine = bind_rows
) %dopar% {
  tr <- combos_gbm$trait[idx]
  r <- combos_gbm$rep[idx]
  f <- combos_gbm$fold[idx]
  
  valid_idx <- fold.list[[r]][[f]]
  train_idx <- setdiff(seq_len(nrow(pheno)), valid_idx)
  
  yT <- pheno[[tr]][train_idx]  # vetor
  xT <- geno[train_idx, ]
  yV <- pheno[[tr]][valid_idx]
  xV <- geno[valid_idx, ]
  
  fit <- gbm(
    yT ~ .,
    data = data.frame(yT, xT),
    distribution = "gaussian",
    n.trees = 500,
    interaction.depth = 2
  )
  
  pred_T <- predict(fit, data.frame(xT), n.trees = 500)
  pred_V <- predict(fit, data.frame(xV), n.trees = 500)
  
  imp_df <- data.frame(varImp(fit, scale = TRUE, value = "rss" , numTrees  = 500))
  # Adiciona informações de repetição e fold, mantendo nomes dos marcadores
  imp_df$marker <- rownames(imp_df)
  imp_df$Rep <- r
  imp_df$Fold <- f
  
  gc()
  
  tibble(
    Trait = tr,
    Rep = r,
    Fold = f,
    R2_Train = round(cor(pred_T, yT), 3),
    R2_Valid = round(cor(pred_V, yV), 3),
    RMSE_Train = round(sqrt(mean((pred_T - yT)^2)), 3),
    RMSE_Valid = round(sqrt(mean((pred_V - yV)^2)), 3),
    GEBV_T = list(pred_T),
    GEBV_V = list(pred_V),
    imp = list(imp_df)
  )
}

stopCluster(cl)

saveRDS(results_cv_GBM, file = "output/results_cv_GBM.rds")

7. Perceptron Multicamadas (PMC)

cl <- makeCluster(max(1, detectCores() - 1))
registerDoParallel(cl)

combos_nn <- expand.grid(
  trait = traits,
  rep = seq_len(nrept),
  fold = seq_len(nfolds),
  h1 = c(1, 2, 4, 8, 16, 32),
  h2 = c(0, 1, 2, 4, 8, 16, 32),
  stringsAsFactors = FALSE
)


results_cv_NN <- foreach(
  idx = seq_len(nrow(combos_nn)),
  .packages = c("ANN2", "neuralnet", "dplyr", "tibble"),
  .combine = bind_rows
) %dopar% {

  tr <- combos_nn$trait[idx]
  r <- combos_nn$rep[idx]
  f <- combos_nn$fold[idx]
  h1 <- combos_nn$h1[idx]
  h2 <- combos_nn$h2[idx]
  
  hidden.layers <- case_when(h2 != 0 ~ c(h1, h2),
                             TRUE ~ h1)
  
  valid_idx <- fold.list[[r]][[f]]
  train_idx <- setdiff(seq_len(nrow(pheno)), valid_idx)
  
  yT <- pheno[[tr]][train_idx]  # vetor
  xT <- geno[train_idx, ]
  yV <- pheno[[tr]][valid_idx]
  xV <- geno[valid_idx, ]
  
  # Construção e Treinamento da Rede Neural
  NN <- neuralnetwork(
    X = xT,
    y = yT,
    hidden.layers = hidden.layers,
    regression = TRUE,
    activ.functions = "relu",
    n.epochs = 500,
    loss.type = "squared",
    val.prop = 0
  )
  
  pred_T <- predict(NN, xT)$predictions
  pred_V <- predict(NN, xV)$predictions
  
  tibble(
    Trait = tr,
    Rep = r,
    Fold = f,
    Hidden_Layers_1 = h1,
    Hidden_Layers_2 = h2,
    R2_Train = round(cor(pred_T, yT), 3),
    R2_Valid = round(cor(pred_V, yV), 3),
    RMSE_Train = round(sqrt(mean((pred_T - yT)^2)), 3),
    RMSE_Valid = round(sqrt(mean((pred_V - yV)^2)), 3),
    GEBV_T = list(pred_T),
    GEBV_V = list(pred_V)
  )
}

stopCluster(cl)

saveRDS(results_cv_NN, file = "output/results_cv_NN.rds")

Resultados Consolidados

# Carregar resultados
results_cv_GBLUP_a <- readRDS("output/results_cv_GBLUP_a.rds")
results_cv_GBLUP_ad <- readRDS("output/results_cv_GBLUP_ad.rds")
results_cv_GBLUP_ade <- readRDS("output/results_cv_GBLUP_ade.rds")
results_cv_MARS_1 <- readRDS("output/results_cv_MARS_1.rds")
results_cv_MARS_2 <- readRDS("output/results_cv_MARS_2.rds")
results_cv_MARS_3 <- readRDS("output/results_cv_MARS_3.rds")
results_cv_DT <- readRDS("output/results_cv_DT.rds")
results_cv_Bag <- readRDS("output/results_cv_Bag.rds")
results_cv_RF <- readRDS("output/results_cv_RF.rds")
results_cv_GBM <- readRDS("output/results_cv_GBM.rds")
results_cv_NN <- readRDS("output/results_cv_NN.rds")
  

# Agrupa por Trait e configuração de neurônios
resumo_nn <- results_cv_NN %>%
  group_by(Trait, Hidden_Layers_1, Hidden_Layers_2) %>%
  summarise(
    R2_Valid_Mean   = mean(R2_Valid, na.rm = TRUE),
    R2_Train_Mean   = mean(R2_Train, na.rm = TRUE),
    RMSE_Valid_Mean = mean(RMSE_Valid, na.rm = TRUE),
    RMSE_Train_Mean = mean(RMSE_Train, na.rm = TRUE),
    R2_Valid_SD     = sd(R2_Valid, na.rm = TRUE),
    R2_Train_SD     = sd(R2_Train, na.rm = TRUE),
    RMSE_Valid_SD   = sd(RMSE_Valid, na.rm = TRUE),
    RMSE_Train_SD   = sd(RMSE_Train, na.rm = TRUE),
    .groups = "drop"
  )

# Exibe os melhores por característica com base no maior R²_Valid
melhores_config_por_trait <- resumo_nn %>%
  group_by(Trait) %>%
  slice_max(order_by = R2_Valid_Mean, n = 1) %>%
  arrange(Trait)

print(melhores_config_por_trait)
# A tibble: 6 × 11
# Groups:   Trait [6]
  Trait Hidden_Layers_1 Hidden_Layers_2 R2_Valid_Mean R2_Train_Mean
  <chr>           <dbl>           <dbl>         <dbl>         <dbl>
1 V1                 32              32         0.438         1    
2 V2                 32              32         0.537         1    
3 V3                 32               2         0.457         0.951
4 V4                 32               0         0.444         1    
5 V5                  1               2         0.322         0.801
6 V6                 16               2         0.306         0.933
# ℹ 6 more variables: RMSE_Valid_Mean <dbl>, RMSE_Train_Mean <dbl>,
#   R2_Valid_SD <dbl>, R2_Train_SD <dbl>, RMSE_Valid_SD <dbl>,
#   RMSE_Train_SD <dbl>
# Adicionar coluna Method e combinar todos
combined_results <- bind_rows(
  results_cv_GBLUP_a  %>% mutate(Method = "GBLUP_a"),
  results_cv_GBLUP_ad %>% mutate(Method = "GBLUP_ad"),
  results_cv_GBLUP_ade %>% mutate(Method = "GBLUP_ade"),
  results_cv_MARS_1   %>% mutate(Method = "MARS_1"),
  results_cv_MARS_2   %>% mutate(Method = "MARS_2"),
  results_cv_MARS_3   %>% mutate(Method = "MARS_3"),
  results_cv_DT     %>% mutate(Method = "DT"),
  results_cv_Bag    %>% mutate(Method = "BAG"),
  results_cv_RF     %>% mutate(Method = "RF"),
  results_cv_GBM    %>% mutate(Method = "GBM")
)


# Resumir por Method e Trait
table_final <- combined_results %>%
  group_by(Method, Trait) %>%
  summarise(
    R2_Valid_Mean   = mean(R2_Valid, na.rm = TRUE),
    R2_Valid_SD     = sd(R2_Valid, na.rm = TRUE),
    RMSE_Valid_Mean = mean(RMSE_Valid, na.rm = TRUE),
    RMSE_Valid_SD   = sd(RMSE_Valid, na.rm = TRUE)
  ) %>%
  ungroup() %>% 
  bind_rows(
    melhores_config_por_trait %>%
      mutate(Method = "NN") %>%
      dplyr::select(Method, Trait, R2_Valid_Mean, R2_Valid_SD, RMSE_Valid_Mean, RMSE_Valid_SD)
  )
`summarise()` has grouped output by 'Method'. You can override using the
`.groups` argument.
# Exibir tabela consolidada
table_final %>%
  arrange(Trait, Method) %>%
  mutate_if(is.numeric, round, 4) %>%
  kable(booktabs = TRUE, caption = "Resultados Consolidados por Método e Traço") %>%
  kable_styling(full_width = FALSE)
Resultados Consolidados por Método e Traço
Method Trait R2_Valid_Mean R2_Valid_SD RMSE_Valid_Mean RMSE_Valid_SD
BAG V1 0.7437 0.0354 1.5453 0.0972
DT V1 0.6573 0.0435 1.7373 0.0938
GBLUP_a V1 0.6401 0.0337 1.7784 0.0752
GBLUP_ad V1 0.6327 0.0000 1.8537 0.0000
GBLUP_ade V1 0.6118 0.0289 1.8123 0.0798
GBM V1 0.7209 0.0230 1.5889 0.0641
MARS_1 V1 0.6571 0.0290 1.7327 0.0746
MARS_2 V1 0.7653 0.0202 1.4861 0.0642
MARS_3 V1 0.6712 0.0314 1.8404 0.1095
NN V1 0.4380 0.0441 2.2661 0.1023
RF V1 0.7444 0.0346 1.5447 0.0953
BAG V2 0.6656 0.0345 0.8482 0.0464
DT V2 0.3090 0.0465 1.0910 0.0494
GBLUP_a V2 0.7164 0.0445 0.7513 0.0485
GBLUP_ade V2 0.6716 0.0269 0.7966 0.0376
GBM V2 0.6910 0.0268 0.7790 0.0431
MARS_1 V2 0.4746 0.0456 0.9599 0.0464
MARS_2 V2 0.5368 0.0529 0.9383 0.0573
MARS_3 V2 0.4912 0.0550 1.0852 0.0867
NN V2 0.5372 0.0422 0.9836 0.0422
RF V2 0.6672 0.0329 0.8480 0.0485
BAG V3 0.5750 0.0504 0.7896 0.0382
DT V3 0.2526 0.0653 0.9650 0.0344
GBLUP_a V3 0.6668 0.0284 0.6989 0.0269
GBLUP_ade V3 0.5966 0.0484 0.7508 0.0314
GBM V3 0.5481 0.0527 0.7924 0.0294
MARS_1 V3 0.4095 0.0595 0.8683 0.0348
MARS_2 V3 0.4151 0.0640 0.8962 0.0443
MARS_3 V3 0.3782 0.0599 1.0304 0.0640
NN V3 0.4574 0.0614 0.9127 0.0534
RF V3 0.5789 0.0525 0.7879 0.0376
BAG V4 0.5753 0.0445 0.7185 0.0253
DT V4 0.2824 0.0650 0.8685 0.0376
GBLUP_a V4 0.6588 0.0439 0.6422 0.0291
GBLUP_ade V4 0.5962 0.0318 0.6854 0.0238
GBM V4 0.5524 0.0307 0.7214 0.0237
MARS_1 V4 0.4330 0.0422 0.7812 0.0265
MARS_2 V4 0.4319 0.0592 0.8072 0.0326
MARS_3 V4 0.3684 0.0523 0.9553 0.0462
NN V4 0.4437 0.0462 0.8460 0.0346
RF V4 0.5789 0.0398 0.7178 0.0259
BAG V5 0.4299 0.0400 0.7695 0.0352
DT V5 0.1408 0.0586 0.9162 0.0427
GBLUP_a V5 0.5617 0.0335 0.7021 0.0312
GBLUP_ade V5 0.4657 0.0358 0.7491 0.0356
GBM V5 0.3892 0.0548 0.8036 0.0419
MARS_1 V5 0.3223 0.0426 0.8182 0.0360
MARS_2 V5 0.2701 0.0714 0.8772 0.0564
MARS_3 V5 0.2433 0.0738 1.0260 0.0702
NN V5 0.3215 0.0676 0.8936 0.0624
RF V5 0.4356 0.0367 0.7677 0.0346
BAG V6 0.4604 0.0395 0.6582 0.0206
DT V6 0.2557 0.0619 0.7519 0.0285
GBLUP_a V6 0.5565 0.0382 0.6125 0.0232
GBLUP_ade V6 0.4741 0.0354 0.6484 0.0192
GBM V6 0.4062 0.0334 0.6927 0.0205
MARS_1 V6 0.3615 0.0443 0.6994 0.0230
MARS_2 V6 0.3334 0.0544 0.7352 0.0266
MARS_3 V6 0.2519 0.0697 0.8841 0.0508
NN V6 0.3064 0.0698 0.8151 0.0481
RF V6 0.4640 0.0355 0.6572 0.0191
# Salvar tabela consolidada
writexl::write_xlsx(table_final, "output/simulated_results_consolidated.xlsx")

sessionInfo()
R version 4.4.1 (2024-06-14 ucrt)
Platform: x86_64-w64-mingw32/x64
Running under: Windows 11 x64 (build 26100)

Matrix products: default


locale:
[1] LC_COLLATE=Portuguese_Brazil.utf8  LC_CTYPE=Portuguese_Brazil.utf8   
[3] LC_MONETARY=Portuguese_Brazil.utf8 LC_NUMERIC=C                      
[5] LC_TIME=Portuguese_Brazil.utf8    

time zone: America/Sao_Paulo
tzcode source: internal

attached base packages:
[1] parallel  stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
 [1] caret_7.0-1          lubridate_1.9.4      forcats_1.0.0       
 [4] stringr_1.5.1        dplyr_1.1.4          purrr_1.1.0         
 [7] readr_2.1.5          tidyr_1.3.1          tibble_3.3.0        
[10] ggplot2_3.5.2        tidyverse_2.0.0      ANN2_2.3.4          
[13] neuralnet_1.44.2     gbm_2.2.2            randomForest_4.7-1.2
[16] rpart_4.1.23         earth_5.3.4          plotmo_3.6.4        
[19] plotrix_3.8-4        Formula_1.2-5        sommer_4.4.2        
[22] crayon_1.5.3         MASS_7.3-60.2        Matrix_1.7-0        
[25] doParallel_1.0.17    iterators_1.0.14     foreach_1.5.2       
[28] kableExtra_1.4.0     cvTools_0.3.3        robustbase_0.99-4-1 
[31] lattice_0.22-7      

loaded via a namespace (and not attached):
 [1] pROC_1.18.5          writexl_1.5.4        rlang_1.1.6         
 [4] magrittr_2.0.3       git2r_0.36.2         compiler_4.4.1      
 [7] systemfonts_1.2.3    vctrs_0.6.5          reshape2_1.4.4      
[10] pkgconfig_2.0.3      fastmap_1.2.0        utf8_1.2.6          
[13] promises_1.3.3       rmarkdown_2.29       prodlim_2025.04.28  
[16] tzdb_0.5.0           xfun_0.52            cachem_1.1.0        
[19] jsonlite_2.0.0       recipes_1.3.1        later_1.4.2         
[22] R6_2.6.1             bslib_0.9.0          stringi_1.8.7       
[25] RColorBrewer_1.1-3   parallelly_1.45.0    jquerylib_0.1.4     
[28] Rcpp_1.1.0           knitr_1.50           future.apply_1.20.0 
[31] httpuv_1.6.16        splines_4.4.1        nnet_7.3-19         
[34] timechange_0.3.0     tidyselect_1.2.1     rstudioapi_0.17.1   
[37] yaml_2.3.10          timeDate_4041.110    codetools_0.2-20    
[40] listenv_0.9.1        plyr_1.8.9           withr_3.0.2         
[43] evaluate_1.0.4       future_1.58.0        survival_3.6-4      
[46] xml2_1.3.8           pillar_1.11.0        whisker_0.4.1       
[49] stats4_4.4.1         generics_0.1.4       rprojroot_2.0.4     
[52] hms_1.1.3            scales_1.4.0         globals_0.18.0      
[55] class_7.3-22         glue_1.8.0           tools_4.4.1         
[58] data.table_1.17.8    ModelMetrics_1.2.2.2 gower_1.0.2         
[61] fs_1.6.6             grid_4.4.1           ipred_0.9-15        
[64] nlme_3.1-168         cli_3.6.5            textshaping_1.0.1   
[67] workflowr_1.7.1      viridisLite_0.4.2    svglite_2.2.1       
[70] lava_1.8.1           gtable_0.3.6         DEoptimR_1.1-3-1    
[73] sass_0.4.10          digest_0.6.37        farver_2.1.2        
[76] htmltools_0.5.8.1    lifecycle_1.0.4      hardhat_1.4.1       

  1. Weverton Gomes da Costa, Pós-Doutorando, Departamento de Estatística - Universidade Federal de Viçosa, ↩︎