如何在numpy中乘n x 1和m x 1向量

67up9zun  于 2023-03-30  发布在  其他
关注(0)|答案(1)|浏览(181)

我需要将一个形状为(n,)和(m,)的数组乘以形状为n x 1和m x 1的向量,以形成形状为n x m的矩阵。
最有效的方法是什么?
我试着重新排列数组但我还是不确定其中的数学原理。

bvuwiixz

bvuwiixz1#

注解中给出的两种解决方案(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)

相关问题