代码出错了,Traceback (most recent call last): File "D:\PythonProject\machine_learning\k_means.py", line 45, in <module> labels = kmeans(X, 3) File "D:\PythonProject\machine_learning\k_means.py", line 38, in kmeans if np.sum(new_centers - centers) == 0: TypeError: unsupported operand type(s) for -: 'list' and 'list'
时间: 2024-03-20 10:41:14 浏览: 111
Mac下anaconda中Spyder打开报错Traceback(most recent call last)…问题
5星 · 资源好评率100%
这个错误是因为 `new_centers` 和 `centers` 是列表,不支持减法操作。在代码中,我们应该将它们转换为 NumPy 数组才能执行减法操作。
修改代码如下:
```
import numpy as np
import pandas as pd
import random
# 读取数据
data = pd.read_csv("iris_pca_self.csv")
X = data.values
# 初始化聚类中心
def init_centers(X, k):
centers = random.sample(list(X), k)
return np.array(centers)
# 计算样本到聚类中心的距离
def calc_distance(X, centers):
distances = []
for center in centers:
distance = np.sqrt(np.sum((X - center) ** 2, axis=1))
distances.append(distance)
return np.array(distances).T
# Kmeans 聚类
def kmeans(X, k):
centers = init_centers(X, k)
# 迭代停止标志
flag = True
while flag:
# 计算距离
distances = calc_distance(X, centers)
# 找到距离最近的聚类中心
labels = np.argmin(distances, axis=1)
# 更新聚类中心
new_centers = []
for i in range(k):
new_center = np.mean(X[labels == i], axis=0)
new_centers.append(new_center)
# 判断是否收敛
if np.sum(np.array(new_centers) - np.array(centers)) == 0:
flag = False
else:
centers = new_centers
return labels
# 聚类结果
labels = kmeans(X, 3)
print(labels)
```
在这个修改后的代码中,我们使用 `np.array()` 将 `new_centers` 和 `centers` 转换为 NumPy 数组,才能执行减法操作。现在,这个代码应该可以运行了。
阅读全文