#使用kmeans对鸢尾花数据集聚类
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
from sklearn.model_selection import train_test_split
matplotlib.rcParams['font.family']='YouYuan'
#加载数据
iris=load_iris()
data=iris.data
target=iris.target
x=data[:,[0,2]] #行数不限,列取第1,3列,列是从0开始算的,所以不是1,3而是0,2
y=iris.target
print(y)
label=np.array(y)
index_0=np.where(label==0)
plt.scatter(x[index_0,0],x[index_0,1],marker='o',color='g',label='0')
index_1=np.where(label==1)
plt.scatter(x[index_1,0],x[index_1,1],marker='*',color='b',label='1')
index_2=np.where(label==2)
plt.scatter(x[index_2,0],x[index_2,1],marker='*',color='r',label='2')
plt.xlabel('花萼长度')
plt.ylabel('花萼宽度')
plt.legend(loc=4)
plt.show()
#kmeans聚类分析
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25,random_state=1)
kms=KMeans(n_clusters=3) #由于共012三类,所以设置聚类数为3
kms.fit(x_train) #在x_train上进行kmeans聚类分析
label_pred=kms.labels_ #获取每个样本点对应的类别
#绘制kmeans结果
x0=x_train[label_pred==0]
x1=x_train[label_pred==1]
x2=x_train[label_pred==2]
plt.scatter(x0[:,0],x0[:,1],c='b',marker='o',label='label0')
plt.scatter(x1[:,0],x1[:,1],c='g',marker='o',label='label1')
plt.scatter(x2[:,0],x2[:,1],c='r',marker='o',label='label2')
plt.xlabel('花萼长度')
plt.ylabel('花萼宽度')
plt.legend(loc=2)
plt.show()
使用kmeans对鸢尾花数据集聚类
于 2023-07-19 16:52:04 首次发布