【问题标题】:Split feature maps (3D arrays) into 2D arrays将特征图(3D 数组)拆分为 2D 数组
【发布时间】:2018-07-05 23:10:41
【问题描述】:

假设我有一个形状为 (32, 32, 96) 的特征图(即 3D 数组)

In [573]: feature_map = np.random.randint(low=0, high=255, size=(32, 32, 96))

现在,我想分别可视化每个特征图。所以,我想提取每个正面切片(即形状为(32, 32) 的二维数组),这样就可以得到 96 个这样的特征图。

如何获取这些数组,可能不作为副本以提高内存效率?由于这只是用于可视化,所以 view 就足够了!

【问题讨论】:

    标签: python numpy multidimensional-array computer-vision deep-learning


    【解决方案1】:

    您可以使用np.transpose 和切片操作(不创建数组的副本):

    feature_map = np.random.randint(low=0, high=255, size=(32, 32, 96))
    feature_map = np.transpose(feature_map, axes=[2, 0, 1])
    for i in range(feature_map.shape[0]):
      print(feature_map[i].shape)  # a view of original array. shape=(32, 32)
    

    ...或者只是切片:

    for i in range(feature_map.shape[2]):
      print(feature_map[:, :, i].shape)  # a view of original array. shape=(32, 32)
    

    【讨论】:

    • 为什么需要transpose?我认为feature_map[..., i] 应该完成这项工作,对吧?
    • 是的,两个版本都可以。其实我更喜欢第二个
    • 谢谢!!另外,请查看我的答案;)
    【解决方案2】:
    import numpy as np
    
    def do_something(array_slice):
        print array_slice
    
    feature_map = np.random.randint(low=0, high=255, size=(3, 3, 9))
    
    # loop over the indices of the last dimension of the array (i.e. 0 to 8)
    for level in range(feature_map.shape[2]):
        # now take only the 2d-slice of the first two dimensions at the height of 'level'
        do_something(feature_map[:,:,level])
    
    # you could also take a slice from another dimension
    for level in range(feature_map.shape[1]):    
        do_something(feature_map[:,level,:])
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。请阅读此how-to-answer 以提供高质量的答案。
    【解决方案3】:

    我还意识到numpy.dsplit() 可以用于此类 3D 数组,因为我们正试图将其沿深度拆分。但是,我必须另外使用np.squeeze() 来消除第三维。此外,根据我的情况,它还返回数组的 view

    # splitting it into 96 slices in one-go!
    In [659]: np.dsplit(feature_map, feature_map.shape[-1])
    
    In [660]: np.dsplit(feature_map, feature_map.shape[-1])[10].flags
    Out[660]: 
      C_CONTIGUOUS : False
      F_CONTIGUOUS : False
      OWNDATA : False   #<============== NO copy is made
      WRITEABLE : True
      ALIGNED : True
      UPDATEIFCOPY : False
    
    In [661]: np.dsplit(feature_map, feature_map.shape[-1])[10].shape
    Out[661]: (32, 32, 1)
    
    # getting rid of unitary dimension with `np.squeeze`
    In [662]: np.squeeze(np.dsplit(feature_map, feature_map.shape[-1])[10]).shape
    Out[662]: (32, 32)
    
    In [663]: np.squeeze(np.dsplit(feature_map, feature_map.shape[-1])[10]).flags
    Out[663]: 
      C_CONTIGUOUS : False
      F_CONTIGUOUS : False
      OWNDATA : False   #<============== NO copy is made
      WRITEABLE : True
      ALIGNED : True
      UPDATEIFCOPY : False
    

    【讨论】:

      猜你喜欢
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-01
      • 2013-05-07
      • 1970-01-01
      相关资源
      最近更新 更多