给我一个蚁群算法的实例和代码
时间: 2024-06-12 13:05:13 浏览: 17
以下是一个用蚁群算法解决旅行商问题的Python代码实例:
```python
import random
# 旅行商问题的距离矩阵
distance_matrix = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
# 蚂蚁数量
num_ants = 10
# 信息素挥发因子
evaporation_rate = 0.5
# 信息素增强因子
pheromone_factor = 0.5
# 最大迭代次数
max_iterations = 100
# 初始化信息素矩阵
pheromone_matrix = [[1 for j in range(4)] for i in range(4)]
# 计算两个城市之间的距离
def distance(city1, city2):
return distance_matrix[city1][city2]
# 计算蚂蚁从起点到终点的路径长度
def path_length(path):
length = 0
for i in range(len(path) - 1):
length += distance(path[i], path[i+1])
return length
# 更新信息素矩阵
def update_pheromone_matrix(paths):
for i in range(4):
for j in range(4):
# 计算所有蚂蚁经过该路径的信息素总量
total_pheromone = sum([1/path_length(path) for path in paths if (i, j) in path])
# 更新信息素矩阵
pheromone_matrix[i][j] = (1 - evaporation_rate) * pheromone_matrix[i][j] + pheromone_factor * total_pheromone
# 选择下一个城市
def select_next_city(current_city, unvisited_cities):
# 如果只剩下一个未访问的城市,直接返回
if len(unvisited_cities) == 1:
return unvisited_cities[0]
# 计算每个城市的信息素和距离权重之和
weights = [(pheromone_matrix[current_city][city] ** 2) * (1/distance(current_city, city)) for city in unvisited_cities]
# 根据权重随机选择下一个城市
total_weight = sum(weights)
r = random.uniform(0, total_weight)
cumulative_weight = 0
for i in range(len(weights)):
cumulative_weight += weights[i]
if cumulative_weight >= r:
return unvisited_cities[i]
# 蚂蚁类
class Ant:
def __init__(self, start_city):
self.path = [start_city]
self.unvisited_cities = [i for i in range(4) if i != start_city]
def choose_next_city(self):
next_city = select_next_city(self.path[-1], self.unvisited_cities)
self.path.append(next_city)
self.unvisited_cities.remove(next_city)
# 主函数
def main():
best_path = None
best_length = float('inf')
for iteration in range(max_iterations):
paths = []
# 每个蚂蚁走一遍
for i in range(num_ants):
ant = Ant(random.randint(0, 3))
while ant.unvisited_cities:
ant.choose_next_city()
paths.append(ant.path)
# 更新信息素矩阵
update_pheromone_matrix(paths)
# 找到最优解
for path in paths:
length = path_length(path)
if length < best_length:
best_path = path
best_length = length
# 输出当前迭代的最优解
print('Iteration {}: Best length = {}'.format(iteration, best_length))
# 输出最终的最优解
print('Best path: {}'.format(best_path))
print('Best length: {}'.format(best_length))
if __name__ == '__main__':
main()
```
该代码使用了基本的蚁群算法框架,包括随机初始化信息素矩阵、每个蚂蚁走一遍、更新信息素矩阵、找到最优解等步骤。具体实现细节可以参考注释。