k_means++不调用sklearn的python代码
时间: 2023-11-06 16:04:38 浏览: 78
好的,下面是一个示例的 K-Means 算法的 Python 代码,不需要使用 sklearn:
```
import numpy as np
import random
def k_means(data, k, max_iter=100):
# 初始化质心
centroids = random.sample(list(data), k)
for i in range(max_iter):
# 分配数据点到最近的质心
clusters = [[] for _ in range(k)]
for point in data:
distances = [np.linalg.norm(point - c) for c in centroids]
cluster_idx = np.argmin(distances)
clusters[cluster_idx].append(point)
# 更新质心
new_centroids = []
for cluster in clusters:
if len(cluster) > 0:
new_centroids.append(np.mean(cluster, axis=0))
else:
new_centroids.append(random.choice(list(data)))
centroids = new_centroids
return centroids
```
希望能够帮到你!
阅读全文