当前位置:   article > 正文

【机器学习】聚类代码练习

len(indices[0])).ravel()

本课程是中国大学慕课《机器学习》的“聚类”章节的课后代码。

课程地址:

https://www.icourse163.org/course/WZU-1464096179

课程完整代码:

https://github.com/fengdu78/WZU-machine-learning-course

代码修改并注释:黄海广,haiguang2000@wzu.edu.cn

在本练习中,我们将实现K-means聚类,并使用它来压缩图像。我们将从一个简单的2D数据集开始,以了解K-means是如何工作的,然后我们将其应用于图像压缩。我们还将对主成分分析进行实验,并了解如何使用它来找到面部图像的低维表示。

K-means 聚类

我们将实施和应用K-means到一个简单的二维数据集,以获得一些直观的工作原理。K-means是一个迭代的,无监督的聚类算法,将类似的实例组合成簇。该算法通过猜测每个簇的初始聚类中心开始,然后重复将实例分配给最近的簇,并重新计算该簇的聚类中心。我们要实现的第一部分是找到数据中每个实例最接近的聚类中心的函数。

  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. import seaborn as sb
  5. from scipy.io import loadmat
  1. def find_closest_centroids(X, centroids):
  2.     m = X.shape[0]
  3.     k = centroids.shape[0]
  4.     idx = np.zeros(m)
  5.     for i in range(m):
  6.         min_dist = 1000000
  7.         for j in range(k):
  8.             dist = np.sum((X[i, :] - centroids[j, :])**2)
  9.             if dist < min_dist:
  10.                 min_dist = dist
  11.                 idx[i] = j
  12.     return idx

让我们来测试这个函数,以确保它的工作正常。我们将使用练习中提供的测试用例。

  1. data2 = pd.read_csv('data/ex7data2.csv')
  2. data2.head()

X1X2
01.8420804.607572
15.6585834.799964
26.3525793.290854
32.9040174.612204
43.2319794.939894
X=data2.values
  1. initial_centroids = initial_centroids = np.array([[33], [62], [85]])
  2. idx = find_closest_centroids(X, initial_centroids)
  3. idx[0:3]
array([0., 2., 1.])

输出与文本中的预期值匹配(记住我们的数组是从零开始索引的,而不是从一开始索引的,所以值比练习中的值低一个)。接下来,我们需要一个函数来计算簇的聚类中心。聚类中心只是当前分配给簇的所有样本的平均值。

  1. sb.set(context="notebook", style="white")
  2. sb.lmplot(x='X1', y='X2', data=data2, fit_reg=False)
  3. plt.show()
043b84d782530955f6c738d95d9679aa.png
  1. def compute_centroids(X, idx, k):
  2.     m, n = X.shape
  3.     centroids = np.zeros((k, n))
  4.     for i in range(k):
  5.         indices = np.where(idx == i)
  6.         centroids[i, :] = (np.sum(X[indices, :], axis=1) /
  7.                            len(indices[0])).ravel()
  8.     return centroids
compute_centroids(data2.values, idx, 3)
  1. array([[2.42830111, 3.15792418],
  2. [5.81350331, 2.63365645],
  3. [7.11938687, 3.6166844 ]])

此输出也符合练习中的预期值。下一部分涉及实际运行该算法的一些迭代次数和可视化结果。这个步骤是由于并不复杂,我将从头开始构建它。为了运行算法,我们只需要在将样本分配给最近的簇并重新计算簇的聚类中心。

  1. def run_k_means(X, initial_centroids, max_iters):
  2.     m, n = X.shape
  3.     k = initial_centroids.shape[0]
  4.     idx = np.zeros(m)
  5.     centroids = initial_centroids
  6.     
  7.     for i in range(max_iters):
  8.         idx = find_closest_centroids(X, centroids)
  9.         centroids = compute_centroids(X, idx, k)
  10.     
  11.     return idx, centroids
idx, centroids = run_k_means(X, initial_centroids, 10)
  1. cluster1 = X[np.where(idx == 0)[0],:]
  2. cluster2 = X[np.where(idx == 1)[0],:]
  3. cluster3 = X[np.where(idx == 2)[0],:]
  4. fig, ax = plt.subplots(figsize=(15,10))
  5. ax.scatter(cluster1[:,0], cluster1[:,1], s=30, color='r', label='Cluster 1')
  6. ax.scatter(cluster2[:,0], cluster2[:,1], s=30, color='g', label='Cluster 2')
  7. ax.scatter(cluster3[:,0], cluster3[:,1], s=30, color='b', label='Cluster 3')
  8. ax.legend()
  9. plt.show()
c5b03fe1fdd2b691e606777c13a79252.png

我们跳过的一个步骤是初始化聚类中心的过程。这可以影响算法的收敛。我们的任务是创建一个选择随机样本并将其用作初始聚类中心的函数。

  1. def init_centroids(X, k):
  2.     m, n = X.shape
  3.     centroids = np.zeros((k, n))
  4.     idx = np.random.randint(0, m, k)
  5.     for i in range(k):
  6.         centroids[i, :] = X[idx[i], :]
  7.     return centroids
init_centroids(X, 3)
  1. array([[1.52334113, 4.87916159],
  2. [3.06192918, 1.5719211 ],
  3. [1.75164337, 0.68853536]])

k值的选择

使用“肘部法则”选取k值

  1. from sklearn.cluster import KMeans
  2. '利用SSE选择k'
  3. SSE = []  # 存放每次结果的误差平方和
  4. for k in range(19):
  5.     estimator = KMeans(n_clusters=k)  # 构造聚类器
  6.     estimator.fit(data2)
  7.     SSE.append(estimator.inertia_)
  8. X = range(19)
  9. plt.figure(figsize=(1510))
  10. plt.xlabel('k')
  11. plt.ylabel('SSE')
  12. plt.plot(X, SSE, 'o-')
  13. plt.show()
a17874d4260bd102b997a1f2e92b2100.png

图中可以看出,k=3的时候是肘点,所以,选择k=3.

K-means图像压缩

我们的下一个任务是将K-means应用于图像压缩。从下面的演示可以看到,我们可以使用聚类来找到最具代表性的少数颜色,并使用聚类分配将原始的24位颜色映射到较低维的颜色空间。

下面是我们要压缩的图像。

  1. from IPython.display import Image
  2. Image(filename='data/bird_small.png')
064db702723ed8104afba9155a6dff5a.png

The raw pixel data has been pre-loaded for us so let's pull it in.

  1. image_data = loadmat('data/bird_small.mat')
  2. # image_data
  1. A = image_data['A']
  2. A.shape
(128, 128, 3)

现在我们需要对数据应用一些预处理,并将其提供给K-means算法。

  1. # normalize value ranges
  2. A = A / 255.
  3. # reshape the array
  4. X = np.reshape(A, (A.shape[0] * A.shape[1], A.shape[2]))
  5. X.shape
(16384, 3)
  1. # randomly initialize the centroids
  2. initial_centroids = init_centroids(X, 16)
  3. # run the algorithm
  4. idx, centroids = run_k_means(X, initial_centroids, 10)
  5. # get the closest centroids one last time
  6. idx = find_closest_centroids(X, centroids)
  7. map each pixel to the centroid value
  8. X_recovered = centroids[idx.astype(int),:]
  9. X_recovered.shape
(16384, 3)
  1. # reshape to the original dimensions
  2. X_recovered = np.reshape(X_recovered, (A.shape[0], A.shape[1], A.shape[2]))
  3. X_recovered.shape
(128, 128, 3)
  1. plt.imshow(X_recovered)
  2. plt.show()
4716d070def8756b69a734ab2cc04305.png

您可以看到我们对图像进行了压缩,但图像的主要特征仍然存在。这就是K-means。下面我们来用scikit-learn来实现K-means。

  1. from skimage import io
  2. # cast to float, you need to do this otherwise the color would be weird after clustring
  3. pic = io.imread('data/bird_small.png') / 255.
  4. io.imshow(pic)
  5. plt.show()
213e381d842d8cc0788ff1d9334b0d06.png
pic.shape
(128, 128, 3)
  1. # serialize data
  2. data = pic.reshape(128*1283)
data.shape
(16384, 3)
  1. from sklearn.cluster import KMeans#导入kmeans库
  2. model = KMeans(n_clusters=16, n_init=100)
model.fit(data)
KMeans(n_clusters=16, n_init=100)
  1. centroids = model.cluster_centers_
  2. print(centroids.shape)
  3. C = model.predict(data)
  4. print(C.shape)
  1. (16, 3)
  2. (16384,)
centroids[C].shape
(16384, 3)
compressed_pic = centroids[C].reshape((128,128,3))
  1. fig, ax = plt.subplots(12)
  2. ax[0].imshow(pic)
  3. ax[1].imshow(compressed_pic)
  4. plt.show()
1750445ca1c2bfed9f631977bd396849.png

密度聚类

DBSCAN(Density-Based Spatial Clustering of Applications with Noise)是一个比较有代表性的基于密度的聚类算法。与划分和层次聚类方法不同,它将簇定义为密度相连的点的最大集合,能够把具有足够高密度的区域划分为簇,并可在噪声的空间数据库中发现任意形状的聚类。

  1. import numpy as np
  2. from sklearn.cluster import DBSCAN
  3. from sklearn import metrics
  4. from sklearn.datasets import make_blobs
  5. from sklearn.preprocessing import StandardScaler
  1. import matplotlib.pyplot as plt
  2. plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
  3. plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

创建样本数据

  1. centers = [[11], [-1-1], [1-1]]
  2. X, labels_true = make_blobs(
  3.     n_samples=750, centers=centers, cluster_std=0.4, random_state=0
  4. )

标准化数据

X = StandardScaler().fit_transform(X)

在DBSCAN使用两个超参数:

扫描半径 (eps)和最小包含点数(minPts)来获得簇的数量,而不是猜测簇的数目。

  • (1)扫描半径 (eps) : 用于定位点/检查任何点附近密度的距离度量,即扫描半径。

  • (2)最小包含点数(minPts) :聚集在一起的最小点数(阈值),该区域被认为是稠密的。

我们定义一个plot_dbscan(MyEps, MiniSample)函数,MyEps代表epsMiniSample代表minPts

  1. def plot_dbscan(MyEps, MiniSample):
  2.     db = DBSCAN(eps=MyEps, min_samples=MiniSample).fit(X)
  3.     core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
  4.     core_samples_mask[db.core_sample_indices_] = True
  5.     labels = db.labels_
  6.     # 标签中的簇数,忽略噪声点(如果存在)。
  7.     n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
  8.     n_noise_ = list(labels).count(-1)
  9.     print("估计的簇的数量: %d" % n_clusters_)
  10.     print("估计的噪声点数量: %d" % n_noise_)
  11.     print("同一性(Homogeneity): %0.4f" %
  12.           metrics.homogeneity_score(labels_true, labels))
  13.     print("完整性(Completeness): %0.4f" %
  14.           metrics.completeness_score(labels_true, labels))
  15.     print("V-measure: %0.3f" % metrics.v_measure_score(labels_true, labels))
  16.     print("ARI(Adjusted Rand Index): %0.4f" %
  17.           metrics.adjusted_rand_score(labels_true, labels))
  18.     print("AMI(Adjusted Mutual Information): %0.4f" %
  19.           metrics.adjusted_mutual_info_score(labels_true, labels))
  20.     print("轮廓系数(Silhouette Coefficient): %0.4f" %
  21.           metrics.silhouette_score(X, labels))
  22.     # #############################################################################
  23.     # 画出结果
  24.     # 黑色点代表噪声点
  25.     unique_labels = set(labels)
  26.     colors = [
  27.         plt.cm.Spectral(each) for each in np.linspace(01len(unique_labels))
  28.     ]
  29.     for k, col in zip(unique_labels, colors):
  30.         if k == -1:
  31.             # Black used for noise.
  32.             col = [0011]
  33.         class_member_mask = labels == k
  34.         xy = X[class_member_mask & core_samples_mask]
  35.         plt.plot(
  36.             xy[:, 0],
  37.             xy[:, 1],
  38.             "o",
  39.             markerfacecolor=tuple(col),
  40.             markeredgecolor="k",
  41.             markersize=14,
  42.         )
  43.         xy = X[class_member_mask & ~core_samples_mask]
  44.         plt.plot(
  45.             xy[:, 0],
  46.             xy[:, 1],
  47.             "o",
  48.             markerfacecolor=tuple(col),
  49.             markeredgecolor="k",
  50.             markersize=6,
  51.         )
  52.     plt.title("簇的数量为: %d" % n_clusters_, fontsize=18)
  53. #     plt.savefig(str(MyEps) + str(MiniSample) + '.png')#保存图片
  54.     plt.show()
plot_dbscan(0.310)
  1. 估计的簇的数量: 3
  2. 估计的噪声点数量: 18
  3. 同一性(Homogeneity): 0.9530
  4. 完整性(Completeness): 0.8832
  5. V-measure: 0.917
  6. ARI(Adjusted Rand Index): 0.9517
  7. AMI(Adjusted Mutual Information): 0.9165
  8. 轮廓系数(Silhouette Coefficient): 0.6255
157c50a4c1207ffac2277f7f9fcd7c9c.png
plot_dbscan(0.110)
  1. 估计的簇的数量: 12
  2. 估计的噪声点数量: 516
  3. 同一性(Homogeneity): 0.3128
  4. 完整性(Completeness): 0.2489
  5. V-measure: 0.277
  6. ARI(Adjusted Rand Index): 0.0237
  7. AMI(Adjusted Mutual Information): 0.2673
  8. 轮廓系数(Silhouette Coefficient): -0.3659
e7360b366b3bda1afe5145c38c8c7164.png
plot_dbscan(0.410)
  1. 估计的簇的数量: 1
  2. 估计的噪声点数量: 2
  3. 同一性(Homogeneity): 0.0010
  4. 完整性(Completeness): 0.0586
  5. V-measure: 0.002
  6. ARI(Adjusted Rand Index): -0.0000
  7. AMI(Adjusted Mutual Information): -0.0011
  8. 轮廓系数(Silhouette Coefficient): 0.0611
6b5c0316c989e907c8e5a9a2d48775b6.png
plot_dbscan(0.36)
  1. 估计的簇的数量: 2
  2. 估计的噪声点数量: 13
  3. 同一性(Homogeneity): 0.5365
  4. 完整性(Completeness): 0.8263
  5. V-measure: 0.651
  6. ARI(Adjusted Rand Index): 0.5414
  7. AMI(Adjusted Mutual Information): 0.6495
  8. 轮廓系数(Silhouette Coefficient): 0.3845
42ee02bfd5a8e3c57719a1c17b7bae6f.png

可以看到,当扫描半径 (eps)为0.3,同时最小包含点数(minPts)为10的时候,评价指标最高。

层次聚类

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
  4. plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
  5. from scipy.cluster.hierarchy import dendrogram
  6. from sklearn.datasets import load_iris
  7. from sklearn.cluster import AgglomerativeClustering
  1. def plot_dendrogram(model, **kwargs):
  2.     # 创建链接矩阵,然后绘制树状图
  3.     # 创建每个节点下的样本计数
  4.     counts = np.zeros(model.children_.shape[0])
  5.     n_samples = len(model.labels_)
  6.     for i, merge in enumerate(model.children_):
  7.         current_count = 0
  8.         for child_idx in merge:
  9.             if child_idx < n_samples:
  10.                 current_count += 1  # leaf node
  11.             else:
  12.                 current_count += counts[child_idx - n_samples]
  13.         counts[i] = current_count
  14.     linkage_matrix = np.column_stack(
  15.         [model.children_, model.distances_, counts]
  16.     ).astype(float)
  17.     # 绘制相应的树状图
  18.     dendrogram(linkage_matrix, **kwargs)
  1. iris = load_iris()
  2. X = iris.data
  1. # 设置距离阈值=0可确保计算完整的树。
  2. model = AgglomerativeClustering(distance_threshold=0, n_clusters=None)
  3. model = model.fit(X)
  1. plt.title("层次聚类树状图")
  2. # 绘制树状图的前三级
  3. plot_dendrogram(model, truncate_mode="level", p=3)
  4. plt.xlabel("节点中的点数(如果没有括号,则为点索引)")
  5. plt.show()
ed25e142fc080f6671513b9369c3c541.png

参考

  • Prof. Andrew Ng. Machine Learning. Stanford University

  • https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html

  • https://scikit-learn.org/stable/auto_examples/cluster

 
 
 
 
 
 
 
 
 
 
  1. 往期精彩回顾
  2. 适合初学者入门人工智能的路线及资料下载机器学习及深度学习笔记等资料打印机器学习在线手册深度学习笔记专辑《统计学习方法》的代码复现专辑
  3. AI基础下载黄海广老师《机器学习课程》视频课黄海广老师《机器学习课程》711页完整版课件

本站qq群955171419,加入微信群请扫码:

2fbc835b8aa9a714ebd59cc79a71d617.png

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/750384
推荐阅读
相关标签
  

闽ICP备14008679号