line 47, in tsp_path_planning closed_tour = np.array(list(vertex_cover) + [vertex_cover[0]]) TypeError: 'set' object is not subscriptable
时间: 2024-02-22 08:56:50 浏览: 31
这个错误是因为你尝试从一个集合对象中获取元素,但集合对象不支持像列表和元组那样的索引操作。解决方案是将该集合对象转换为列表对象,例如使用`list()`函数将`vertex_cover`转换为列表对象,如下所示:
```python
closed_tour = np.array(list(vertex_cover) + [list(vertex_cover)[0]])
```
这将把`vertex_cover`集合转换为列表,然后将其连接到第一个元素上,最后将结果转换为NumPy数组。这应该解决该错误。
相关问题
def tsp_path_planning(points): # TSP路径规划 n = len(points) dist_matrix = cdist(points, points) mst = minimum_spanning_tree(csr_matrix(dist_matrix)).toarray() graph = Graph() for i in range(n): graph.add_node(i) for i in range(n): for j in range(i+1, n): if mst[i, j] != 0: graph.add_edge(i, j, weight=dist_matrix[i, j]) vertex_cover = min_weighted_vertex_cover(graph, weight='weight') odd_vertices = list(vertex_cover) odd_edges = np.zeros((len(vertex_cover), 2)) k = 0 for i in range(n): if i in odd_vertices: odd_edges[k, 0] = i k += 1 closed_tour = np.array(list(vertex_cover) + [vertex_cover[0]]) for i in range(0, len(odd_edges), 2): u, v = int(odd_edges[i, 0]), int(odd_edges[i+1, 0]) min_dist, min_j = np.inf, -1 for j in range(n): if j not in odd_vertices: dist = dist_matrix[u, j] + dist_matrix[v, j] if dist < min_dist: min_dist, min_j = dist, j closed_tour = np.insert(closed_tour, np.where(closed_tour == u)[0][0]+1, min_j) closed_tour = np.insert(closed_tour, np.where(closed_tour == v)[0][0]+1, min_j) odd_vertices.remove(u) odd_vertices.remove(v) return closed_tour这个函数貌似没有删除重复的顶点
是的,你说得没错。这个函数确实没有删除重复的顶点,因为它是用于求解TSP路径规划的,而TSP路径规划中需要经过所有的顶点,因此不需要删除重复的顶点。另外,由于TSP问题是NP问题,没有一种简单的算法可以在多项式时间内求解,因此很多TSP路径规划算法都是近似算法或者启发式算法,而不是精确算法,因此允许一定的误差和重复顶点。
请以import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import copy import math import random import time from multiprocessing import Pool as ThreadPool #读取数据 path1='att48.tsp' path2='eil76.tsp' path3='pcb442.tsp' path4='rd100.tsp' path5='tsp225.tsp' def readcity(path): df = pd.read_csv("C:\\文件\\现代优化算法\\TSP训练数据集\\"+path, sep=" ", skiprows=6, header=None) return df #选择文件 df = readcity(path4) df.head() city = np.array(range(1,len(df[0][0:len(df)-1])+1)) city_x = np.array(df[1][0:len(df)-1]) city_y = np.array(df[2][0:len(df)-1])为开头补充完成一个模拟退火求解tsp问题的代码,我发给你的代码是用于获取输入数据并将其转化成坐标的
下面是一个简单的模拟退火求解TSP问题的代码,它使用了上面提到的数据读取和坐标转化代码:
```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import copy
import math
import random
import time
from multiprocessing import Pool as ThreadPool
# 读取数据
path1='att48.tsp'
path2='eil76.tsp'
path3='pcb442.tsp'
path4='rd100.tsp'
path5='tsp225.tsp'
def readcity(path):
df = pd.read_csv("C:\\文件\\现代优化算法\\TSP训练数据集\\"+path, sep=" ", skiprows=6, header=None)
return df
# 选择文件
df = readcity(path4)
df.head()
# 获取城市坐标
city = np.array(range(1,len(df[0][0:len(df)-1])+1))
city_x = np.array(df[1][0:len(df)-1])
city_y = np.array(df[2][0:len(df)-1])
city_pos = np.stack((city_x, city_y), axis=1)
# 计算两点之间的距离
def distance(city1, city2):
return math.sqrt((city1[0]-city2[0])**2 + (city1[1]-city2[1])**2)
# 计算路径长度
def path_length(path):
length = 0
for i in range(len(path)-1):
length += distance(city_pos[path[i]-1], city_pos[path[i+1]-1])
length += distance(city_pos[path[-1]-1], city_pos[path[0]-1])
return length
# 生成随机解
def generate_random_solution():
return np.random.permutation(city)
# 退火算法求解TSP问题
def simulated_annealing():
# 设置参数
initial_temperature = 100
cooling_rate = 0.99
temperature = initial_temperature
current_path = generate_random_solution()
current_length = path_length(current_path)
best_path = current_path
best_length = current_length
# 迭代求解
while temperature > 1:
# 生成新解
new_path = copy.deepcopy(current_path)
i = random.randint(0, len(city)-1)
j = random.randint(0, len(city)-1)
new_path[i], new_path[j] = new_path[j], new_path[i]
new_length = path_length(new_path)
# 计算接受概率
delta = new_length - current_length
if delta < 0 or random.random() < math.exp(-delta/temperature):
current_path = new_path
current_length = new_length
# 更新最优解
if current_length < best_length:
best_path = current_path
best_length = current_length
# 降温
temperature *= cooling_rate
return best_path, best_length
# 运行算法
start_time = time.time()
best_path, best_length = simulated_annealing()
end_time = time.time()
# 打印结果
print("最优路径:", best_path)
print("最优路径长度:", best_length)
print("运行时间:", end_time - start_time)
# 绘制路径
plt.figure(figsize=(8, 8))
plt.plot(city_pos[best_path-1, 0], city_pos[best_path-1, 1], 'o-')
plt.title("Simulated Annealing TSP Solution (length={})".format(round(best_length)))
plt.show()
```
这段代码实现了一个简单的模拟退火算法求解TSP问题。它首先读取数据,然后计算出每个城市的坐标,并且定义了计算两个城市之间距离和计算路径长度的函数。接着,它使用随机解作为初始解,并且迭代地生成新解并计算接受概率,直到降温至最低温度。最后,它输出最优路径和路径长度,并且绘制路径。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)