Python 如何将两个向量相乘并得到一个矩阵?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28578302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to multiply two vector and get a matrix?
提问by Larry
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.
在 numpy 操作中,我有两个向量,假设向量 A 是 4X1,向量 B 是 1X5,如果我做 AXB,它应该产生一个大小为 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?
我应该如何获得我想要的矩阵的输出产品?
采纳答案by Dietrich Epp
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 中是elementwise multiplication,并且矩阵乘法可用numpy.dot()
(或使用@
运算符,在 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.outer(numpy.array([1, 2]), numpy.array([3, 4]))
array([[3, 4],
[6, 8]])
回答by max yi
If you are using numpy.
如果您使用 numpy.
First, make sure you have two vectors. For example, vec1.shape = (10, )
and vec2.shape = (26, )
; in numpy, row vector and column vector are the same thing.
首先,确保你有两个向量。例如,vec1.shape = (10, )
和vec2.shape = (26, )
;在 numpy 中,行向量和列向量是一回事。
Second, you do res_matrix = vec1.reshape(10, 1) @ vec2.reshape(1, 26) ;
.
其次,你做res_matrix = vec1.reshape(10, 1) @ vec2.reshape(1, 26) ;
。
Finally, you should have: res_matrix.shape = (10, 26)
.
最后,你应该有:res_matrix.shape = (10, 26)
。
numpy documentation says it will deprecate np.matrix()
, so better not use it.
numpy 文档说它会弃用np.matrix()
,所以最好不要使用它。
回答by Serenity
Function matmul
(since numpy 1.10.1) works fine:
函数matmul
(自 numpy 1.10.1 起)工作正常:
import numpy as np
a = np.array([[1],[2],[3],[4]])
b = np.array([[1,1,1,1,1],])
ab = np.matmul(a, b)
print (ab)
print(ab.shape)
You have to declare your vectors right. The first has to be a list of lists of one number (this vector has to have columns in one row), and the second - a list of list (this vector has to have rows in one column) like in above example.
你必须正确声明你的向量。第一个必须是一个数字列表的列表(这个向量必须在一行中有列),第二个 - 一个列表列表(这个向量必须在一个列中有行),就像上面的例子一样。
Output:
输出:
[[1 1 1 1 1]
[2 2 2 2 2]
[3 3 3 3 3]
[4 4 4 4 4]]
(4, 5)