#K均值(K-Means分散性聚类)算法
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn import datasets
iris=datasets.load_iris()
x=iris.data[:,:4] #取特征空间4个维度
print(x.shape)
plt.scatter(x[:,0],x[:,1],c="red",marker='o',label='see')
plt.xlabel('petal length')
plt.ylabel('petal width')
plt.legend(loc=2)
plt.show()
estimator=KMeans(n_clusters=3) #构造聚类器
estimator.fit(x) #聚类
label_pred=estimator.labels_ #获取聚类标签
# 绘制K-Means结果
x0=x[label_pred==0]
x1=x[label_pred==1]
x2=x[label_pred==2]
plt.scatter(x0[:,0],x0[:,1],c="red",marker='o',label='label0')
plt.scatter(x1[:,0],x1[:,1],c="green",marker='*',label='label1')
plt.scatter(x2[:,0],x2[:,1],c="blue",marker='+',label='label2')
plt.xlabel('petal length')
plt.ylabel('petal width')
plt.legend(loc=2)
plt.show()
python实现K均值(K-Means分散性聚类)算法
最新推荐文章于 2022-10-28 21:30:45 发布