[英]How to flatten only some dimensions of a numpy array
有沒有一種快速的方法來“亞展平”或展平 numpy 數組中的一些第一個維度?
例如,給定一個尺寸為(50,100,25)
的 numpy 數組,結果尺寸將為(5000,25)
看看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)
對亞歷山大的回答稍作概括 - np.reshape 可以將 -1 作為參數,意思是“數組總大小除以所有其他列出的維度的乘積”:
例如展平除最后一個維度之外的所有維度:
>>> arr = numpy.zeros((50,100,25))
>>> new_arr = arr.reshape(-1, arr.shape[-1])
>>> new_arr.shape
# (5000, 25)
對彼得的回答稍作概括——如果您想超越三維數組,您可以在原始數組的形狀上指定一個范圍。
例如展平除最后兩個維度之外的所有維度:
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)
另一種方法是使用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
numpy.vstack
非常適合這種情況
import numpy as np
arr = np.ones((50,100,25))
np.vstack(arr).shape
> (5000, 25)
我更喜歡使用stack
, vstack
或hstack
而不是reshape
因為reshape
只是掃描數據並且似乎將其強制為所需的形狀。 如果您要取列平均值,這可能會出現問題。
這是我的意思的說明。 假設我們有以下數組
>>> arr.shape
(2, 3, 4)
>>> arr
array([[[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]],
[[7, 7, 7, 7],
[7, 7, 7, 7],
[7, 7, 7, 7]]])
我們應用這兩種方法來獲得一個形狀數組 (3,8)
>>> arr.reshape((3,8)).shape
(3, 8)
>>> np.hstack(arr).shape
(3, 8)
但是,如果我們看看它們在每種情況下是如何被重塑的, hstack
將允許我們獲取列和,我們也可以從原始數組中計算出來。 使用 reshape 這是不可能的。
>>> arr.reshape((3,8))
array([[1, 2, 3, 4, 1, 2, 3, 4],
[1, 2, 3, 4, 7, 7, 7, 7],
[7, 7, 7, 7, 7, 7, 7, 7]])
>>> np.hstack(arr)
array([[1, 2, 3, 4, 7, 7, 7, 7],
[1, 2, 3, 4, 7, 7, 7, 7],
[1, 2, 3, 4, 7, 7, 7, 7]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.