Numpy - 两个矩阵的按行外积 [英] Numpy - row-wise outer product of two matrices

查看:38
本文介绍了Numpy - 两个矩阵的按行外积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 numpy 数组:形状为 (b, i) 的 A 和形状为 (b, o) 的 B.我想计算一个形状为 (b, i, o) 的数组 R,其中 R 的每一行 l 包含Al 行和 Bl 行.到目前为止,我所拥有的是:

I have two numpy arrays: A of shape (b, i) and B of shape (b, o). I would like to compute an array R of shape (b, i, o) where every line l of R contains the outer product of the row l of A and the row l of B. So far what i have is:

import numpy as np

A = np.ones((10, 2))
B = np.ones((10, 6))
R = np.asarray([np.outer(a, b) for a, b in zip(A, B)])
assert R.shape == (10, 2, 6)

我觉得这个方法太慢了,因为zip和最后转换成一个numpy数组.

I think this method is too slow, because of the zip and the final transformation into a numpy array.

有没有更有效的方法来做到这一点?

Is there a more efficient way to do it ?

推荐答案

numpy.matmul,可以做矩阵栈"的乘法.在这种情况下,我们希望将一堆列向量与一堆行向量相乘.首先将矩阵 A 赋形 (b, i, 1) 并将矩阵 B 赋形 (b, 1, o).然后用matmul进行b次外积:

That is possible with numpy.matmul, which can do multiplication of "matrix stacks". In this case we want to multiply a stack of column vectors with a stack of row vectors. First bring matrix A to shape (b, i, 1) and B to shape (b, 1, o). Then use matmul to perform b times the outer product:

import numpy as np

i, b, o = 3, 4, 5

A = np.ones((b, i))
B = np.ones((b, o))

print(np.matmul(A[:, :, np.newaxis], B[:, np.newaxis, :]).shape)  # (4, 3, 5)

另一种可能是使用 numpy.einsum,可以直接表示你的索引符号:

An alternative could be to use numpy.einsum, which can directly represent your index notation:

np.einsum('bi,bo->bio', A, B)

这篇关于Numpy - 两个矩阵的按行外积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆