好的,以下是使用Python编写的粒子群优化算法解决0-1背包问题的代码,使用的是这个数据集:
```python
import numpy as np
# 读取数据集
def read_data(file_path):
with open(file_path, 'r') as f:
lines = f.readlines()
n = int(lines[0])
capacity = int(lines[1].split()[1])
weights = np.zeros(n)
values = np.zeros(n)
for i in range(n):
line = lines[i+2].split()
values[i] = int(line[0])
weights[i] = int(line[1])
return n, capacity, weights, values
# 计算适应度函数
def fitness(x, values, weights, capacity):
value = np.sum(x * values)
weight = np.sum(x * weights)
if weight <= capacity:
return value
else:
return 0
# 初始化粒子群
def init_particles(num_particles, num_items):
particles = np.random.randint(2, size=(num_particles, num_items))
velocities = np.zeros((num_particles, num_items))
pbest = particles.copy()
pbest_fitness = np.zeros(num_particles)
for i in range(num_particles):
pbest_fitness[i] = fitness(particles[i], values, weights, capacity)
gbest = pbest[np.argmax(pbest_fitness)]
gbest_fitness = np.max(pbest_fitness)
return particles, velocities, pbest, pbest_fitness, gbest, gbest_fitness
# 更新粒子位置和速度
def update_particles(particles, velocities, pbest, pbest_fitness, gbest, gbest_fitness, w, c1, c2):
r1 = np.random.rand(*particles.shape)
r2 = np.random.rand(*particles.shape)
velocities = w * velocities + c1 * r1 * (pbest - particles) + c2 * r2 * (gbest - particles)
particles[velocities >= 0.5] = 1
particles[velocities < 0.5] = 0
fitnesses = np.array([fitness(particles[i], values, weights, capacity) for i in range(num_particles)])
pbest_fitness[fitnesses > pbest_fitness] = fitnesses[fitnesses > pbest_fitness]
pbest[fitnesses > pbest_fitness] = particles[fitnesses > pbest_fitness]
if np.max(pbest_fitness) > gbest_fitness:
gbest = pbest[np.argmax(pbest_fitness)]
gbest_fitness = np.max(pbest_fitness)
return particles, velocities, pbest, pbest_fitness, gbest, gbest_fitness
# 粒子群优化算法
def pso(num_particles, num_items, values, weights, capacity, max_iter=1000, w=0.5, c1=1, c2=1):
particles, velocities, pbest, pbest_fitness, gbest, gbest_fitness = init_particles(num_particles, num_items)
for i in range(max_iter):
particles, velocities, pbest, pbest_fitness, gbest, gbest_fitness = update_particles(particles, velocities,
pbest, pbest_fitness,
gbest, gbest_fitness,
w, c1, c2)
return gbest, gbest_fitness
if __name__ == '__main__':
file_path = 'knapsack_01.txt'
n, capacity, weights, values = read_data(file_path)
num_particles = 50
num_items = n
gbest, gbest_fitness = pso(num_particles, num_items, values, weights, capacity)
print(f'最优解:{gbest}\n最优适应度:{gbest_fitness}')
```
在这个代码中,我们使用了numpy库来进行向量化计算,使得代码更加简洁高效。读取数据集的函数`read_data`返回了物品数`n`、背包容量`capacity`、物品重量`weights`和物品价值`values`。适应度函数`fitness`计算了一个解的总价值,并判断是否超出容量。初始化粒子群的函数`init_particles`随机生成了一组初始解,其中包括了位置向量、速度向量、个体最优解和最优适应度以及全局最优解和最优适应度。更新粒子位置和速度的函数`update_particles`根据当前位置和速度以及全局最优解和局部最优解来更新每个粒子的位置和速度,并计算适应度并更新最优解。最后,`pso`函数是整个PSO算法的实现,其中可以设置粒子数、最大迭代次数、惯性权重和学习因子。
在这个代码中,我们使用了这个数据集作为测试数据,你也可以将其替换成其他数据集进行测试。