【问题标题】:How to flatten only some dimensions of a numpy array如何仅展平numpy数组的某些维度
【发布时间】:2013-09-16 10:54:52
【问题描述】:

有没有一种快速的方法来“子展平”或仅展平 numpy 数组中的一些第一个维度?

例如,给定一个维度为 (50,100,25) 的 numpy 数组,结果维度将是 (5000,25)

【问题讨论】:

标签: python numpy flatten


【解决方案1】:

看看numpy.reshape

>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)

>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape   
# (5000, 25)

# One shape dimension can be -1. 
# In this case, the value is inferred from 
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)

【讨论】:

  • 这样的解决方案对我来说似乎有点不雅,因为它们需要一些冗余信息。我希望有一种方法可以做到这一点,只需要指定维度的子集,比如arr.flatten(dimensions=(0, 1))
  • @Denziloe 在不指定额外数据将被折叠到哪个维度的情况下,不能简单地“展平” ndarray 的任意维度。以 2x2x3 ndarray 为例,展平最后一个维度可以产生 2x6 或6x2,所以信息不是多余的。您可以使用 -1 指定尺寸: 从numpy.reshape 一个形状尺寸可以是-1。在这种情况下,该值是从数组的长度和剩余维度推断出来的。所以一个 2x2xN 重新整形为 2Nx2 看起来像这样:arr.reshape((-1,2)).
  • @Denziloe 实现此目的的方法可能类似于arr.reshape(arr.shape[0] * arr.shape[1], arr.shape[2])
【解决方案2】:

稍微概括一下 Alexander 的回答 - np.reshape 可以将 -1 作为参数,意思是“数组总大小除以所有其他列出的维度的乘积”:

例如展平除最后一个维度之外的所有维度:

>>> arr = numpy.zeros((50,100,25))
>>> new_arr = arr.reshape(-1, arr.shape[-1])
>>> new_arr.shape
# (5000, 25)

【讨论】:

    【解决方案3】:

    对 Peter 的回答稍作概括——如果您想超越三维数组,可以在原始数组的形状上指定一个范围。

    例如展平除最后 两个 维度之外的所有维度:

    arr = numpy.zeros((3, 4, 5, 6))
    new_arr = arr.reshape(-1, *arr.shape[-2:])
    new_arr.shape
    # (12, 5, 6)
    

    编辑:对我之前的回答稍作概括——当然,您也可以在重塑的开头指定一个范围:

    arr = numpy.zeros((3, 4, 5, 6, 7, 8))
    new_arr = arr.reshape(*arr.shape[:2], -1, *arr.shape[-2:])
    new_arr.shape
    # (3, 4, 30, 7, 8)
    

    【讨论】:

    • 已经两年多了……我们需要再稍微概括一下! ;)
    【解决方案4】:

    另一种方法是使用numpy.resize(),如:

    In [37]: shp = (50,100,25)
    In [38]: arr = np.random.random_sample(shp)
    In [45]: resized_arr = np.resize(arr, (np.prod(shp[:2]), shp[-1]))
    In [46]: resized_arr.shape
    Out[46]: (5000, 25)
    
    # sanity check with other solutions
    In [47]: resized = np.reshape(arr, (-1, shp[-1]))
    In [48]: np.allclose(resized_arr, resized)
    Out[48]: True
    

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 1970-01-01
      • 2021-08-29
      • 2022-08-05
      • 1970-01-01
      • 2015-12-08
      • 1970-01-01
      • 2020-09-03
      • 2010-11-22
      相关资源
      最近更新 更多