我需要实现Kmeans聚类算法实现对一对点的聚类请给我python代码
时间: 2024-05-02 13:17:57 浏览: 37
以下是K-means聚类算法的Python实现:
```python
import numpy as np
def distance(point1, point2):
return np.sqrt(np.sum((point1 - point2) ** 2))
def kmeans(points, k):
n = points.shape[0]
centroids = points[np.random.choice(n, k, replace=False)]
clusters = [[] for _ in range(k)]
while True:
for point_idx, point in enumerate(points):
min_dist = np.inf
closest_centroid_idx = None
for centroid_idx, centroid in enumerate(centroids):
dist = distance(point, centroid)
if dist < min_dist:
min_dist = dist
closest_centroid_idx = centroid_idx
clusters[closest_centroid_idx].append(point_idx)
new_centroids = np.zeros((k, points.shape[1]))
for cluster_idx, cluster in enumerate(clusters):
cluster_mean = np.mean(points[cluster], axis=0)
new_centroids[cluster_idx] = cluster_mean
if np.allclose(new_centroids, centroids):
break
centroids = new_centroids
clusters = [[] for _ in range(k)]
return clusters
```
其中,distance函数用于计算两个点之间的欧几里得距离,kmeans函数实现了K-means聚类算法。它接受一个二维数组points,其中每一行表示一个点的坐标,以及一个整数k,表示需要将points分成k个簇。函数返回一个包含k个列表的列表clusters,每个列表表示一个簇,包含该簇中点的索引。
阅读全文