Python学习资料整理

K-means聚类及Python实战

2019-07-07  本文已影响122人  惑也

一、参数与方法

  1. scikit-learn中用于进行k-means机器学习的类是sklearn.cluster.KMeans,它所涉及的参数有超过10个之多,但是最常用的其实就是n_clusters 和random_state;
  2. n_clusters表示打算聚类的数目,默认情况下是8;
  3. random_state表示产生随机数的方法。默认缺省值为None,此时随机数产生器是np.random所使用的RandomState实例。可以自定义一个RandomState实例类型作为参数,也可以使用一个整数来作为参数,此时这个整数表示产生随机数的种子,即类编号的qi shi zhi;
  4. 常用方法

二、聚类步骤

  1. 导入包,准备数据
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt

x = np.array([[15, 17], [12,18], [14,15], [13,16], [12,15], [16,12], 
              [4,6], [5,8], [5,3], [7,4], [7,2], [6,5]])
  1. 聚类分析前,需要确定聚类数目。数据量较少时,可以直接通过观察数据,确定类别,本例中数据,很明显可以看出,聚类数目设置为2比较合适;数据量较多时,可以按比例随机抽样,画散点图来观察聚类数目;当数据量特别大时,可以通过误差平方和的方式,来确定聚类数据;
  2. 进行k-means聚类,使用fit_predit()函数,为数据加上聚类标签;
y_pred= KMeans(n_clusters=2).fit_predict(x)
y_pred
array([1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], dtype=int32)
  1. 可视化聚类效果,一类设置为红色,另一类设置为绿色;
plt.figure(figsize=(6, 6))
color = ("red", "green")
colors = np.array(color)[y_pred]
plt.scatter(x[:, 0], x[:, 1], c=colors)
plt.show()
  1. 基于上面的聚类结果,通过fit()函数和predict()函数,为新增加的2个元素,预测分类;
kmeans = KMeans(n_clusters=2).fit(x)
new_data = np.array([[3, 3], [15, 15]])

# 预测分类的结果
new_kmeans = kmeans.predict(new_data)
new_kmeans
array([1, 0], dtype=int32)

三、图片处理实例

  1. 需求说明
  1. 聚类
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances_argmin
from sklearn.datasets import load_sample_image
from sklearn.utils import shuffle
n_colors = 64    # 聚类数目为64
china = load_sample_image('china.jpg')
china = np.array(china, dtype=np.float64) / 255    # 读取照片像素值,并将其转化到[0, 1]
w, h, d = original_shape = tuple(china.shape)
image_array = china.reshape(w * h, d)
# 随机排列,取前1000
image_array_sample = shuffle(image_array, random_state=0)[:1000]  

# 聚类,构建模型
kmeans = KMeans(n_clusters=n_colors, random_state=0).fit(image_array_sample)
labels = kmeans.predict(image_array)
  1. 重建图像
def recreate_image(center_data, labels, w, h):
    """基于模型中心,构建图片"""
    
    d = center_data.shape[1]
    image = np.zeros((w, h, d))
    labels_index = 0
    for i in range(w):
        for j in range(h):
            image[i][j] = center_data[labels[labels_index]]
            labels_index += 1
    return image 
ax = plt.axes([0, 0, 2, 2])
plt.axis('off')
plt.title('Quantized image (64 colors, K-Means)')
plt.imshow(recreate_image(kmeans.cluster_centers_, labels, w, h))
上一篇 下一篇

猜你喜欢

热点阅读