此处展示的是三维的k均值聚类,可以修改为多维的聚类,直接增加x的维度就好了
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
colo = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
x = 50 * np.random.rand(100, 3) # 3 表示3个特征,即3维
fig = plt.figure(figsize=(12, 8))
ax = Axes3D(fig, elev=30, azim=20)
shape = x.shape
sse = []
score = []
K = 4 # 分为K类
for k in [K]:
clf = KMeans(n_clusters=k)
clf.fit(x)
sse.append(clf.inertia_)
lab = clf.fit_predict(x)
score.append(silhouette_score(x, clf.labels_, metric='euclidean'))
for i in range(shape[0]):
plt.xlabel('x')
plt.ylabel('y')
plt.title('k=' + str(k))
ax.scatter(x[i, 0],x[i, 1], x[i, -1], c=colo[lab[i]])
plt.show()