错误:数值表达式包含6个元素:仅第一个使用,GA中的警告

问题描述 投票:0回答:1

这是我的代码,我想知道为什么会有警告消息说“要更换的物品数量不是更换长度的倍数”?

    library(GA)
    library(readxl)
    > data1 <- 
    read_excel("C:/Users/nadiahalim/OneDrive/CS954/Scheduling/data1.xlsx")
    > View(data1)
    > data1

数据1的输出

# A tibble: 6 x 4
   Jobj    Pj    Dj    Wj
  <dbl> <dbl> <dbl> <dbl>
1     1    25    61     3
2     2     7   102     7
3     3    42    86     1
4     4    36    44     3
5     5    18   150     1
6     6    29   134     4

我想重新排序Jobj,以使它给出由Cj表示的最短完成时间。我的代码中使用了For循环,如下所示:

Cj=0
i<- sample(data1$Jobj)
for(i in 1:i){
fitness <-function(j){
for(j in data1$Jobj){
Cj[j] <- data1$Pj[j]+sum(Cj[j-1])
}
print(Cj)
}
fitness()

此代码的输出

numerical expression has 6 elements: only the first used[1]  25  32  74 110 128 157
[1]  25  32  74 110 128 157
[1]  25  32  74 110 128 157
[1]  25  32  74 110 128 157
[1]  25  32  74 110 128 157

然后,我为GA代码运行:

GA <- ga(type = "permutation", fitness = fitness, lower = 1, upper = 6, maxiter= 5, run = 20, optim = TRUE)

GA的输出如下,并且警告指出要替换的项目数不是替换长度的倍数

    number of items to replace is not a multiple of replacement length[1]  25  32  74 110 128 157
number of items to replace is not a multiple of replacement lengthGA | iter = 3 | Mean = 25 | Best = 25
[1]  25  32  74 110 128 157
number of items to replace is not a multiple of replacement length[1]  25  32  74 110 128 157
number of items to replace is not a multiple of replacement length[1]  25  32  74 110 128 157

然后我竞选

summary(GA)

摘要GA的输出

-- Genetic Algorithm ------------------- 

GA settings: 
Type                  =  permutation 
Population size       =  50 
Number of generations =  5 
Elitism               =  2 
Crossover probability =  0.8 
Mutation probability  =  0.1 

GA results: 
Iterations             = 5 
Fitness function value = 25 
Solutions = 
      x1 x2 x3 x4 x5 x6
[1,]   4  1  6  3  5  2
[2,]   6  3  1  5  4  2
[3,]   6  2  3  4  1  5
[4,]   3  6  4  1  5  2
[5,]   4  6  2  1  5  3
[6,]   5  3  4  1  2  6
[7,]   2  1  6  3  5  4
[8,]   4  1  6  3  2  5
[9,]   3  6  1  2  5  4
[10,]  3  6  2  1  5  4
 ...                   
[35,]  4  5  6  2  1  3
[36,]  3  4  5  6  2  1

[当我运行Summary(GA)时,它似乎可以工作,但是我对警告消息感到好奇。如果有人可以为此提供帮助,我将不胜感激。预先谢谢你。

r for-loop permutation genetic-algorithm
1个回答
0
投票

无需使用fitness进行for循环就可以轻松实现cumsum功能中要执行的操作。

例如,您从for循环获得的输出是

#[1] 25  32  74 110 128 157

并使用cumsum,我们得到了相同的结果。

cumsum(data1$Pj)
#[1]  25  32  74 110 128 157

然而,主要问题是fitness函数应仅返回一个值,而不返回像cumsum这样的值的向量。因此,如果将函数更改为类似的内容

fitness <- function(j) sum(j)

您可以做:

fitness(data1$Pj)
#[1] 157

library(GA)
GA <- ga(type = "permutation", fitness = fitness, lower = 1, upper = 6, 
         maxiter= 5, run = 20, optim = TRUE)

不会返回任何警告。

© www.soinside.com 2019 - 2024. All rights reserved.