【问题标题】:Filtering a numpy array using another array of labels使用另一个标签数组过滤 numpy 数组
【发布时间】:2017-07-31 04:29:26
【问题描述】:

给定两个 numpy 数组,即:

images.shape: (60000, 784) # An array containing 60000 images
labels.shape: (60000, 10)  # An array of labels for each image

labels 的每一行在特定索引处包含一个1,以指示images 中相关示例的类。 (所以[0 0 1 0 0 0 0 0 0 0] 表示该示例属于第 2 类(假设我们的类索引从 0 开始)。

我正在尝试有效地分离images,以便我可以一次处理属于特定类的所有图像。最明显的解决方案是使用for 循环(如下所示)。但是,我不确定如何过滤 images,以便只返回具有适当 labels 的那些。

for i in range(0, labels.shape[1]):
  class_images = # (?) Array containing all images that belong to class i

顺便说一句,我还想知道是否有更有效的方法可以消除 for 循环的使用。

【问题讨论】:

    标签: python arrays numpy filter


    【解决方案1】:

    一种方法是将标签数组转换为布尔值并将其用于索引:

    classes = []
    blabels = labels.astype(bool)
    for i in range(10):
        classes.append(images[blabels[:, i], :])
    

    或者作为单行使用列表理解:

    classes = [images[l.astype(bool), :] for l in labels.T]
    

    【讨论】:

      【解决方案2】:
      _classes= [[] for x in range(10)]
      for image_index , element in enumerate(labels):
          _classes[element.index(1)].append(image_index)
      

      例如 _classes[0] 将包含分类为 class0 的图像的索引。

      【讨论】:

      • 如果你使用 numpy,你可以使用 nonzero(element == 1)[0][0] 代替 element.index(1)
      猜你喜欢
      • 2012-03-06
      • 2017-09-16
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 2013-11-19
      • 2017-05-08
      相关资源
      最近更新 更多