简体   繁体   English

Numpy 向量和矩阵加法

[英]Numpy vector and matrix addition

What is the best way to perform normal vector addition, where one of the operands is an nx 1 matrix?执行法线向量加法的最佳方法是什么,其中一个操作数是nx 1矩阵?

Why do I care?我为什么在乎? Sometimes, a function that should return a vector returns an nx 1 matrix (because the function would equivalently work element-wise on a matrix).有时,应该返回向量的 function 会返回nx 1矩阵(因为 function 等效地在矩阵上按元素工作)。 When I want to further work with the returned "vector", I always have to reshape - there must be a better way.当我想进一步处理返回的“向量”时,我总是不得不重塑——一定有更好的方法。

For example:例如:

v = np.zeros(shape=(2,1))
w = np.array([1,1])
print('{}, {}'.format(v.shape,w.shape))

Prints: (2, 1), (2,)打印:(2, 1), (2,)

print(v+w)

[[1. [[1。 1.] [1. 1.] [1. 1.]] 1.]]

print(v+w.reshape((2,1)))

[[1.] [1.]] (the desired output!) [[1.] [1.]] (所需的输出!)

If w has the desired shape of the result (eg (2,) ), and v has the same size (eg (2,1) , or (2,) ), this is safe and easy:如果w具有所需的结果形状(例如(2,) ),并且v具有相同的大小(例如(2,1)(2,) ),则这是安全且容易的:

w + v.reshape(w.shape)

Less generally, if all you want is to get rid of the last dimension, knowing it is of length 1, you can do:不太一般,如果您只想摆脱最后一个维度,知道它的长度为 1,您可以这样做:

w + v[..., 0]

Sounds a bit like you are coming from MATLAB where everything is 2d (scalars size is (1,1)) and the trailing dimension is outermost.听起来有点像您来自 MATLAB,其中一切都是 2d(标量大小为 (1,1)),并且尾随维度位于最外层。 Or a linear algebra that treats 'vectors' as single column matrices.或将“向量”视为单列矩阵的线性代数。

In numpy , 0 and 1d arrays are just a normal as 2d.numpy中,0 和 1d arrays 与 2d 一样正常。 A shape like (n,) is common.像 (n,) 这样的形状很常见。 By the rules of broadcasting adding a leading dimension is automatic (1,n), but adding a trailing dimension requires user action.根据广播规则,添加前导维度是自动的 (1,n),但添加尾随维度需要用户操作。 That a[:,None] is most idiomatic, though not the only option. a[:,None]是最惯用的,尽管不是唯一的选择。

The v+w broadcasting logic is v+w广播逻辑是

(2,1) + (2,) => (2,1) + (1,2) => (2,2)

The auto-leading logic avoids ambiguity (what should happen if you try to add a (2,) to a (3,)?).自动引导逻辑避免了歧义(如果您尝试将 (2,) 添加到 (3,) 会发生什么?)。 And since leading dimensions are 'outer-most' it makes most sense to expand in that direction.而且由于领先的维度是“最外层的”,因此向那个方向扩展是最有意义的。 MATLAB on the other hand 'naturally' expends and contracts the trailing dimensions.另一方面,MATLAB“自然”地扩展和收缩尾随维度。

So to some degree or other a (n,1) shape is more awkward in numpy , though it is still relatively easy to create.因此,在某种程度上, (n,1) 形状在numpy中更尴尬,尽管它仍然相对容易创建。

Another example of an auto leading dimension:自动前导维度的另一个示例:

In [129]: np.atleast_2d(np.arange(3)).shape
Out[129]: (1, 3)

On the other hand expand_dims lets us add dimensions all over the place另一方面, expand_dims让我们可以在所有地方添加维度

In [132]: np.expand_dims(np.arange(3),(0,2,3)).shape
Out[132]: (1, 3, 1, 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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