【发布时间】:2019-06-25 00:07:20
【问题描述】:
我正在编写一个遗传算法 (GA),以在我的社交网络数据(一个 iGraph 对象)中找到某种排列。我正在使用 R 库 GA,但它生成的排列包含重复且它们的长度各不相同,而我想要没有重复且长度相同的排列。
我知道突变和交叉函数会导致这种现象,但我找不到解决方法。我试图实现一个适应度函数,它对“坏”排列给出低分,但这会导致错误(见下文)。
cp_GA <- function(g, ratio = 0.2, maxiter = 1000, run = 40, pop = 200) {
library("igraph")
library("GA")
# ratio : ratio of the number of core/all vertices
# this is describing the desired size of the core group
# maxiter: max number of iterations for the GA
# run : max number of runs with the same fitness
# pop : population size for tha GA
# desired core size:
coresize <- round(vcount(g) * ratio, 0)
fitness_vertex_perm <- function(permutation) {
# this is the fitness function for the GA
# it calculates the density of the core with the current permutation
# the if-else structure prevents permutations with repetitions
if (sort(permutation) == c(1:vcount(g))) {
dens <- edge_density(
induced_subgraph(permute(g, as.numeric(permutation)), 1:coresize, impl =
"auto"))
} else {
dens <- 0
}
return(dens)
}
lowerlimit <- 1:vcount(g)
upperlimit <- vcount(g):1
hint <- order(degree(g), decreasing = TRUE)
maxfitness <- 1
GA <- ga(type = "permutation",
fitness = fitness_vertex_perm,
lower = lowerlimit,
upper = upperlimit,
maxiter = maxiter,
run = run,
maxFitness = maxfitness,
suggestions = hint,
popSize = pop
)
return(GA)
}
在上面的适应度函数中,if else 语句检查排列是否正常,但这会抛出一个错误:
testresult <- cp_GA(g, ratio = 0.13, maxiter = 1000, run = 60, pop = 400)
Error in getComplete(control) :
argument "control" is missing, with no default
In addition: Warning message:
In if (sort(permutation) == c(1:vcount(g))) { :
Error in getComplete(control) :
argument "control" is missing, with no default
如果没有 if-else,它会运行,但会产生对我没有用的排列结果。
如何设置 GA 以生成正确类型的排列?
【问题讨论】:
标签: r igraph genetic-algorithm