D:\annaconda\python.exe C:\Users\竹石子\Desktop\电工杯\deepseek_python_20250523_77122d.py Traceback (most recent call last): File "C:\Users\竹石子\Desktop\电工杯\deepseek_python_20250523_77122d.py", line 211, in <module> best_routes, best_cost, dist_matrix = multi_type_simulated_annealing( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\竹石子\Desktop\电工杯\deepseek_python_20250523_77122d.py", line 142, in multi_type_simulated_annealing routes, dist_matrix = generate_initial_routes(coords, weights, vehicle_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\竹石子\Desktop\电工杯\deepseek_python_20250523_77122d.py", line 36, in generate_initial_routes dist_matrix = squareform(pdist(coords)) ^^^^^^^^^^^^^ File "D:\annaconda\Lib\site-packages\scipy\spatial\distance.py", line 2180, in pdist return pdist_fn(X, out=out, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: Unsupported dtype object 进程已结束,退出代码为 1 根据报错纠正上一代码
时间: 2025-05-31 18:52:23 浏览: 20
从错误信息来看,问题出在 `pdist` 函数的调用上。具体来说,`ValueError: Unsupported dtype object` 表明传递给 `pdist` 的数据类型为 `object`,而 `pdist` 只支持数值类型的数组(如 `float` 或 `int`)。这通常是由于输入数据中存在非数值类型的数据导致的。
---
### **问题分析**
1. **错误来源**:
- `coords` 是通过 `pd.read_excel` 读取的坐标数据,可能包含非数值类型(如空值、字符串等)。
- 在调用 `pdist` 之前,需要确保 `coords` 是一个纯数值类型的二维数组。
2. **解决方案**:
- 检查并清理 `coords` 数据,确保其为纯数值类型。
- 使用 `numpy` 的 `astype` 方法将数据转换为浮点数类型。
---
### **修复后的代码**
以下是修复后的代码片段:
```python
import numpy as np
from scipy.spatial.distance import pdist, squareform
def generate_initial_routes(coords: np.ndarray, weights: np.ndarray, vehicle_params: dict):
"""生成初始路径"""
try:
# 确保 coords 是浮点数类型
coords = np.array(coords, dtype=np.float64)
# 计算距离矩阵
dist_matrix = squareform(pdist(coords))
# 初始化变量
routes = {k: [] for k in vehicle_params}
unassigned = {k: [] for k in vehicle_params}
# 根据垃圾类型筛选未分配点
for k in vehicle_params:
unassigned[k] = [i + 1 for i in range(len(weights)) if weights[i][k - 1] > 0]
# 构建初始路径
for k in vehicle_params:
Q = vehicle_params[k]['Q']
while unassigned[k]:
route = []
load = 0
current = 0 # 仓库
while True:
# 筛选可服务的候选点
candidates = [
p for p in unassigned[k]
if (load + weights[p - 1][k - 1] <= Q)
]
if not candidates:
break
# 选择最近的候选点
next_point = min(candidates, key=lambda p: dist_matrix[current][p])
route.append(next_point)
load += weights[next_point - 1][k - 1]
unassigned[k].remove(next_point)
current = next_point
if route:
routes[k].append(route)
return routes, dist_matrix
except Exception as e:
print(f"生成初始路径时发生错误: {e}")
raise
```
---
### **解释**
1. **数据类型检查与转换**:
- 使用 `np.array(coords, dtype=np.float64)` 将 `coords` 转换为浮点数类型,确保 `pdist` 可以正常计算距离。
- 如果原始数据中存在非数值类型(如空值或字符串),转换时会抛出异常,提示用户数据存在问题。
2. **距离矩阵计算**:
- `pdist(coords)` 计算两两之间的距离,并返回一个压缩形式的距离向量。
- `squareform(pdist(coords))` 将压缩形式的距离向量转换为对称的距离矩阵。
3. **路径构建逻辑**:
- 遍历每种车辆类型,根据垃圾类型筛选出符合条件的点。
- 使用贪心算法构建初始路径,优先选择最近的点进行分配。
---
### **完整调用示例**
以下是一个完整的调用示例,展示如何加载数据并生成初始路径:
```python
import pandas as pd
import os
def read_multi_type_data(coord_file, weight_file):
"""读取多类型垃圾数据"""
try:
# 检查文件是否存在
if not os.path.exists(coord_file):
raise FileNotFoundError(f"文件 {coord_file} 不存在,请检查路径!")
if not os.path.exists(weight_file):
raise FileNotFoundError(f"文件 {weight_file} 不存在,请检查路径!")
# 动态读取坐标数据
coords_df = pd.read_excel(coord_file, sheet_name=0, skiprows=1, usecols='A:D')
coords = coords_df.iloc[:, 1:3].values
# 动态读取垃圾量数据
weights_df = pd.read_excel(weight_file, header=0)
weights = weights_df.values
# 车辆参数
vehicle_params = {
1: {'Q': 8, 'type': '厨余垃圾'},
2: {'Q': 6, 'type': '可回收物'},
3: {'Q': 3, 'type': '有害垃圾'},
4: {'Q': 10, 'type': '其他垃圾'}
}
return coords, weights, vehicle_params
except Exception as e:
print(f"读取文件时发生错误: {e}")
raise
if __name__ == '__main__':
try:
# 加载数据
coord_file = '附件1.xlsx'
weight_file = '附件3.xlsx'
coords, weights, vehicle_params = read_multi_type_data(coord_file, weight_file)
# 生成初始路径
routes, dist_matrix = generate_initial_routes(coords, weights, vehicle_params)
print("初始路径生成成功!")
except Exception as e:
print(f"程序运行时发生错误: {e}")
```
---
### **相关问题**
阅读全文
相关推荐














