用pyhton实现蚁群算法演示
时间: 2023-05-21 22:03:47 浏览: 104
可以使用Python的numpy和matplotlib库来实现蚁群算法的演示。以下是一个简单的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义问题
def objective_function(x):
return np.sum(x**2)
# 定义蚂蚁类
class Ant:
def __init__(self, num_dimensions):
self.position = np.random.uniform(low=-5.12, high=5.12, size=num_dimensions)
self.velocity = np.zeros(num_dimensions)
self.best_position = self.position.copy()
self.best_fitness = objective_function(self.position)
def update_position(self):
self.position += self.velocity
# 边界处理
self.position[self.position < -5.12] = -5.12
self.position[self.position > 5.12] = 5.12
# 更新最优解
fitness = objective_function(self.position)
if fitness < self.best_fitness:
self.best_position = self.position.copy()
self.best_fitness = fitness
# 定义蚁群算法类
class AntColonyOptimization:
def __init__(self, num_ants, num_iterations, num_dimensions):
self.num_ants = num_ants
self.num_iterations = num_iterations
self.num_dimensions = num_dimensions
self.ants = [Ant(num_dimensions) for _ in range(num_ants)]
self.best_ant = self.ants[0]
def update(self):
for ant in self.ants:
ant.update_position()
if ant.best_fitness < self.best_ant.best_fitness:
self.best_ant = ant
def run(self):
for i in range(self.num_iterations):
self.update()
print(f"Iteration {i+1}: Best fitness = {self.best_ant.best_fitness:.4f}")
print(f"\nBest solution found: {self.best_ant.best_position}")
print(f"Best fitness found: {self.best_ant.best_fitness:.4f}")
# 绘制最优解的轨迹
x = np.arange(-5.12, 5.12, 0.1)
y = np.arange(-5.12, 5.12, 0.1)
X, Y = np.meshgrid(x, y)
Z = np.zeros_like(X)
for i in range(Z.shape[0]):
for j in range(Z.shape[1]):
Z[i, j] = objective_function(np.array([X[i, j], Y[i, j]]))
plt.contour(X, Y, Z, levels=20)
plt.plot([ant.best_position[0] for ant in self.ants], [ant.best_position[1] for ant in self.ants], 'ro-')
plt.plot(self.best_ant.best_position[0], self.best_ant.best_position[1], 'bo')
plt.show()
# 运行蚁群算法
aco = AntColonyOptimization(num_ants=20, num_iterations=100, num_dimensions=2)
aco.run()
```
这个示例代码实现了在二维空间中寻找最小值的蚁群算法。在每次迭代中,每只蚂蚁都会根据当前位置和速度更新自己的位置,并记录自己的最优解。整个蚁群中的最优解会被记录下来,并在最后绘制出所有蚂蚁的轨迹以及最优解的位置。
阅读全文