r GA与R

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了r GA与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)

以上是关于r GA与R的主要内容,如果未能解决你的问题,请参考以下文章

马尔科夫决策过程

用R语言实现遗传算法

R语言-数据透视表

如何使用带有R的遗传算法优化支持向量机的参数

将代码从基数R转换为dplyr,特别是添加变量

将 bigquery JSON 数据转储加载到 R tibble