4

我使用 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 = max(vi / wi ) + c 惩罚 = K * max[∑(wx )−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

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

4

0 回答 0