【问题标题】:How to collapse two array axis together of a numpy array?如何将一个numpy数组的两个数组轴折叠在一起?
【发布时间】:2019-04-06 08:06:52
【问题描述】:

基本思想:我有一组图像images=np.array([10, 28, 28, 3])。所以 10 张图像 28x28 像素,3 个颜色通道。我想将它们拼接成一条长线:single_image.shape # [280, 28, 3]。什么是最好的基于 numpy 的函数?

更一般地说:是否存在类似于stitch(array, source_axis=0, target_axis=1) 的函数,它可以通过连接子数组A[:,:,i,:,:,:] 沿axis=target_axis 将数组A.shape # [a0, a1, source_axis, a4, target_axis, a6] 转换为形状B.shape # [a0, a1, a4, target_axis*source_axis, a6]

【问题讨论】:

  • 简单的重塑怎么样,images = images.reshape(-1, 28, 3)

标签: python arrays numpy concatenation


【解决方案1】:

您可以使用单个 moveaxis + reshape 组合进行设置 -

def merge_axis(array, source_axis=0, target_axis=1):
    shp = a.shape
    L = shp[source_axis]*shp[target_axis] # merged axis len
    out_shp = np.insert(np.delete(shp,(source_axis,target_axis)),target_axis-1,L)
    return np.moveaxis(a,source_axis,target_axis-1).reshape(out_shp)

或者,out_shp 可以使用数组操作进行设置,并且可能更容易遵循,就像这样 -

shp = np.array(a.shape)
shp[target_axis] *= shp[source_axis]
out_shp = np.delete(shp,source_axis)

如果 sourcetarget 轴是相邻的,我们可以跳过 moveaxis 并简单地进行整形,额外的好处是输出将是输入的视图,因此在运行时几乎是免费的。因此,我们将引入一个 If-conditional 来检查和修改我们的实现,以类似于这些 -

def merge_axis_v1(array, source_axis=0, target_axis=1):
    shp = a.shape
    L = shp[source_axis]*shp[target_axis] # merged_axis_len
    out_shp = np.insert(np.delete(shp,(source_axis,target_axis)),target_axis-1,L)
    if target_axis==source_axis+1:
        return a.reshape(out_shp)
    else:
        return np.moveaxis(a,source_axis,target_axis-1).reshape(out_shp)

def merge_axis_v2(array, source_axis=0, target_axis=1):
    shp = np.array(a.shape)
    shp[target_axis] *= shp[source_axis]
    out_shp = np.delete(shp,source_axis)
    if target_axis==source_axis+1:
        return a.reshape(out_shp)
    else:
        return np.moveaxis(a,source_axis,target_axis-1).reshape(out_shp)

验证views -

In [156]: a = np.random.rand(10,10,10,10,10)

In [157]: np.shares_memory(merge_axis_v1(a, source_axis=0, target_axis=1),a)
Out[157]: True

【讨论】:

    【解决方案2】:

    这是我的看法:

    def merge_axis(array, source_axis=0, target_axis=1):
        array = np.moveaxis(array, source_axis, 0)
        array = np.moveaxis(array, target_axis, 1)
        array = np.concatenate(array)
        array = np.moveaxis(array, 0, target_axis-1)
        return array
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-04
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 2011-07-22
      • 1970-01-01
      相关资源
      最近更新 更多