使用sklearn对iris数据集进行聚类分析

导入库

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
from sklearn.preprocessing import MinMaxScaler

%matplotlib inline
sns.set(style="white")
pd.set_option("display.max_rows", 1000)

sklearn自带iris数据集(nrow=150)

  • 4个预测变量
  • 3分类结局
iris = load_iris()
X = iris["data"]
Y = iris["target"]

display(X[:5])
display(pd.Series(Y).value_counts())

Y = Y.reshape(-1, 1) # Y的形状转换为[150, 1]
array([[5.1, 3.5, 1.4, 0.2],
       [4.9, 3. , 1.4, 0.2],
       [4.7, 3.2, 1.3, 0.2],
       [4.6, 3.1, 1.5, 0.2],
       [5. , 3.6, 1.4, 0.2]])

2    50
1    50
0    50
dtype: int64
data = pd.DataFrame(np.concatenate((X, Y), axis=1),
                    columns=["x1", "x2", "x3", "x4", "y"])
data["y"] = data["y"].astype("int64")
data.head()   
x1x2x3x4y
05.13.51.40.20
14.93.01.40.20
24.73.21.30.20
34.63.11.50.20
45.03.61.40.20

观察数据分布

4个预测变量两两散点图

sns.pairplot(data, hue="y")

数据标准化

Kmeans聚类前应对数据进行标准化

scaler = MinMaxScaler()
data.iloc[:, :4] = scaler.fit_transform(data.iloc[:, :4])
data.head()
x1x2x3x4y
00.2222220.6250000.0677970.0416670
10.1666670.4166670.0677970.0416670
20.1111110.5000000.0508470.0416670
30.0833330.4583330.0847460.0416670
40.1944440.6666670.0677970.0416670

设置类别数为3,进行Kmeans聚类

clus = KMeans(n_clusters=3)
clus = clus.fit(data.iloc[:, 1:4])

聚类完成后150个样本的聚类标签

clus.labels_
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], dtype=int32)

聚类完成后三个聚类中心

clus.cluster_centers_
array([[0.595     , 0.07830508, 0.06083333],
       [0.2975    , 0.55661017, 0.50583333],
       [0.42916667, 0.76745763, 0.8075    ]])

聚类的评估指标

clus.inertia_
4.481991774793322

确定最佳聚类数目

尝试不同的类别数,查看criterion值(越小越好),画出“肘线图”

L = []
for i in range(1, 9):
    clus = KMeans(n_clusters=i)
    clus.fit(data.iloc[:, 1:3])
    L.append([i, clus.inertia_])
L = pd.DataFrame(L, columns=["k", "criterion"])
L
kcriterion
0118.253249
125.106290
233.312646
342.585065
451.946648
561.637264
671.387541
781.175937
sns.pointplot(x="k", y="criterion", data=L)
sns.despine()

output_24_0

根据选定的聚类模型,对样本进行预测

从“肘线图”可看出最佳类别数等于3或4较好,此处使用3

clus = KMeans(n_clusters=3)
clus = clus.fit(data.iloc[:, 1:4])
data["pred"] = clus.predict(data.iloc[:, 1:4])

data.loc[data["pred"] == 0, "Pred"] = 11
data.loc[data["pred"] == 1, "Pred"] = 0
data.loc[data["pred"] == 2, "Pred"] = 2
data.loc[data["Pred"] == 11, "Pred"] = 1
data["Pred"] = data["Pred"].astype("int64")
data.head()
x1x2x3x4ypredPred
00.2222220.6250000.0677970.041667010
10.1666670.4166670.0677970.041667010
20.1111110.5000000.0508470.041667010
30.0833330.4583330.0847460.041667010
40.1944440.6666670.0677970.041667010

画出预测混淆矩阵,计算准确率

df = pd.crosstab(data["y"], data["Pred"])
df
Pred012
y
05000
10464
20446
L = []
for i in range(df.shape[0]):
    for j in range(df.shape[1]):
        if i != j:
            L.append(df.iloc[i, j])
print("预测准确率为:", round((150 - sum(L)) / 150 * 100, 1), "%")
预测准确率为: 94.7 %
  • 9
    点赞
  • 77
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值