给我写一个蚁群算法,用python
时间: 2024-05-06 08:20:09 浏览: 67
人工智能-项目实践-蚁群算法-蚁群算法python实现.zip
以下是一个简单的蚁群算法的实现,用于解决旅行商问题:
```python
import random
# 定义城市个数和蚂蚁个数
num_cities = 10
num_ants = 20
# 定义城市之间的距离矩阵
distances = [[0, 5, 10, 15, 20, 25, 30, 35, 40, 45],
[5, 0, 5, 10, 15, 20, 25, 30, 35, 40],
[10, 5, 0, 5, 10, 15, 20, 25, 30, 35],
[15, 10, 5, 0, 5, 10, 15, 20, 25, 30],
[20, 15, 10, 5, 0, 5, 10, 15, 20, 25],
[25, 20, 15, 10, 5, 0, 5, 10, 15, 20],
[30, 25, 20, 15, 10, 5, 0, 5, 10, 15],
[35, 30, 25, 20, 15, 10, 5, 0, 5, 10],
[40, 35, 30, 25, 20, 15, 10, 5, 0, 5],
[45, 40, 35, 30, 25, 20, 15, 10, 5, 0]]
# 定义初始信息素浓度和信息素挥发率
init_pheromone = 1.0
evaporation_rate = 0.5
# 初始化信息素矩阵
pheromones = [[init_pheromone for _ in range(num_cities)] for _ in range(num_cities)]
# 定义蚂蚁类
class Ant:
def __init__(self, start_city):
self.visited_cities = [start_city]
self.current_city = start_city
self.distance_traveled = 0
def choose_next_city(self):
# 计算当前城市和未访问城市之间的信息素和距离的乘积
product = [(pheromones[self.current_city][i] ** 2) / distances[self.current_city][i] for i in range(num_cities) if i not in self.visited_cities]
# 选择下一个城市
if product:
max_product = max(product)
options = [i for i in range(num_cities) if i not in self.visited_cities and (pheromones[self.current_city][i] ** 2) / distances[self.current_city][i] == max_product]
self.current_city = random.choice(options)
else:
options = [i for i in range(num_cities) if i not in self.visited_cities]
self.current_city = random.choice(options)
# 更新已访问城市列表和已经走过的距离
self.visited_cities.append(self.current_city)
self.distance_traveled += distances[self.visited_cities[-2]][self.current_city]
def deposit_pheromone(self):
# 计算蚂蚁留下的信息素
deposit = 1 / self.distance_traveled
# 在经过的路径上留下信息素
for i in range(len(self.visited_cities) - 1):
pheromones[self.visited_cities[i]][self.visited_cities[i+1]] += deposit
pheromones[self.visited_cities[i+1]][self.visited_cities[i]] += deposit
# 定义主函数
def main(num_iterations):
best_distance = float('inf')
best_path = None
for i in range(num_iterations):
# 初始化蚂蚁
ants = [Ant(random.randint(0, num_cities-1)) for _ in range(num_ants)]
# 让蚂蚁移动并留下信息素
for ant in ants:
for _ in range(num_cities-1):
ant.choose_next_city()
ant.deposit_pheromone()
# 挥发信息素
for i in range(num_cities):
for j in range(num_cities):
pheromones[i][j] *= (1 - evaporation_rate)
# 更新最优路径和最优距离
for ant in ants:
if ant.distance_traveled < best_distance:
best_distance = ant.distance_traveled
best_path = ant.visited_cities
print(f'Best path: {best_path}')
print(f'Best distance: {best_distance}')
if __name__ == '__main__':
main(1000)
```
该蚁群算法通过将信息素浓度和距离的倒数乘积作为蚂蚁选择下一个城市的概率分布,并在路径上留下信息素,来不断寻找最优解。经过多次迭代后,算法能够找到一个近似最优的路径。
阅读全文