我需要将一个形状为(n,)和(m,)的数组乘以形状为n x 1和m x 1的向量,以形成形状为n x m的矩阵。最有效的方法是什么?我试着重新排列数组但我还是不确定其中的数学原理。
bvuwiixz1#
注解中给出的两种解决方案(np.outer(a, b)和a[:, None] * b)是等效的,并且具有相似的效率:
np.outer(a, b)
a[:, None] * b
In [25]: m, n = 300, 500 ...: ...: a = np.random.randn(m) ...: b = np.random.randn(n) ...: ...: outer = np.outer(a, b) ...: broadcast = a[:, None] * b ...: ...: assert outer.shape == (m, n) ...: assert broadcast.shape == (m, n) ...: assert np.all(outer == broadcast) ...: ...: %timeit outer = np.outer(a, b) ...: %timeit broadcast = a[:, None] * b 118 µs ± 619 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) 119 µs ± 2.46 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
1条答案
按热度按时间bvuwiixz1#
注解中给出的两种解决方案(
np.outer(a, b)
和a[:, None] * b
)是等效的,并且具有相似的效率: