简体   繁体   English

Numpy:如何逐个乘以两个向量,shape(n,1)和(n,)?

[英]Numpy: How to elementwise-multiply two vectors, shape (n,1) and (n,)?

Elementwise multiplication of two vectors is no problem if they both have the same shape, say both (n,1) or both (n,). 如果它们都具有相同的形状,例如两个(n,1)或两个(n,),则两个矢量的元素相乘是没有问题的。 If one vector has shape (n,1) and the other (n,), though, the * -operator returns something funny. 但是,如果一个向量具有形状(n,1)和另一个(n,),则*运算符返回一些有趣的东西。

a = np.ones((3,1))
b = np.ones((3,))
print a * b

The resulting nxn-matrix contains A_{i,j}=a_i*b_j. 得到的nxn矩阵包含A_ {i,j} = a_i * b_j。

How can I do elementwise multiplication for the a and b then? 我怎样才能为ab做元素乘法呢?

Slice the vectors in a way that makes their shape match: 以使形状匹配的方式切割向量:

a[:, 0] * b

or 要么

a * b[:, None]

Add a second axis to b to that a and b have the same dimensions: 将第二个轴添加到bab具有相同的尺寸:

>>> a * b[:,np.newaxis]
array([[ 1.],
       [ 1.],
       [ 1.]])

Alternatively, transpose a so that broadcasting works: 或者,转置a以便广播工作:

>>> a.T * b
array([[ 1.,  1.,  1.]])

(You'd probably want to transpose the result.) (您可能想要转置结果。)

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

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