简体   繁体   English

2列向量的Numpy内积

[英]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)

i think you mean to have:我想你的意思是:

x= np.array([1,2])

in order to get 5 as output, your vector needs to be 1xN not Nx1 if you want to apply np.inner on it为了得到 5 作为输出,如果你想在它上面应用np.inner ,你的向量需要是 1xN 而不是 Nx1

尝试以下它会起作用

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM