实现粒kmeans聚类算法的python代码
时间: 2023-05-26 16:06:57 浏览: 69
以下是一种基本的粒kmeans聚类算法的Python代码实现:
```python
import numpy as np
from typing import List
def kmeans(data: np.ndarray, k: int, max_iter: int = 300) -> List[np.ndarray]:
"""
:param data: shape: (n_samples, n_features)
:param k: number of clusters
:param max_iter: maximum number of iterations
:return: list of length k containing the centroids of the clusters
"""
n_samples = data.shape[0]
centroids = data[np.random.choice(n_samples, k, replace=False)]
for i in range(max_iter):
clusters = [[] for _ in range(k)]
for j, x in enumerate(data):
distances = np.linalg.norm(x - centroids, axis=1)
nearest_centroid = np.argmin(distances)
clusters[nearest_centroid].append(j)
new_centroids = np.zeros((k, data.shape[1]))
for cluster_index, cluster in enumerate(clusters):
if len(cluster) > 0:
new_centroids[cluster_index] = np.mean(data[cluster], axis=0)
else:
new_centroids[cluster_index] = centroids[cluster_index]
if np.allclose(new_centroids, centroids):
break
centroids = new_centroids
return centroids
```
这个函数将一组数据点(用 numpy 数组表示)和所需的聚类数作为参数,并返回一个列表,其中包含每个集群的质心。它首先随机初始化质心,然后在每次迭代中将每个数据点分配到最近的质心(使用欧几里得距离),然后更新每个质心的位置以使它们移向其分配的数据点的平均位置。该过程重复进行,直到质心稳定或达到最大迭代次数为止。
此实现的一个限制是,由于它使用欧几里得距离度量相似性,因此不能很好地处理高维数据或非欧几里得距离。此外,它可能会陷入局部最小值,特别是在处理非凸簇形状时。