问题描述
在 numpy 操作中,我有两个向量,假设向量 A 是 4X1,向量 B 是 1X5,如果我做 AXB,它应该产生一个大小为 4X5 的矩阵.
但是我尝试了很多次,做了很多类型的reshape和transpose,它们要么抛出错误,提示未对齐要么返回一个值.
我应该如何得到我想要的矩阵的输出产品?
只要向量具有正确的形状,普通矩阵乘法就可以工作.请记住,Numpy 中的 *
是元素乘法,矩阵乘法可通过 numpy.dot()
(或@
运算符,在 Python 3.5 中)
这称为外积".您可以使用 numpy.outer()
使用普通向量获得它:
In numpy operation, I have two vectors, let's say vector A is 4X1, vector B is 1X5, if I do AXB, it should result a matrix of size 4X5.
But I tried lot of times, doing many kinds of reshape and transpose, they all either raise error saying not aligned or return a single value.
How should I get the output product of matrix I want?
Normal matrix multiplication works as long as the vectors have the right shape. Remember that *
in Numpy is elementwise multiplication, and matrix multiplication is available with numpy.dot()
(or with the @
operator, in Python 3.5)
>>> numpy.dot(numpy.array([[1], [2]]), numpy.array([[3, 4]]))
array([[3, 4],
[6, 8]])
This is called an "outer product." You can get it using plain vectors using numpy.outer()
:
>>> numpy.outer(numpy.array([1, 2]), numpy.array([3, 4]))
array([[3, 4],
[6, 8]])
这篇关于如何将两个向量相乘并得到一个矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!