Python | 实现 K-means 聚类——多维数据聚类散点图绘制
warning:
这篇文章距离上次修改已过186天,其中的内容可能已经有所变动。
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
# 生成模拟数据
def make_data(n_samples, n_features, centers=3, random_state=0):
np.random.seed(random_state)
centers = np.random.rand(centers, n_features)
cluster_std = 0.6
clusters = np.zeros((n_samples, n_features))
for i in range(centers.shape[0]):
clusters += np.random.normal(centers[i], cluster_std, size=(n_samples, n_features))
return clusters
# 绘制聚类散点图
def plot_clusters(X, y_pred, title=None):
# 为不同的聚类分配颜色
colors = np.array([x for _, x in plt.get_cmap('tab20b').colors])
for i in range(len(colors)):
plt.scatter(X[y_pred == i, 0], X[y_pred == i, 1], s=30, c=colors[i])
plt.title(title)
plt.show()
# 定义 K-means 聚类函数
def kmeans_cluster(X, n_clusters, max_iter=300):
kmeans = KMeans(n_clusters=n_clusters, max_iter=max_iter)
y_pred = kmeans.fit_predict(X)
title = f"K-Means Clustering with n_clusters = {n_clusters}, Silhouette Score: {silhouette_score(X, y_pred)}"
plot_clusters(X, y_pred, title)
# 使用函数进行聚类
n_samples = 3000
n_features = 2
n_clusters = 3
random_state = 1
X = make_data(n_samples, n_features, centers=n_clusters, random_state=random_state)
kmeans_cluster(X, n_clusters, max_iter=300)
这段代码首先定义了生成模拟数据和绘制聚类散点图的函数。然后定义了kmeans_cluster
函数,它使用scikit-learn库中的KMeans
算法对数据进行聚类,并计算和绘制聚类的散点图,其中包括每个样本的聚类预测结果和蒙轮机得分。最后,使用生成的模拟数据调用kmeans_cluster
函数进行聚类。
评论已关闭