Skip to content

Instantly share code, notes, and snippets.

@HTLife
Created May 8, 2018 04:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HTLife/e1a887aa125be68ad184c2eacdeec935 to your computer and use it in GitHub Desktop.
Save HTLife/e1a887aa125be68ad184c2eacdeec935 to your computer and use it in GitHub Desktop.
GA with R
#R version 3.3.2
set.seed(10)
N_size = 20
N_bit = 8
Gen = 50
mut_freq = 0.1
Population = matrix(sample(c(0,1), size=N_size*N_bit, replace=TRUE), N_size, N_bit)
fit = function(input) {
return (-input^2 + 14*input + 50 )
}
PoValue = function(input) {
Po_value = 8*input[,2] +
4*input[,3] +
2*input[,4] +
1*input[,5] +
1/2*input[,6] +
1/4*input[,7] +
1/8*input[,8]
for (i in 1:N_size) {
if (input[i,1] == 1) {
Po_value[i] = Po_value[i] * -1
}
}
return (Po_value)
}
Po_value = PoValue(Population)
fit_value = fit(Po_value)
idx = 1:N_size
max_Gen_value = rep(0, Gen)
max_Gen_value[1] = max(fit_value)
max_Gen_ind = matrix(0, Gen, N_bit)
max_Gen_ind[1,] = Population[which(fit_value == max(fit_value))[1],]
max_Gen_Po_value = rep(0, Gen)
max_Gen_Po_value[1] = Po_value[which(fit_value == max(fit_value))[1]]
for (now_Gen in 2:Gen) {
child = matrix(0, N_size, N_bit)
child[1,] = Population[which(fit_value == max(fit_value))[1],]
switch_bit = sample(N_bit, 1)
child[2,] = child[1,]
child[2, switch_bit:N_bit] = !child[2, switch_bit:N_bit]
child_size = 2
total_wheel = sum(fit_value)
select_frequency = abs(fit_value / total_wheel)
while (child_size < N_size) {
P_idx = sample(idx, size=2, replace=F, prob=select_frequency)
P1 = Population[P_idx[1],]
P2 = Population[P_idx[2],]
switch_bit = sample(N_bit, 1)
P1_new = P1
P1_new[switch_bit:N_bit] = P2[switch_bit:N_bit]
P2_new = P2
P2_new[switch_bit:N_bit] = P1[switch_bit:N_bit]
if (runif(1,0,1) < mut_freq) {
tar_bit = sample(N_bit, 1)
P1_new[tar_bit] = !P1_new[tar_bit]
}
if (runif(1,0,1) < mut_freq) {
tar_bit = sample(N_bit, 1)
P2_new[tar_bit] = !P2_new[tar_bit]
}
child[child_size + 1, ] = P1_new
child[child_size + 2, ] = P2_new
child_size = child_size + 2
}
Population = child
Po_value = PoValue(Population)
fit_value = fit(Po_value)
max_Gen_value[now_Gen] = max(fit_value)
max_Gen_Po_value[now_Gen] = Po_value[which(fit_value == max(fit_value))[1]]
max_Gen_ind[now_Gen,] = Population[which(fit_value == max(fit_value))[1],]
}
print(max_Gen_ind)
print(max_Gen_Po_value)
print(max_Gen_value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment