你能写代码实现随机生成2维坐标点,对点进行聚类,进行K=2,3,4,聚类并用matplot画图吗
时间: 2023-12-03 12:45:59 浏览: 158
当然可以,以下是Python代码实现:
```python
import random
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
# 随机生成二维坐标点
def generate_points(num):
points = []
for i in range(num):
x = random.uniform(0, 10)
y = random.uniform(0, 10)
points.append((x, y))
return points
# 对点进行聚类
def cluster_points(points, k):
kmeans = KMeans(n_clusters=k)
kmeans.fit(points)
return kmeans.labels_
# 画图
def plot_clusters(points, clusters, k):
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
for i in range(k):
cluster_points = [points[j] for j in range(len(points)) if clusters[j] == i]
plt.scatter([p[0] for p in cluster_points], [p[1] for p in cluster_points], c=colors[i])
plt.show()
# 测试
points = generate_points(100)
for k in range(2, 5):
clusters = cluster_points(points, k)
plot_clusters(points, clusters, k)
```
这段代码会随机生成100个二维坐标点,并对这些点进行K=2,3,4的聚类并用matplotlib画图展示。
阅读全文