k均值聚类分析鸢尾花数据集

python代码思路分析

  • 加载iris数据集
  • 获取鸢尾花两列属性值,分别作为横、纵方向值
  • 创建一个Kmeans模型,并对鸢尾花数据集在此模型中训练
  • 使用模型预测聚类分析结果
  • 画图
from sklearn.datasets import load_iris #导入数据集iris
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

# 1. 获取两列数据
k = 3
iris=load_iris()
X=[x[0] for x in iris.data]
Y=[x[1] for x in iris.data]

# 2. 模型构建
km = KMeans(n_clusters=k, init='k-means++', max_iter=30)
km.fit(iris.data)

 #获取簇心
centroids = km.cluster_centers_
# 获取归集后的样本所属簇对应值
y_kmean = km.predict(iris.data)
fig = plt.figure(figsize = (6,6))
#set the size of subplots
left,width=0.12,0.77
bottom,height=0.11,0.4
bottom_h=bottom+height+0.04
rect_line1=[left,bottom,width,height]
rect_line2=[left,bottom_h,width,height]
axbelow=plt.axes(rect_line1)
axupper=plt.axes(rect_line2)
axupper.scatter(X[:50],Y[:50],color='red' ,marker='o',label='setosa',s=40)#前50个样本
axupper.scatter(X[50:100],Y[50:100],color='blue' ,marker='x',label='versicolor',s=40)#中间50个样本
axupper.scatter(X[100:],Y[100:],color='green' ,marker='+',label='Virginica',s=40)#后50个样本
axbelow.scatter(X, Y, c=y_kmean, s=50, cmap='viridis')
axbelow.scatter(centroids[:, 0], centroids[:, 1], c='black', s=100, alpha=0.5)
plt.legend(loc=2)

plt.show()

代码中部分解析

plt中figure函数

作用:创建一个图形
参数介绍:

参数名:figsize

类型: tuple of integers 整数元组, optional可选, default: None,默认没有

备注:宽度,高度英寸。如果没有提供,默认为rc figure.figsize。

figure函数详细解释见原文链接:
https://blog.csdn.net/weixin_41500849/article/details/80352338

plt中axes函数

    ~~~    axes函数类似于subplot函数,这里我使用它主要是为了限定子图形的大小。

axes与subplot区别详细解释见原文链接:
https://www.zhihu.com/question/51745620

scatter函数

    ~~~     函数中前两个参数是横纵坐标值,s=?此参数指的是图中点占的面积大小,cmap=?此参数指的是图中点颜色设置图。

scatter详细解释见原文链接:
https://blog.csdn.net/xiaobaicai4552/article/details/79065990

以上,部分解释属个人理解,如有错误还望原谅与批评指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值