Genetic Algorithms to learn a Bayesian Networks Structure

This is my code using GA to learn a Bayesian network structure. library('bnlearn') library('genalg') source('adj.remove.cycles.R') N_NODES = 6 evalFunc = function(x_vec){ learning.net = empty.graph(LETTERS[1:N_NODES]) x = matrix(x_vec,ncol = 6, nrow = 6,            dimnames = list(LETTERS[1:N_NODES], LETTERS[1:N_NODES])) for (i in c(1:N_NODES)){ x[i,i]=0L } x_removed = adj.remove.cycles(x, maxlength=N_NODES) x_removed_mat = x_removed$adjmat.acyclic amat(learning.net) = x_removed_mat learning.net=pdag2dag(learning.net, ordering = c("A", "B", "C", "D", "E", "F")) return(-score(learning.net, learning.test,type = "k2")) #Higher score is better } getBestSolution = function(summary_string){ s_split = unlist(strsplit(summary_string,'\n')) s1 = s_split[13] s1_split = unlist(strsplit(s1,': ')) s2 = s1_split[2] numbas =as.numeric( scan(textConnection(s2), what="",sep=" ") ) final_matrix_vec = numbas[!is.na(numbas)] final_matrix = matrix(final_matrix_vec,ncol = 6, nrow = 6,                            dimnames = list(LETTERS[1:6], LETTERS[1:6])) for (j in c(1:6)){ final_matrix[j,j]=0L }   return(final_matrix) } data(learning.test) adj = matrix(0L, ncol = 6, nrow = 6,            dimnames = list(LETTERS[1:6], LETTERS[1:6])) adj["A", "B"] = 1L adj["B", "E"] = 1L learning.net = empty.graph(LETTERS[1:N_NODES]) amat(learning.net) = adj png('./k2/initial_graph.png') plot(learning.net) dev.off adj_vec = as.vector(adj) chromosome = adj_vec all_iters = c(1,3) for (iter in all_iters){ GAmodel <- rbga.bin(size = 36, popSize = 50, iters = iter, mutationChance = 0.2,                    elitism = T, evalFunc = evalFunc) final_matrix = getBestSolution(summary.rbga(GAmodel)) learning.net = empty.graph(LETTERS[1:N_NODES]) amat(learning.net) = final_matrix learning.net = pdag2dag(learning.net, ordering = c("A", "B", "C", "D", "E", "F")) iter_title = paste('Iteration=',toString(iter),sep="") png(paste('./k2/',iter_title,'.png',sep="")) plot(learning.net,main=iter_title) dev.off } png(paste('./k2/',"Best Evaluation Score",'.png',sep="")) plot(1:iter,GAmodel$best,main="Best Evaluation Score") dev.off png(paste('./k2/',"Average Evaluation Score",'.png',sep="")) plot(1:iter,GAmodel$mean,main='Average Evaluation Score') dev.off fit = bn.fit(learning.net, learning.test) fit bn.fit.barchart(fit$A) pred = predict(fit$D,learning.test) table(pred,learning.test[,"D"]) The adj.remove.cycles.R is used to remove cycles in adjacency matrix, which I obtained in https://github.com/bhaibeka/predictionet/blob/master/R/adj.remove.cycles.R
 * 1) Initialization
 * 1) Initialization
 * 1) all_iters = c(1,3,5,7,9,11,13,15,17,19,21,25,30,35,100)