python写一个kmeans
时间: 2023-10-11 08:09:56 浏览: 31
好的,以下是一个简单的 Python K-Means 实现:
```python
import numpy as np
class KMeans:
def __init__(self, k, max_iterations=100):
self.k = k
self.max_iterations = max_iterations
def fit(self, data):
# 随机选择 k 个中心点
centers = data[np.random.choice(len(data), self.k, replace=False)]
for i in range(self.max_iterations):
# 分配每个数据点到最近的中心点
clusters = [[] for _ in range(self.k)]
for point in data:
distances = np.linalg.norm(centers - point, axis=1)
cluster = np.argmin(distances)
clusters[cluster].append(point)
# 计算新的中心点
new_centers = np.zeros_like(centers)
for i, cluster in enumerate(clusters):
if len(cluster) == 0:
# 如果一个簇没有任何数据点,那么这个簇的中心点不变
new_centers[i] = centers[i]
else:
new_centers[i] = np.mean(cluster, axis=0)
# 如果新的中心点和旧的中心点相同,那么算法已经收敛,结束循环
if np.allclose(centers, new_centers):
break
centers = new_centers
return centers, clusters
```
这里定义了一个 KMeans 类,构造函数中传入 k 和最大迭代次数(默认为 100)。fit 方法接收一个数据集作为参数,并返回最终的 k 个中心点和每个数据点所属的簇。