Write code to solve the following 0-1 Knapsack problem

조회 수: 6 (최근 30일)
Chihiro Ogino
Chihiro Ogino 2022년 12월 8일
답변: Mathy 2024년 8월 10일
Given a knapsack of items N and capacity W. The volume and value of the item is c(i) and w(i) respectively. Find the maximum total value in the knapsack. Suppose that N=10, and V=300. The volume of each item is 95, 75, 23, 73, 50, 22, 6, 57, 89 and 98. The values of each item are 89, 59, 19, 43, 100, 72, 44, 16, 7 and 64.
  댓글 수: 7
Chihiro Ogino
Chihiro Ogino 2022년 12월 8일
편집: Chihiro Ogino 2022년 12월 8일
I just noticed the mismatch that I did. Bless you
Chihiro Ogino
Chihiro Ogino 2022년 12월 8일
Any suggestion on how do I apply BPSO algorithm in this same code?

댓글을 달려면 로그인하십시오.

답변 (1개)

Mathy
Mathy 2024년 8월 10일
Hi Chihiro,
Below is a basic implementation of Binary Particle Swarm Optimization (BPSO) algorithm to solve the 0-1 knapsack problem in MATLAB.
function bpso_knapsack
% Parameters
num_particles = 30;
num_iterations = 100;
num_items = 10;
w = 0.5; % Inertia weight
c1 = 2; % Cognitive (particle) weight
c2 = 2; % Social (swarm) weight
max_weight = 50;
% Generate random weights and values for the items
weights = randi([1, 15], 1, num_items);
values = randi([10, 100], 1, num_items);
% Initialize particles
particles = randi([0, 1], num_particles, num_items);
velocities = rand(num_particles, num_items);
personal_best_positions = particles;
personal_best_values = zeros(num_particles, 1);
for i = 1:num_particles
personal_best_values(i) = fitness(particles(i, :), weights, values, max_weight);
end
[global_best_value, idx] = max(personal_best_values);
global_best_position = personal_best_positions(idx, :);
% Store best values for plotting
best_values = zeros(num_iterations, 1);
% Main loop
for iter = 1:num_iterations
for i = 1:num_particles
% Update velocity
velocities(i, :) = w * velocities(i, :) + ...
c1 * rand * (personal_best_positions(i, :) - particles(i, :)) + ...
c2 * rand * (global_best_position - particles(i, :));
% Update position
particles(i, :) = sigmoid(velocities(i, :)) > rand(1, num_items);
% Calculate fitness
current_value = fitness(particles(i, :), weights, values, max_weight);
% Update personal best
if current_value > personal_best_values(i)
personal_best_positions(i, :) = particles(i, :);
personal_best_values(i) = current_value;
end
end
% Update global best
[current_best_value, idx] = max(personal_best_values);
if current_best_value > global_best_value
global_best_value = current_best_value;
global_best_position = personal_best_positions(idx, :);
end
% Store best value for plotting
best_values(iter) = global_best_value;
% Display iteration and best value
fprintf('Iteration %d: Best Value = %d\n', iter, global_best_value);
end
% Final result
fprintf('Optimal solution found: \n');
disp(global_best_position);
fprintf('Maximum value: %d\n', global_best_value);
% Plot the best values over iterations
figure;
plot(1:num_iterations, best_values, 'LineWidth', 2);
xlabel('Iteration');
ylabel('Best Value');
title('BPSO Optimization Progress');
grid on;
end
function value = fitness(particle, weights, values, max_weight)
total_weight = sum(particle .* weights);
if total_weight > max_weight
value = 0;
else
value = sum(particle .* values);
end
end
function s = sigmoid(x)
s = 1 ./ (1 + exp(-x));
end
Explanation:
  1. Parameters:
  • num_particles: Number of particles in the swarm.
  • num_iterations: Number of iterations to run the algorithm.
  • num_items: Number of items in the knapsack problem.
  • w, c1, c2: Parameters for the PSO algorithm (inertia weight, cognitive weight, social weight).
  • max_weight: Maximum weight capacity of the knapsack.
  1. Initialization:
  • Randomly generate weights and values for the items.
  • Initialize particles and velocities.
  • Determine the personal best positions and values for each particle.
  • Determine the global best position and value.
  1. Main Loop:
  • Update velocities and positions of particles.
  • Calculate the fitness of each particle.
  • Update personal and global bests based on fitness values.
  1. Fitness Function:
  • Calculates the total value of the items in the knapsack if the total weight does not exceed the maximum weight.
  1. Sigmoid Function:
  • Used to map velocities to probabilities for binary decision making.
This code provides a basic framework for BPSO applied to the 0-1 Knapsack problem. You can further optimize the parameters and enhance the algorithm based on specific needs and problem constraints.
And the plot generated from the above code looks something like this:
Hope this helps!

카테고리

Help CenterFile Exchange에서 Particle Swarm에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by