你能写代码实现随机生成2维坐标点,对点进行聚类,进行K=2,3,4,聚类并用matplot画图吗,再写代码实现对鸢尾花进行K-means算法聚类,并用matplot画图吗,数据集是iris_training
时间: 2023-12-03 14:45:30 浏览: 72
当然可以,以下是代码实现:
随机生成2维坐标点进行聚类:
```python
import random
import matplotlib.pyplot as plt
# 随机生成100个坐标点
points = [(random.uniform(-10, 10), random.uniform(-10, 10)) for _ in range(100)]
# 初始化聚类中心
k = 4
centers = [(random.uniform(-10, 10), random.uniform(-10, 10)) for _ in range(k)]
# 迭代聚类过程
for _ in range(10):
clusters = [[] for _ in range(k)]
for point in points:
# 计算每个点到聚类中心的距离
distances = [((point[0]-center[0])**2 + (point[1]-center[1])**2)**0.5 for center in centers]
# 将点分配到距离最近的聚类中心的簇中
cluster_idx = distances.index(min(distances))
clusters[cluster_idx].append(point)
# 更新聚类中心
centers = [(sum([p[0] for p in cluster])/len(cluster), sum([p[1] for p in cluster])/len(cluster)) for cluster in clusters]
# 画图
colors = ['r', 'g', 'b', 'y']
for i, cluster in enumerate(clusters):
x = [p[0] for p in cluster]
y = [p[1] for p in cluster]
plt.scatter(x, y, c=colors[i])
plt.show()
```
对鸢尾花进行K-means算法聚类:
```python
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
# 加载数据集
iris = load_iris()
X = iris.data
# 进行K-means聚类
kmeans = KMeans(n_clusters=3)
kmeans.fit(X)
# 画图
colors = ['r', 'g', 'b']
for i in range(3):
idx = np.where(kmeans.labels_ == i)
plt.scatter(X[idx, 0], X[idx, 1], c=colors[i])
plt.show()
```
注意:对于iris数据集,由于其是4维数据,而我们只画出了前两维,因此聚类效果可能不是很好。
阅读全文