在GA

时间:2017-03-23 15:29:46

标签: r plot genetic-algorithm

GA套餐最大限度地提升了健身功能。我理解,对于使用GA的缩小问题,您需要在健身功能中将您的适应度乘以-1。

##calling the ga() function
my_ga <- ga(...)

在绘制最小化问题的图形(plot(my_ga))时,我得到了一个显示最大化模式的图表:

which shows a maximization process

我试图通过更改ylim中的plot()来反转y轴,我得到了这个(这是我想要的,除了负y轴):

## explicitly defining the y-axis
x <- seq(1.1,1.4, 0.05)
plot(my_ga, ylim=rev(range(-x)))

enter image description here

但是我根本没有发现这种方法有效,是否有更快的方法 - 将y轴更改为正并隐式确定范围,使用GA包绘制最小化图?

btw,请忽略此示例中的不良收敛

[编辑] - 添加了源代码

library(clusterSim)
library(GA)

## data
data(data_ratio)
dataset2 <- data_ratio

## fitness function
DBI2 <- function(x) {
        cl <- kmeans(dataset2, centers = dataset2[x==1, ])
        dbi <- index.DB(dataset2, cl=cl$cluster, centrotypes = "centroids")
        score <- -dbi$DB  

        return(score)  

}

k_min <- 5

## initialization of populaton
initial_population <- function(object) {
        init <- t(replicate(object@popSize, sample(rep(c(1, 0), c(k_min, object@nBits - k_min))), TRUE))
        return(init)
}

## mutation operator
my_mutation <- function(object, parent){

        pop <- parent <- as.vector(object@population[parent, ])
        difference <- abs(sum(pop) - k_min)
        ## checking condition where there are more cluster being turned on than k_min
        if(sum(pop) > k_min){
                ## determine position of 1's
                bit_position_1 <- sample(which(pop==1), difference)
                ## bit inversion
                for(i in 1:length(bit_position_1)){
                        pop[bit_position_1[i]] <- abs(pop[bit_position_1[i]] - 1)
                } 
        } else if (sum(pop) < k_min){
                ## determine position of 0's
                bit_position_0 <- sample(which(pop==0), difference)
                ## bit inversion
                for(i in 1:length(bit_position_0)){
                        pop[bit_position_0[i]] <- abs(pop[bit_position_0[i]] - 1)
                }

        } 

        return(pop)
}

my_ga<- ga(type = "binary", 
        population = initial_population, 
        fitness = DBI2, 
        selection = ga_rwSelection,
        crossover = gabin_spCrossover,
        mutation = my_mutation,
        pcrossover = 0.8,
        pmutation = 1.0,
        popSize = 100, 
        maxiter = 100,
        seed = 212,
        nBits = nrow(dataset2))


plot(my_ga)

1 个答案:

答案 0 :(得分:3)

好吧,我们可以通过翻转对象本身中数据的符号来作弊。这是一个帮助函数来做到这一点

flip_ga_y <- function(x) {
    x@summary <- x@summary*-1
    x
}

然后您可以绘制样本数据,如

plot(flip_ga_y(my_ga), ylim=c(1.1,1.4))

请注意,您必须指定ylim,因为该功能会对标志的方向做出一些强有力的选择。但是这会返回

enter image description here