我想实现这一目标:
a = np.array ([[1, 2],
[2, 1]])
b = np.array ([[0.25, 0.25, 0.5, 0.5],
[0.25, 0.25, 0.5, 0.5],
[0.5, 0.5, 0.25, 0.25],
[0.5, 0.5, 0.25, 0.25])
从数学上讲,它们不是相同的矩阵。但是我认为您知道我想要做什么。我想将矩阵的尺寸加倍。但是因此我想通过取四个对应单元格的四分之一来保留初始矩阵a中的信息。
some1知道如何在numpy中有效地做到这一点吗?
答案 0 :(得分:3)
您可以在两个轴上使用两个重复功能,然后进行简单除法:
In [8]: np.repeat(np.repeat(a, 2, 1), 2, 0)/4
Out[8]:
array([[0.25, 0.25, 0.5 , 0.5 ],
[0.25, 0.25, 0.5 , 0.5 ],
[0.5 , 0.5 , 0.25, 0.25],
[0.5 , 0.5 , 0.25, 0.25]])
答案 1 :(得分:1)
这里有一个np.broadcast_to
,它利用broadcasting
避免了两个复制阶段或通过一次复制来获得性能收益-
# "Expand" array a by Height, H and Width, W
def expand_blockavg(a, H, W):
m,n = a.shape
return np.broadcast_to((a/float(H*W))[:,None,:,None],(m,H,n,W)).reshape(m*H,-1)
样品运行-
In [93]: a
Out[93]:
array([[1, 2],
[2, 1]])
In [94]: expand_blockavg(a, H=2, W=2)
Out[94]:
array([[0.25, 0.25, 0.5 , 0.5 ],
[0.25, 0.25, 0.5 , 0.5 ],
[0.5 , 0.5 , 0.25, 0.25],
[0.5 , 0.5 , 0.25, 0.25]])
In [95]: expand_blockavg(a, H=2, W=3)
Out[95]:
array([[0.17, 0.17, 0.17, 0.33, 0.33, 0.33],
[0.17, 0.17, 0.17, 0.33, 0.33, 0.33],
[0.33, 0.33, 0.33, 0.17, 0.17, 0.17],
[0.33, 0.33, 0.33, 0.17, 0.17, 0.17]])
大型阵列上的运行时测试-
In [2]: a = np.random.rand(200,200)
# Expand by (2 x 2)
# @Kasrâmvd's soln
In [85]: %timeit np.repeat(np.repeat(a, 2, 1), 2, 0)/4
1000 loops, best of 3: 492 µs per loop
In [86]: %timeit expand_blockavg(a, H=2, W=2)
1000 loops, best of 3: 382 µs per loop
# Expand by (20 x 20)
# @Kasrâmvd's soln
In [5]: %timeit np.repeat(np.repeat(a, 20, 1), 20, 0)/400
10 loops, best of 3: 32 ms per loop
In [6]: %timeit expand_blockavg(a, H=20, W=20)
10 loops, best of 3: 20.1 ms per loop
具有(2 x 2)扩展的较大数组-
In [87]: a = np.random.rand(2000,2000)
# @Kasrâmvd's soln
In [88]: %timeit np.repeat(np.repeat(a, 2, 1), 2, 0)/4
10 loops, best of 3: 70.2 ms per loop
In [89]: %timeit expand_blockavg(a, H=2, W=2)
10 loops, best of 3: 51.6 ms per loop