用python绘制聚类模型图
时间: 2024-10-05 10:02:43 浏览: 37
在Python中,你可以使用一些数据可视化库如`matplotlib`, `seaborn`, 或者专门用于可视化机器学习模型的`plotly`和` Yellowbrick`来绘制聚类模型图。以下是一个简单的例子,展示如何使用`scikit-learn`和`matplotlib`来绘制K-means聚类的结果:
```python
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import numpy as np
# 创建随机数据集
n_samples = 150
random_state = 170
X, _ = make_blobs(n_samples=n_samples, random_state=random_state)
# 使用K-means算法
kmeans = KMeans(n_clusters=3, random_state=random_state)
y_pred = kmeans.fit_predict(X)
# 绘制数据点及其聚类结果
plt.scatter(X[:, 0], X[:, 1], c=y_pred, cmap='viridis')
plt.title('K-means Clustering Result')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
# 显示轮廓线
plt.figure()
plt.scatter(X[:, 0], X[:, 1], c=y_pred, cmap='viridis')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.title('Silhouette Plot (showing the quality of clustering)')
from sklearn.metrics import silhouette_score
silhouette_avg = silhouette_score(X, y_pred)
plt.text(-0.05, 0.8, f'Silhouette Score: {silhouette_avg:.3f}',
transform=plt.gca().transAxes, fontsize=14)
plt.show()
阅读全文
相关推荐


















