numpy:如何对两个向量(形状(n,1)和(n,))进行元素乘运算? [英] Numpy: How to elementwise-multiply two vectors, shape (n,1) and (n,)?

查看:277
本文介绍了numpy:如何对两个向量(形状(n,1)和(n,))进行元素乘运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果两个向量都具有相同的形状(例如两个(n,1)或两个(n,)),则它们的元素逐个相乘是没有问题的.但是,如果一个向量的形状为(n,1),另一向量的形状为(n,),则*运算符将返回有趣的值.

Elementwise multiplication of two vectors is no problem if they both have the same shape, say both (n,1) or both (n,). If one vector has shape (n,1) and the other (n,), though, the *-operator returns something funny.

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

生成的nxn矩阵包含A_ {i,j} = a_i * b_j.

The resulting nxn-matrix contains A_{i,j}=a_i*b_j.

然后如何对ab进行元素逐个乘法?

How can I do elementwise multiplication for the a and b then?

推荐答案

以使矢量形状匹配的方式对矢量进行切片:

Slice the vectors in a way that makes their shape match:

a[:, 0] * b

a * b[:, None]

这篇关于numpy:如何对两个向量(形状(n,1)和(n,))进行元素乘运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆