【问题标题】:Printing images of each clusters打印每个集群的图像
【发布时间】:2019-08-12 05:06:15
【问题描述】:

我使用 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_
    

在此之后我想打印每个集群的图像,

【问题讨论】:

标签: python machine-learning image-processing computer-vision


【解决方案1】:

对于十个集群,您将获得十个集群中心。您现在可以打印它们,也可以将它们可视化 - 这是我假设您想要做的。

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()

【讨论】:

  • 但它只显示了 10 张图片,如何显示来自每个中心的一些图片
  • 似乎对集群和中心的含义存在一些误解。您使用 KMeans 将数据与 10 个集群进行了聚类。然后你想可视化/打印你的集群的中心。每个集群存在一个中心。那么你将拥有 10 个聚类中心。
  • 您的论点绝对正确,但 OP 可以说是询问如何从每个集群而不是集群中心打印 一些 图像(即样本);无论如何,我不确定在这种情况下打印集群中心有多有意义/有趣。
  • 我相应地编辑了答案,现在绘制了一个随机成员。稍作调整,他改为绘制所有成员,绘制 N 个成员等。
猜你喜欢
  • 2011-12-21
  • 2022-10-04
  • 2019-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-16
  • 2018-06-02
  • 2019-06-10
相关资源
最近更新 更多