如何解决使用各个群集的外部坐标可视化群集
我想可视化群集。
通过使用以下代码:
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
X = np.array([[28,7],[36,5],[32,2],[56,8],[47,[50,100],[100,[26,59],[19,71],[75,9],[34,4],[28,1],[33,6]])
col = ['blue','green','c','m','y','k',"violet","indigo"]
ncluster = 2
kmeans = KMeans(n_clusters=ncluster,max_iter=500).fit(X)
y = kmeans.labels_
centroids = kmeans.cluster_centers_
clusters_centroids = dict()
clusters_radii = dict()
for cluster in range(ncluster):
clusters_centroids[cluster] = list(
zip(centroids[:,0],centroids[:,1]))[cluster]
clusters_radii[cluster] = max([np.linalg.norm(np.subtract(
i,clusters_centroids[cluster])) for i in zip(X[y == cluster,X[y == cluster,1])])
fig,ax = plt.subplots(1,figsize=(7,5))
def drawclusters():
for i in range(ncluster):
plt.scatter(X[y == i,X[y == i,s=100,c=col[i],label=f'Cluster {i + 1}')
art = mpatches.Circle(
clusters_centroids[i],clusters_radii[i],edgecolor=col[i],fill=False)
ax.add_patch(art)
plt.scatter(centroids[:,s=200,c='red',label='Centroids',marker='x')
drawclusters()
plt.legend()
plt.tight_layout()
plt.show()
我正在圈子:
但是我想使用类似于此点的点来可视化忽略我只需要可视化部分的数据部分(我需要形状):
我需要python中的代码。 R中有一个功能 fviz_cluster 。
解决方法
您可以使用scipy.spatial.ConvexHull()
创建每个群集的凸包。请注意,X[y == i]
需要转换为新数组,因为ConvexHull()
会将索引返回短数组。返回的点形成一个多边形。首先需要复制第一点以进行绘图,以包括封闭多边形的线段。
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
from scipy.spatial import ConvexHull
def drawclusters(ax):
for i in range(ncluster):
points = X[y == i]
ax.scatter(points[:,0],points[:,1],s=100,c=col[i],label=f'Cluster {i + 1}')
hull = ConvexHull(points)
vert = np.append(hull.vertices,hull.vertices[0]) # close the polygon by appending the first point at the end
ax.plot(points[vert,points[vert,'--',c=col[i])
ax.fill(points[vert,alpha=0.2)
ax.scatter(centroids[:,centroids[:,s=200,c='red',label='Centroids',marker='x')
X = np.array([[28,7],[36,5],[32,2],[56,8],[47,[50,100],[100,[26,59],[19,71],[75,9],[34,4],[28,[33,6]])
col = ['blue','green']
ncluster = 2
kmeans = KMeans(n_clusters=ncluster,max_iter=500).fit(X)
y = kmeans.labels_
centroids = kmeans.cluster_centers_
fig,ax = plt.subplots(1,figsize=(7,5))
drawclusters(ax)
ax.legend()
plt.tight_layout()
plt.show()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。