k-mean的代码怎么写
时间: 2024-04-29 19:27:05 浏览: 94
K-mean的代码实现可以参考以下步骤:
1. 随机选取k个点作为初始簇中心
2. 对于每个样本点,计算其与每个簇中心的距离,将其归入距离最近的簇
3. 对于每个簇,重新计算簇中心
4. 重复步骤2和3,直到簇中心不再发生变化或达到最大迭代次数
以下是Python的实现代码示例:
```
import numpy as np
def k_means(X, k, max_iterations):
n_samples, n_features = X.shape
# Initialize cluster centers
centroids = X[np.random.choice(n_samples, k, replace=False)]
# Iterate until convergence or max_iterations
for i in range(max_iterations):
# Assign points to nearest cluster
clusters = [[] for _ in range(k)]
for idx, sample in enumerate(X):
distances = [np.linalg.norm(sample - centroid) for centroid in centroids]
nearest_centroid_idx = np.argmin(distances)
clusters[nearest_centroid_idx].append(idx)
# Update centroid position
new_centroids = np.zeros((k, n_features))
for cluster_idx, cluster in enumerate(clusters):
cluster_mean = np.mean(X[cluster], axis=0)
new_centroids[cluster_idx] = cluster_mean
# Check for convergence
if np.allclose(centroids, new_centroids):
break
centroids = new_centroids
return centroids, clusters
```
阅读全文