使用python的sklearn库写出k-means算法的示例,要求使用不同的颜色标出不同聚类,使用不同形状的点标出聚类中心,并求出聚类中心并显示
时间: 2023-06-16 11:07:39 浏览: 51
下面是一个使用sklearn库实现k-means算法的示例代码,其中使用不同的颜色和形状标出不同聚类和聚类中心,最后输出聚类中心的坐标:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
# 生成随机数据
np.random.seed(0)
X = np.vstack([np.random.randn(100, 2) + [2, 2], np.random.randn(100, 2) + [-2, -2], np.random.randn(100, 2) + [2, -2]])
# 计算k-means
kmeans = KMeans(n_clusters=3)
kmeans.fit(X)
# 绘制聚类结果
plt.scatter(X[:, 0], X[:, 1], c=kmeans.labels_, cmap='viridis')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], marker='^', s=100, linewidths=1, color='black')
plt.title('K-means Clustering')
plt.show()
# 输出聚类中心坐标
print("Cluster centers:")
print(kmeans.cluster_centers_)
```
运行结果如下图所示,其中不同的颜色代表不同的聚类,不同形状的点代表聚类中心,并且输出了聚类中心的坐标:
![k-means clustering](https://i.imgur.com/9qL9D4t.png)