一、Kmeans重要属性:labels_
重要属性 labels_,表示查看聚好的类别,每个样本所对应的类。
二、尝试在代码框回答以下问题:
首先,我们来自己创建一个数据集。这样的数据集是我们自己创建,所以是有标签的。
(1) 导入需要的模块、库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
plt.style.use('ggplot')
(2)自建数据集
#生成500*2的数据集,每一组数据可以有4个中心点,即数据集有4个标签
X, y = make_blobs(n_samples=500,
n_features=2,centers=4,random_state=1)
(3)使用labels_查看聚好的类别
n_clusters = 3 # 设定聚类簇数
cluster = KMeans(n_clusters=n_clusters, random_state=0).fit(X)
y_pred = cluster.labels_
y_pred
输出为:
array([0, 0, 2, 1, 2, 1, 2, 2, 2, 2, 0, 0, 2, 1, 2, 0, 2, 0, 1, 2, 2, 2,
2, 1, 2, 2, 1, 1, 2, 2, 0, 1, 2, 0, 2, 0, 2, 2, 0, 2, 2, 2, 1, 2…])
知识点扩充
(1) KMeans因为并不需要建立模型或者预测结果,因此只需要fit就能够得到聚类结果了
(2) KMeans也有接口predict和fit_predict:
(3) 小节:分类器.fit(X).predict的结果= 分类器.fit_predict(X)=分类器.fit(X).labels_
fit_pre = KMeans(n_clusters=3, random_state=0).fit_predict(X)
(cluster.predict(X)==fit_pre).sum()
(fit_pre== cluster.labels_).sum()
是不是发现运行结果是一致的呢? (尝试输出运行结果)
我们什么时候需要predict呢?当数据量太大的时候!
其实我们不必使用所有的数据来寻找质心,少量的数据就可以帮助我们确定质心了。
当我们数据量非常大的时候,我们可以使用部分数据来帮助我们确认质心,剩下的数据的聚类结果,使用predict来调用。
cluster_smallsub = KMeans(n_clusters=n_clusters, random_state=0).fit(X[:200])
sample_pred = cluster_smallsub.predict(X)
y_pred == sample_pred
输出为:
array([False, False, True, False, True, False, True, True, True,
True, False, False, True…])
注: 这样的结果,肯定与直接 fit 全部数据会不一致。有时候,当不要求那么精确,或者数据量实在太大,那可以使用这样的方法。