沿特定维度扩展数组
Expanding an array along particular dimension
我有一个数组如下:
arr = np.arange(2*1*15).reshape(2, 1, 15)
现在,我怎样才能将这个数组展开成 (2, 10, 15)
的形状呢?要填写值,可以使用与原始数组的 (1, 15)
部分相同的值(即来自最后两个维度)。
您可以使用 numpy.repeat
沿第二个轴复制值:
np.repeat(arr, 10, axis=1).shape
# (2, 10, 15)
同时,我发现numpy.broadcast_to也可以做这个工作。
举个小例子:
In [8]: np.broadcast_to(arr, (2, 5, 15))
Out[8]:
array([[[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]],
[[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]])
性能注意事项:计时后,我发现numpy.broadcast_to
大约是。 40x 比 numpy.repeat
快。
是因为:
It's faster because it creates a read-only view of the data with lots of elements pointing to the same memory locations. If you copy the result, the performance is about the same. If you don't need to edit the final result, it provides a massive performance gain
我有一个数组如下:
arr = np.arange(2*1*15).reshape(2, 1, 15)
现在,我怎样才能将这个数组展开成 (2, 10, 15)
的形状呢?要填写值,可以使用与原始数组的 (1, 15)
部分相同的值(即来自最后两个维度)。
您可以使用 numpy.repeat
沿第二个轴复制值:
np.repeat(arr, 10, axis=1).shape
# (2, 10, 15)
同时,我发现numpy.broadcast_to也可以做这个工作。
举个小例子:
In [8]: np.broadcast_to(arr, (2, 5, 15))
Out[8]:
array([[[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]],
[[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]])
性能注意事项:计时后,我发现numpy.broadcast_to
大约是。 40x 比 numpy.repeat
快。
It's faster because it creates a read-only view of the data with lots of elements pointing to the same memory locations. If you copy the result, the performance is about the same. If you don't need to edit the final result, it provides a massive performance gain