我有一个名为 a 的 numpy 数组(图像),其大小为:
[3,128,192]
现在我想要创建一个numpy数组,其中包含具有此维度的 n n 副本:
[n,3,128,192]
存在一个numpy函数,可以帮助我解决这个问题而不使用循环指令?
答案 0 :(得分:1)
只需使用np.stack
# say you need 10 copies of a 3D array `a`
In [267]: n = 10
In [266]: np.stack([a]*n)
或者,如果您真的关心效果,则应使用np.concatenate
。
In [285]: np.concatenate([a[np.newaxis, :, :]]*n)
示例:
In [268]: a
Out[268]:
array([[[ 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, 30, 31]],
[[32, 33, 34, 35],
[36, 37, 38, 39],
[40, 41, 42, 43],
[44, 45, 46, 47]]])
In [271]: a.shape
Out[271]: (3, 4, 4)
In [269]: n = 10
In [270]: np.stack([a]*n).shape
Out[270]: (10, 3, 4, 4)
In [285]: np.concatenate([a[np.newaxis, :, :]]*n).shape
Out[285]: (10, 3, 4, 4)
性能:
# ~ 4x faster than using `np.stack`
In [292]: %timeit np.concatenate([a[np.newaxis, :, :]]*n)
100000 loops, best of 3: 10.7 µs per loop
In [293]: %timeit np.stack([a]*n)
10000 loops, best of 3: 41.1 µs per loop
答案 1 :(得分:0)
方法#1:一种方法是np.repeat
在扩展输入数组后再沿着第一个轴重复一个维度,一个单一的维度None/np.newaxis
-
np.repeat(a[None],n,axis=0)
样品运行 -
1)2D案例:
In [209]: a
Out[209]:
array([[7, 8, 0, 1],
[5, 0, 1, 0],
[4, 3, 0, 1]])
In [210]: np.repeat(a[None],2,axis=0)
Out[210]:
array([[[7, 8, 0, 1],
[5, 0, 1, 0],
[4, 3, 0, 1]],
[[7, 8, 0, 1],
[5, 0, 1, 0],
[4, 3, 0, 1]]])
2)3D案例:
In [214]: a
Out[214]:
array([[[7, 2, 4, 2],
[6, 7, 7, 6],
[6, 8, 2, 1]],
[[1, 5, 8, 5],
[8, 0, 6, 4],
[1, 2, 8, 8]]])
In [215]: np.repeat(a[None],2,axis=0)
Out[215]:
array([[[[7, 2, 4, 2],
[6, 7, 7, 6],
[6, 8, 2, 1]],
[[1, 5, 8, 5],
[8, 0, 6, 4],
[1, 2, 8, 8]]],
[[[7, 2, 4, 2],
[6, 7, 7, 6],
[6, 8, 2, 1]],
[[1, 5, 8, 5],
[8, 0, 6, 4],
[1, 2, 8, 8]]]])
方法#2:如果您不介意输入数组的只读版本,我们可以使用np.broadcast_to
-
np.broadcast_to(a, (n,) + a.shape)
方法#3:如果你不介意输入数组的视图,那么这里有一个NumPy步骤 -
def strided_repeat_newaxis0(a, n):
s0,s1,s2 = a.strides
shp = (n,) + a.shape
return np.lib.index_tricks.as_strided(a, shape=shp, strides=(0,s0,s1,s2))
运行时测试
In [290]: a = np.random.randint(0,9,(3,128,192))
In [291]: %timeit np.repeat(a[None],100,axis=0)
100 loops, best of 3: 6.15 ms per loop
In [292]: %timeit strided_repeat_newaxis0(a, 100)
100000 loops, best of 3: 4.69 µs per loop
In [293]: %timeit np.broadcast_to(a, (n,) + a.shape)
100000 loops, best of 3: 3.03 µs per loop
答案 2 :(得分:0)
您可以将np.repeat
方法与np.newaxis
一起使用:
import numpy as np
test = np.random.randn(3,128,192)
result = np.repeat(test[np.newaxis,...], 10, axis=0)
print(result.shape)
>> (10, 3, 128, 192)