【发布时间】:2021-02-24 13:52:38
【问题描述】:
我正在关注这个详细的 KMeans 教程:https://github.com/python-engineer/MLfromscratch/blob/master/mlfromscratch/kmeans.py,它使用具有 2 个特征的数据集。
但我有一个包含 5 个特征(列)的数据框,因此我没有在教程中使用 def euclidean_distance(x1, x2): 函数,而是按如下方式计算欧几里得距离。
def euclidean_distance(df):
n = df.shape[1]
distance_matrix = np.zeros((n,n))
for i in range(n):
for j in range(n):
distance_matrix[i,j] = np.sqrt(np.sum((df.iloc[:,i] - df.iloc[:,j])**2))
return distance_matrix
接下来我想实现教程中计算质心的部分,如下所示;
def _closest_centroid(self, sample, centroids):
distances = [euclidean_distance(sample, point) for point in centroids]
由于我的 def euclidean_distance(df): 函数只需要 1 个参数 df,我怎样才能最好地实现它以获得质心?
我的示例数据集,df如下:
col1,col2,col3,col4,col5
0.54,0.68,0.46,0.98,-2.14
0.52,0.44,0.19,0.29,30.44
1.27,1.15,1.32,0.60,-161.63
0.88,0.79,0.63,0.58,-49.52
1.39,1.15,1.32,0.41,-188.52
0.86,0.80,0.65,0.65,-45.27
[添加:plot() 函数]
您包含的绘图函数给出了一个错误TypeError: object of type 'itertools.combinations' has no len(),我通过将len(combinations) 更改为len(list(combinations)) 解决了这个问题。但是输出 不是散点图。知道我需要在这里解决什么吗?
【问题讨论】:
-
教程中的欧几里得距离函数是为数组定义的,因此空间的维度无关紧要。这意味着您不需要编写自己的函数。
-
本教程中的函数适用于具有任意数量特征的两个数组(我在之前的评论中所说的维度)。它从数据集的形状中推断出特征的数量。运行教程中的代码时,您究竟在哪里遇到错误?
-
第 81 行,在 _closest_centroid
distances = [euclidean_distance(sample, point) for point in centroids]TypeError: euclidean_distance() 只需要 1 个参数(给定 2 个) -
repo 中的函数不会抛出该错误,因为它确实需要 2 个参数。你确定你在用那个吗?
-
当我使用教程函数时,line 17: y_pred = k.predict(X) 上的 kmeans_test.py 抛出 ' ValueError:无法识别的标记样式 [13.15717]' 指向 kmeans.py 文件上的 第 35 行 和 93 行。如前所述,我更改了 make_blobs() 函数来满足我的 31 行和 5 列(功能)的数据框,如下所示。否则,教程代码无需任何修改即可正常运行。
data = pd.read_csv('df.csv')X = np.array(data)print(X.shape)clusters = 5k = KMeans(K=clusters, max_iters=150, plot_steps=True)y_pred = k.predict(X)k.plot()
标签: python dataframe k-means euclidean-distance