Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 背包(背包)采用遗传算法。如何将惩罚添加到健身功能中_Algorithm_Matlab_Genetic Algorithm_Knapsack Problem_Fitness - Fatal编程技术网

Algorithm 背包(背包)采用遗传算法。如何将惩罚添加到健身功能中

Algorithm 背包(背包)采用遗传算法。如何将惩罚添加到健身功能中,algorithm,matlab,genetic-algorithm,knapsack-problem,fitness,Algorithm,Matlab,Genetic Algorithm,Knapsack Problem,Fitness,我使用ga(matlab优化工具)来解决背包问题。我用硬编码的权值数组编写了一个简单的适应度函数: function fitness = bp_fitness(x) % This function computes the fitness value for the 0-1 knapsack problem % x: The current chromosome % max_capacity: maximum capacity of the knapsack % items: a two-di

我使用ga(matlab优化工具)来解决背包问题。我用硬编码的权值数组编写了一个简单的适应度函数:

function fitness = bp_fitness(x)

% This function computes the fitness value for the 0-1 knapsack problem
% x: The current chromosome
% max_capacity: maximum capacity of the knapsack
% items: a two-dimensional array that holds the weight and value
% of each item respectively.

items = [8 15;2 16;5 20; 1 5;13 50;10 35;3 14;4 17;12 40;7 25;
     6 10;18 65;15 50;11 34;9 12;14 20;8 16;19 70;13 30;6 10;
     43 1;18 65;15 50;31 24;3 16;24 42;8 16;21 4;30 10;6 10;
     8 15;2 16];

max_capacity = 350;

overalweight = sum(x*items(:,1));

if overalweight > max_capacity
    fitness = 0;
else
    fitness = -1*sum(x*items(:,2));
end
一切正常。问题是,如何对不适合背包的染色体施加惩罚?我发现:

在背包问题的情况下,可以通过将超出限制的重量乘以可能的最高值重量比来计算惩罚

K=最大值(vi/wi)+c 惩罚=K*max[∑(w x)−W、 0]

但我不知道如何正确地实施这个公式。 我试过:

if overalweight > max_capacity
    k = max(items(:,2)./items(:,1))+1;
    penalty = k * (overalweight - max_capacity);
    fitness = -1*(sum(x*items(:,2)) - penalty);
    fprintf('fit = %i\n',-1*fitness);
else
    fitness = -1*sum(x*items(:,2));
end

这样,两个函数之间的优化结果根本没有区别,这让我觉得我做错了什么。希望有人能在这里帮助我。

这可能是因为你在这两种情况下都得到了非常优化的结果,这就是为什么你看不出两者有什么不同penalty@AnderBiguri,所以我需要更改项目或参数才能看到它?是的,那太好了。尝试获取一些不太合适的数据,并在有惩罚和无惩罚的情况下进行测试。@anonymous为什么要悬赏这个问题?正如Ander上面提到的,这很可能是数据问题,而不是代码问题。由于OP已经半年没有出现了,我怀疑我们是否能得到任何数据或信息来解释为什么这段代码不能产生正确的结果。你最好问问你自己的实现,你可以在哪里提供数据。当我在学校的时候,我记得在这方面我尝试过优化代码。类似这样的问题通常是编译器太好了,以至于它优化了这两种解决方案以获得同等质量的运行时机器代码。