蚁群算法python代码_Python蚁群算法代码范例+注释
时间: 2024-01-17 13:03:54 浏览: 87
以下是一个简单的蚁群算法Python代码范例,带有注释说明:
```python
import random
# 定义城市数量
num_cities = 10
# 定义城市之间的距离矩阵
distance_matrix = []
for i in range(num_cities):
row = []
for j in range(num_cities):
if i == j:
row.append(0)
else:
row.append(random.randint(1, 100))
distance_matrix.append(row)
# 定义参数
num_ants = 5
alpha = 1 # 信息素重要程度因子
beta = 2 # 启发式因子
evaporation = 0.5 # 信息素挥发速度
Q = 1 # 信息素增加强度系数
num_iterations = 10
# 初始化信息素矩阵
pheromone_matrix = [[1 / (num_cities * num_cities) for j in range(num_cities)] for i in range(num_cities)]
# 定义函数,用于选择下一个城市
def select_next_city(current_city, visited_cities, pheromone_matrix, distance_matrix):
unvisited_cities = [i for i in range(num_cities) if i not in visited_cities]
probabilities = [0 for i in range(num_cities)]
total_probabilities = 0
for city in unvisited_cities:
probabilities[city] = (pheromone_matrix[current_city][city] ** alpha) * ((1 / distance_matrix[current_city][city]) ** beta)
total_probabilities += probabilities[city]
if total_probabilities == 0:
return random.choice(unvisited_cities)
probabilities = [probability / total_probabilities for probability in probabilities]
r = random.random()
current_probability = 0
for i in range(len(probabilities)):
current_probability += probabilities[i]
if r <= current_probability:
return unvisited_cities[i]
# 定义函数,用于更新信息素矩阵
def update_pheromone_matrix(pheromone_matrix, ant_paths, distance_matrix, evaporation, Q):
for i in range(num_cities):
for j in range(num_cities):
pheromone_matrix[i][j] *= (1 - evaporation)
for ant_path, ant_distance in ant_paths:
for i in range(num_cities - 1):
pheromone_matrix[ant_path[i]][ant_path[i+1]] += Q / ant_distance
pheromone_matrix[ant_path[num_cities-1]][ant_path[0]] += Q / ant_distance
# 开始迭代
for iteration in range(num_iterations):
# 每只蚂蚁都从一个随机城市出发
ant_paths = []
for ant in range(num_ants):
current_city = random.randint(0, num_cities-1)
visited_cities = [current_city]
ant_path = [current_city]
ant_distance = 0
# 选择下一个城市,直到所有城市都被访问过
while len(visited_cities) < num_cities:
next_city = select_next_city(current_city, visited_cities, pheromone_matrix, distance_matrix)
visited_cities.append(next_city)
ant_path.append(next_city)
ant_distance += distance_matrix[current_city][next_city]
current_city = next_city
ant_distance += distance_matrix[ant_path[num_cities-1]][ant_path[0]]
ant_paths.append((ant_path, ant_distance))
# 更新信息素矩阵
update_pheromone_matrix(pheromone_matrix, ant_paths, distance_matrix, evaporation, Q)
# 打印最佳路径
ant_paths.sort(key=lambda x: x[1])
print(f"Best path after iteration {iteration}: {ant_paths[0][0]}, distance: {ant_paths[0][1]}")
```
这个代码实现了一个简单的蚁群算法,用于求解旅行商问题。在代码中,首先定义了城市数量和城市之间的距离矩阵。然后定义了一些参数,包括蚂蚁数量、信息素重要程度因子、启发式因子、信息素挥发速度、信息素增加强度系数和迭代次数等。接着初始化了信息素矩阵。然后定义了两个函数,一个用于选择下一个城市,另一个用于更新信息素矩阵。最后在迭代中,每只蚂蚁都从一个随机城市出发,选择下一个城市,直到所有城市都被访问过,然后更新信息素矩阵。迭代结束后,打印最佳路径。
阅读全文