我使用了sklearn的KMeans来形成图像簇,但在打印每个簇的图像时遇到了困难。
- 我有一个维度为(10000, 100, 100, 3)的np数组train
- 然后我将图像展平,使每一行代表一张图像。Train维度:(10000, 30000)
-
我应用了KMeans。
from scipy import ndimagefrom sklearn.cluster import KMeanskmeans = KMeans(n_clusters=10, random_state=0)clusters = kmeans.fit_predict(train)centers = kmeans.cluster_centers_
在这之后,我想打印每个簇的图像,
回答:
对于十个簇,你将得到十个簇中心。你现在可以打印它们,或者你可以将它们可视化——我假设你想要做的是后者。
import numpy as npimport matplotlib.pyplot as plt#假中心 centers = np.random.random((10,100,100,3))#打印中心for ci in centers: print(ci)#可视化中心:for ci in centers: plt.imshow(ci) plt.show()
编辑:我理解你不仅希望可视化中心,还希望可视化每个簇的其他成员。
你可以如下操作来显示一个随机成员:
from scipy import ndimagefrom sklearn.cluster import KMeansimport numpy as npimport matplotlib.pyplot as pltimport random#参数n_clusters=10 #假训练数据original_train = np.random.random((100, 100, 100, 3)) #100张图像,每张100像素,RGB n,x,y,c = original_train.shapeflat_train = original_train.reshape((n,x*y*c))kmeans = KMeans(n_clusters, random_state=0)clusters = kmeans.fit_predict(flat_train)centers = kmeans.cluster_centers_#可视化中心:for ci in centers: plt.imshow(ci.reshape(x,y,c)) plt.show()#可视化其他成员for cluster in np.arange(n_clusters): cluster_member_indices = np.where(clusters == cluster)[0] print("簇%s中有%s个成员" % (cluster, len(cluster_member_indices))) #选择一个随机成员 random_member = random.choice(cluster_member_indices) plt.imshow(original_train[random_member,:,:,:]) plt.show()