灰狼优化算法(gwo)(解决tsp问题,代码完整免费)
时间: 2023-08-11 18:07:48 浏览: 182
灰狼优化算法(GWO)是一种新兴的优化算法,该算法模拟了灰狼群体的行为,以解决各种优化问题。其中一个应用就是用于解决旅行商问题(TSP)。
以下是使用GWO算法解决TSP问题的代码:
```python
import numpy as np
# 计算两个城市之间的距离
def distance(city1, city2):
return np.sqrt(np.sum((city1 - city2) ** 2))
# 计算一条路径的长度
def path_length(path, cities):
length = 0
for i in range(len(path) - 1):
length += distance(cities[path[i]], cities[path[i+1]])
length += distance(cities[path[-1]], cities[path[0]])
return length
# 灰狼优化算法
def gwo_tsp(cities, search_agent_num=10, max_iter=50):
# 初始化灰狼群体
search_agents = np.zeros((search_agent_num, len(cities)), dtype=np.int)
for i in range(search_agent_num):
search_agents[i] = np.random.permutation(len(cities))
alpha = np.zeros(len(cities), dtype=np.int)
beta = np.zeros(len(cities), dtype=np.int)
delta = np.zeros(len(cities), dtype=np.int)
# 计算每个灰狼的适应度
fitness = np.zeros(search_agent_num)
for i in range(search_agent_num):
fitness[i] = 1 / path_length(search_agents[i], cities)
# 迭代优化
for t in range(max_iter):
a = 2 - 2 * t / max_iter # 调整参数a
for i in range(search_agent_num):
# 更新alpha、beta、delta
if fitness[i] > fitness[np.argmax(fitness)]:
delta = search_agents[i]
elif fitness[i] > fitness[np.argmin(fitness)]:
beta = search_agents[i]
else:
alpha = search_agents[i]
# 更新灰狼位置
r1 = np.random.random(len(cities))
r2 = np.random.random(len(cities))
A1 = 2 * a * r1 - a
C1 = 2 * r2
D_alpha = np.abs(C1 * alpha - search_agents[i])
X1 = alpha - A1 * D_alpha
r1 = np.random.random(len(cities))
r2 = np.random.random(len(cities))
A2 = 2 * a * r1 - a
C2 = 2 * r2
D_beta = np.abs(C2 * beta - search_agents[i])
X2 = beta - A2 * D_beta
r1 = np.random.random(len(cities))
r2 = np.random.random(len(cities))
A3 = 2 * a * r1 - a
C3 = 2 * r2
D_delta = np.abs(C3 * delta - search_agents[i])
X3 = delta - A3 * D_delta
new_position = (X1 + X2 + X3) / 3
new_position = np.argsort(new_position)
# 更新适应度
new_fitness = 1 / path_length(new_position, cities)
if new_fitness > fitness[i]:
search_agents[i] = new_position
fitness[i] = new_fitness
# 返回最优解和最优解的路径长度
best_path = search_agents[np.argmax(fitness)]
best_length = 1 / fitness[np.argmax(fitness)]
return best_path, best_length
```
其中,参数`cities`为城市坐标的数组,每一行为一个城市的横纵坐标;`search_agent_num`为灰狼群体大小;`max_iter`为最大迭代次数。函数返回最优解和最优解的路径长度。
使用该函数求解TSP问题的示例代码如下:
```python
# 生成50个随机城市坐标
cities = np.random.rand(50, 2)
# 使用灰狼优化算法求解TSP问题
best_path, best_length = gwo_tsp(cities)
print('最优解路径:', best_path)
print('最优解路径长度:', best_length)
```
该代码会生成50个随机城市坐标,并使用灰狼优化算法求解TSP问题。最终输出最优解路径和最优解路径长度。
阅读全文