[英]Numpy inner product of 2 column vectors
How can I take an inner product of 2 column vectors in python's numpy
如何在python的
numpy
取2列向量的内积
Below code does not work下面的代码不起作用
import numpy as np
x = np.array([[1], [2]])
np.inner(x, x)
It returned它回来了
array([[1, 2],
[2, 4]])`
instead of 5
而不是
5
The inner product of a vector with dimensions 2x1 (2 rows, 1 column) with another vector of dimension 2x1 (2 rows, 1 column) is a matrix with dimensions 2x2 (2 rows, 2 columns).一个维度为 2x1(2 行,1 列)的向量与另一个维度为 2x1(2 行,1 列)的向量的内积是一个维度为 2x2(2 行,2 列)的矩阵。 When you take the inner product of any tensor the inner most dimensions must match (which is 1 in this case) and the result is a tensor with the dimensions matching the outter, ie;
当您取任何张量的内积时,最里面的维度必须匹配(在这种情况下为 1),结果是一个维度与外部匹配的张量,即; a 2x1 * 1x2 = 2x2.
2x1 * 1x2 = 2x2。
What you want to do is transpose both such that when you multiply the dimensions are 1x2 * 2x1 = 1x1.您想要做的是转置两者,以便在乘以维度时为 1x2 * 2x1 = 1x1。
More generally, multiplying anything with dimensions NxM
by something with dimensions MxK
, yields something with dimensions NxK
.更一般地,乘以任何尺寸
NxM
的东西,尺寸MxK
,产量一些与尺寸NxK
。 Note the inner dimensions must both be M
.请注意,内部尺寸必须都是
M
。 For more,review your matrix multiplication rules有关更多信息,请查看您的矩阵乘法规则
The np.inner
function will automatically transpose the second argument, thus when you pass in two 2x1, you get a 2x2, but if you pass in two 1x2 you will get a 1x1. np.inner
函数会自动转置第二个参数,因此当你传入两个 2x1 时,你会得到一个 2x2,但是如果你传入两个 1x2,你将得到一个 1x1。
Try this:尝试这个:
import numpy as np
x = np.array([[1], [2]])
np.inner(np.transpose(x), np.transpose(x))
or simply define your x as row vectors initially.或者简单地将 x 最初定义为行向量。
import numpy as np
x = np.array([1,2])
np.inner(x, x)
尝试以下它会起作用
np.dot(np.transpose(a),a))
make sure col_vector has shape (N,1) where N is the number of elements确保 col_vector 具有形状 (N,1) 其中 N 是元素的数量
then simply sum one to one multiplication result然后简单地将一比一的乘法结果相加
np.sum(col_vector*col_vector)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.