gpt4 book ai didi

python - 访问按 KMeans 集群分组的数据的有效方法

转载 作者:行者123 更新时间:2023-11-30 08:59:41 25 4
gpt4 key购买 nike

我试图围绕每个质心绘制圆圈,其半径延伸到属于每个簇的最远点。现在,我绘制的圆的半径延伸到整个训练数据集中距离聚类中心最远的点

这是我的代码:

def KMeansModel(n):
pca = PCA(n_components=2)
reduced_train_data = pca.fit_transform(train_data)
KM = KMeans(n_clusters=n)
KM.fit(reduced_train_data)
plt.plot(reduced_train_data[:, 0], reduced_train_data[:, 1], 'k.', markersize=2)
centroids = KM.cluster_centers_
# Plot the centroids as a red X
plt.scatter(centroids[:, 0], centroids[:, 1],
marker='x', color='r')
for i in centroids:
print np.max(metrics.pairwise_distances(i, reduced_train_data))
plt.gca().add_artist(plt.Circle(i, np.max(metrics.pairwise_distances(i, reduced_train_data)), fill=False))
plt.show()

out = [KMeansModel(n) for n in np.arange(1,16,1)]

最佳答案

当你这样做时

metrics.pairwise_distances(i, reduced_train_data)

您计算与所有训练点的距离,而不仅仅是与相关类的训练点的距离。为了从训练数据中找到与 ind 类相对应的点的位置,您可以这样做

np.where(KM.labels_==ind)[0]

因此,在 for 循环内部

for i in centroids:

您需要从特定类(class)访问训练点。这将完成这项工作:

from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn import metrics
import matplotlib.pyplot as plt
import numpy as np

def KMeansModel(n):
pca = PCA(n_components=2)
reduced_train_data = pca.fit_transform(train_data)
KM = KMeans(n_clusters=n)
KM.fit(reduced_train_data)
plt.plot(reduced_train_data[:, 0], reduced_train_data[:, 1], 'k.', markersize=2)
centroids = KM.cluster_centers_
# Plot the centroids as a red X
plt.scatter(centroids[:, 0], centroids[:, 1],
marker='x', color='r')
for ind,i in enumerate(centroids):
class_inds=np.where(KM.labels_==ind)[0]
max_dist=np.max(metrics.pairwise_distances(i, reduced_train_data[class_inds]))
print(max_dist)
plt.gca().add_artist(plt.Circle(i, max_dist, fill=False))
plt.show()

out = [KMeansModel(n) for n in np.arange(1,16,1)]

这是我使用代码得到的数字之一:

enter image description here

关于python - 访问按 KMeans 集群分组的数据的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45397964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com