用K均值算法编程一套算法
时间: 2023-11-30 17:42:43 浏览: 94
K均值算法是一种聚类算法,可以将数据按相似度分类。下面是使用Python实现K均值算法的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成随机数据
def create_data(num):
data = []
for i in range(num):
x = np.random.randint(0, 100)
y = np.random.randint(0, 100)
data.append([x, y])
return np.array(data)
# 计算两点之间的距离
def distance(p1, p2):
return np.sqrt(np.sum(np.square(p1 - p2)))
# K均值算法
def k_means(data, k):
# 随机选择k个点作为初始聚类中心
centers = data[np.random.choice(len(data), k, replace=False)]
while True:
# 初始化聚类结果
clusters = [[] for _ in range(k)]
# 将每个点分配到最近的聚类中心
for point in data:
distances = [distance(point, center) for center in centers]
cluster = np.argmin(distances)
clusters[cluster].append(point)
# 计算新的聚类中心
new_centers = []
for cluster in clusters:
if len(cluster) == 0:
new_centers.append(np.random.randint(0, 100, size=2))
else:
new_centers.append(np.mean(cluster, axis=0))
# 判断聚类中心是否变化
if np.allclose(centers, new_centers):
break
centers = new_centers
return centers, clusters
# 测试
data = create_data(100)
centers, clusters = k_means(data, 3)
colors = ['r', 'g', 'b']
for i, cluster in enumerate(clusters):
for point in cluster:
plt.scatter(point[0], point[1], c=colors[i])
for center in centers:
plt.scatter(center[0], center[1], c='k', marker='x')
plt.show()
```
该代码生成100个随机数据点,然后使用K均值算法将其分为3类,并在图中用不同颜色表示不同的类别。可以根据需要修改数据生成方式和聚类数目。
阅读全文
相关推荐















