机器学习》23-实验四 手写体数字图像聚类参考代码[2页]

2023-01-12 05:22:17   第一文档网     [ 字体: ] [ 阅读: ] [ 文档下载 ]

#第一文档网# 导语】以下是®第一文档网的小编为您整理的《机器学习》23-实验四 手写体数字图像聚类参考代码[2页]》,欢迎阅读!
手写体,图像,机器,参考,实验
import numpy as np

from matplotlib import pyplot as plt from sklearn import manifold, datasets

X, y = datasets.load_digits(return_X_y=True) n_samples, n_features = X.shape

#np.random.seed(0)

#---------------------------------------------------------------------- # 可视化聚类

def plot_clustering(X_red, labels, title=None):

x_min, x_max = np.min(X_red, axis=0), np.max(X_red, axis=0) X_red = (X_red - x_min) / (x_max - x_min)

plt.figure(figsize=(6, 4))

for i in range(X_red.shape[0]):

plt.text(X_red[i, 0], X_red[i, 1], str(y[i]),

color=plt.cm.nipy_spectral(labels[i] / 10.), fontdict={'weight': 'bold', 'size': 9}

plt.xticks([]) plt.yticks([])

if title is not None:

plt.title(title, size=17) plt.axis('off')

plt.tight_layout(rect=[0, 0.03, 1, 0.95]) plt.tight_layout(rect=[0, 0.03, 1, 0.95])

#---------------------------------------------------------------------- # 2D embedding of the digits dataset print("Computing embedding")

X_red = manifold.SpectralEmbedding(n_components=2).fit_transform(X) print("Done.")

from sklearn.cluster import AgglomerativeClustering agglustering = AgglomerativeClustering(linkage='ward',

n_clusters=10) agglustering.fit(X_red)

agglabels = agglustering.labels_

from sklearn.cluster import KMeans kmclustering = KMeans(n_clusters=10) kmclustering.fit(X_red)


kmlabels = kmclustering.labels_

from sklearn.cluster import MeanShift msclustering = MeanShift() msclustering.fit(X_red)

mslables = msclustering.labels_

from sklearn.cluster import DBSCAN dbsclustering = DBSCAN() dbsclustering.fit(X_red)

dbslabels = dbsclustering.labels_

from sklearn.metrics import silhouette_score print("AGG silhouette_score: %0.3f"

% silhouette_score(X_red, agglabels)) print("KMeans silhouette_score: %0.3f" % silhouette_score(X_red, kmlabels)) print("MeanShift silhouette_score: %0.3f" % silhouette_score(X_red, mslables)) # print("DBSCAN v_measure_score: %0.3f" # % silhouette_score(X_red, dbslabels))

plot_clustering(X_red, agglustering.labels_,

"AgglomerativeClustering(k=10)")

plot_clustering(X_red, kmclustering.labels_,"KMeans(k=10)") plot_clustering(X_red, msclustering.labels_,"MeanShift") plot_clustering(X_red, dbsclustering.labels_,"DBSCAN") plt.show()


本文来源:https://www.dy1993.cn/uSZK.html

相关推荐