打印每个簇的图像

2024-04-18 22:36:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用sklearn KMeans来形成图像簇,我在打印每个簇的图像时遇到了困难。你知道吗

  1. 我有一个维度的np数组序列:(10000,100,100,3)
  2. 然后我将图像展平,使每一行显示一个图像。列车尺寸:(10000、30000)
  3. 我应用了KMeans。你知道吗

    from scipy import ndimage
    
    from sklearn.cluster import KMeans
    
    kmeans = KMeans(n_clusters=10, random_state=0)
    
    clusters = kmeans.fit_predict(train)
    
    centers = kmeans.cluster_centers_
    

在这之后我要打印每个簇的图像


Tags: from图像import尺寸np序列scipy数组
1条回答
网友
1楼 · 发布于 2024-04-18 22:36:08

对于十个集群,您将得到十个集群中心。你现在可以把它们打印出来,也可以把它们形象化——我想你会这么做的。你知道吗

import numpy as np
import matplotlib.pyplot as plt

#fake centers 
centers = np.random.random((10,100,100,3))

#print centers
for ci in centers:
    print(ci)

#visualize centers:
for ci in centers: 
    plt.imshow(ci)
    plt.show()

编辑:我知道您不仅希望可视化中心,还希望可视化每个集群的其他成员。你知道吗

您可以对单个随机成员执行以下操作:

from scipy import ndimage
from sklearn.cluster import KMeans
import numpy as np
import matplotlib.pyplot as plt
import random

#PARAMS
n_clusters=10  

#fake train data
original_train = np.random.random((100, 100, 100, 3)) #100 images of each 100 px,py and RGB 

n,x,y,c = original_train.shape

flat_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_

#visualize centers:
for ci in centers: 
    plt.imshow(ci.reshape(x,y,c))
    plt.show()

#visualize other members
for cluster in np.arange(n_clusters):

    cluster_member_indices = np.where(clusters == cluster)[0]
    print("There are %s members in cluster %s" % (len(cluster_member_indices), cluster))

    #pick a random member
    random_member = random.choice(cluster_member_indices)
    plt.imshow(original_train[random_member,:,:,:])
    plt.show()

相关问题 更多 >