The GA
package maximize the fitness function in nature. I understand that for minization problem using GA
, you will need to multiply your fitness with -1 in your fitness function.
##calling the ga() function
my_ga <- ga(...)
When plotting the graph (plot(my_ga)
) for a minimization problem, I got a graph which shows a maximization pattern:
I tried to reverse the y-axis by the changing the ylim
in plot()
and I got this (which is something I wanted, except for the negative y-axis):
## explicitly defining the y-axis
x <- seq(1.1,1.4, 0.05)
plot(my_ga, ylim=rev(range(-x)))
But I don't find this approach efficient at all, is there a faster way - which to change the y-axis to positive and implicitly determining the range, to plot minimization graph using the GA
package?
btw, just ignore the poor convergence in this example
[EDIT] - added source code
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)