文章最后更新于 1555 天前,其中的信息可能已经过时。
k-means 算法基础原理
本文注重对 k-means 算法的实现作出分析,基础原理不作赘述。
k-means 算法的特点
1. k-means 算法的基本概念:
- k 代表分为几个簇
- means 表示寻求新质心点的时候采用求均值的方法
2. k-means 算法的特点:
- k-means 算法与 knn 算法类似,都是需要“聚类”
- k-means 算法是无监督学习算法的一种
k-means 算法的实现步骤:
- 随机选取 K 个对象,并以它们为质心;
- 计算数据集样本点到质心的距离;
- 根据样本点距离质心的距离将其分簇(类),距离哪个近,划分到哪个簇(类);
- 以簇内所有样本点的均值重新计算质心,,然后重复第二步,直到划分的簇(类)不在变化后停止。
k-means 算法代码实现
模块的导入与 K 均值聚类算法类的定义
1import random2
3import numpy as np4from matplotlib import pyplot as plt5
6
7class KMeans:8 """9 K-means clustering(K均值聚类)10 """11
12 def __init__(self, n_clusters: int, iterations=100, eps=1e-3):13 """14 Args:15 n_clusters (int): 聚类类别数.16 iterations (int, optional): 迭代次数, 默认为100.17 eps (float, optional): 中心点最小更新量, 默认为1e-3.18 """19 self.n_clusters, self.iterations, self.eps, self.centers = n_clusters, iterations, eps, None20
21 def fit(self, X: np.ndarray):22 """23 Args:24 X (np.ndarray): 输入25 """26 # 随机选择k个点作为中心点27 self.centers = X[random.sample(range(len(X)), self.n_clusters)] # range(len(X))返回一个迭代对象 random.sample截取一段数字返回一个列表28
29 for _ in range(self.iterations):30 y_pred = self(X)31
32 # 各类别的均值作为新的中心点,33 centers = np.stack(34 [35 # 存在元素属于类别i则计算类别i所有点的均值,否则随机选择一个点作为类别i的均值36 np.mean(X[y_pred == i], axis=0) if np.any(y_pred == i) else random.choice(X) for i in range(self.n_clusters) # np.any()用于判读真假,37 ]38 )39
40 # 中心点最大更新值小于eps则停止迭代41 if np.abs(self.centers - centers).max() < self.eps:42 break43
44 # 将更新后的均值作为各类别中心点45 self.centers = centers46
47 def __call__(self, X: np.ndarray):48 return np.array([np.argmin(np.linalg.norm(self.centers - x, axis=1)) for x in X]) # 每一点类别为最近的中心点类别,返回下标随机生成测试集
1def load_data(n_samples_per_class=200, n_classes=5):2 X = np.concatenate([np.random.randn(n_samples_per_class, 2) + 3 * np.random.randn(2) for _ in range(n_classes)])3 y = np.concatenate([np.full(n_samples_per_class, label) for label in range(n_classes)])4 return X, y画出图像,实现聚类算法
1if __name__ == "__main__":2 n_classes = 53 X, y = load_data(n_classes=n_classes)4
5 plt.figure(figsize=[12, 6])6 plt.subplot(1, 2, 1)7 plt.title("Ground Truth")8 for label in range(n_classes):9 plt.scatter(X[y == label, 0], X[y == label, 1], marker=".")10
11 kmeans = KMeans(n_clusters=n_classes)12 kmeans.fit(X)13 y_pred = kmeans(X)14
15 plt.subplot(1, 2, 2)16 plt.title("Clustering")17 for label in range(n_classes):18 plt.scatter(X[y_pred == label, 0], X[y_pred == label, 1], marker=".")19
20 plt.scatter(kmeans.centers[:, 0], kmeans.centers[:, 1], marker="*")21
22 plt.show()完整代码
1#!/user/bin/env python32# -*- coding: utf-8 -*-3
4import random5
6import numpy as np7from matplotlib import pyplot as plt8
9
10class KMeans:11 """12 K-means clustering(K均值聚类)13 """14
15 def __init__(self, n_clusters: int, iterations=100, eps=1e-3):16 """17 Args:18 n_clusters (int): 聚类类别数.19 iterations (int, optional): 迭代次数, 默认为100.20 eps (float, optional): 中心点最小更新量, 默认为1e-3.21 """22 self.n_clusters, self.iterations, self.eps, self.centers = n_clusters, iterations, eps, None23
24 def fit(self, X: np.ndarray):25 """26 Args:27 X (np.ndarray): 输入28 """29 # 随机选择k个点作为中心点30 self.centers = X[random.sample(range(len(X)), self.n_clusters)] # range(len(X))返回一个迭代对象 random.sample截取一段数字返回一个列表31
32 for _ in range(self.iterations):33 y_pred = self(X)34
35 # 各类别的均值作为新的中心点,36 centers = np.stack(37 [38 # 存在元素属于类别i则计算类别i所有点的均值,否则随机选择一个点作为类别i的均值39 np.mean(X[y_pred == i], axis=0) if np.any(y_pred == i) else random.choice(X) for i in range(self.n_clusters) # np.any()用于判读真假,40 ]41 )42
43 # 中心点最大更新值小于eps则停止迭代44 if np.abs(self.centers - centers).max() < self.eps:45 break46
47 # 将更新后的均值作为各类别中心点48 self.centers = centers49
50 def __call__(self, X: np.ndarray):51 return np.array([np.argmin(np.linalg.norm(self.centers - x, axis=1)) for x in X]) # 每一点类别为最近的中心点类别,返回下标52
53
54def load_data(n_samples_per_class=200, n_classes=5):55 X = np.concatenate([np.random.randn(n_samples_per_class, 2) + 3 * np.random.randn(2) for _ in range(n_classes)])56 y = np.concatenate([np.full(n_samples_per_class, label) for label in range(n_classes)])57 return X, y58
59
60if __name__ == "__main__":61 n_classes = 562 X, y = load_data(n_classes=n_classes)63
64 plt.figure(figsize=[12, 6])65 plt.subplot(1, 2, 1)66 plt.title("Ground Truth")67 for label in range(n_classes):68 plt.scatter(X[y == label, 0], X[y == label, 1], marker=".")69
70 kmeans = KMeans(n_clusters=n_classes)71 kmeans.fit(X)72 y_pred = kmeans(X)73
74 plt.subplot(1, 2, 2)75 plt.title("Clustering")76 for label in range(n_classes):77 plt.scatter(X[y_pred == label, 0], X[y_pred == label, 1], marker=".")78
79 plt.scatter(kmeans.centers[:, 0], kmeans.centers[:, 1], marker="*")80
81 plt.show()- 文章作者:
- 希亚的西红柿
- 版权声明:
- 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自希亚的西红柿のBlog!
相关推荐
评论
评论加载中…
