简体   繁体   English

Numpy 运算符用于具有矩阵单独行乘法的每个向量元素

[英]Numpy operator for each vector element with matrix individual row multiplication

Is there a numpy operator that will result in the individual vector element multiplying with the corresponding matrix row?是否有一个 numpy 运算符会导致单个向量元素与相应的矩阵行相乘?

For eg,例如,

    import numpy
    a,b=numpy.array([1,2]), numpy.array([[1,2,3,4],[5,6,7,8]])

When I multiply a and b, I want the result to be当我将 a 和 b 相乘时,我希望结果是

[[1,2,3,4],[10,12,14,16]]

where each vector element is multiplied with the corresponding matrix row elements.其中每个向量元素与相应的矩阵行元素相乘。

I know how to implement this using loops, but I just wanted to know whether an in-built function exists in numpy for this, especially when b is an extremely large, but sparse matrix ?我知道如何使用循环来实现这个,但我只是想知道 numpy 中是否存在内置的 function ,尤其是当 b 是一个非常大但稀疏的矩阵时?

Thank you.谢谢你。

You could use multiply like the following:您可以像下面这样使用multiply

import numpy
a,b=numpy.array([1,2]), numpy.array([[1,2,3,4],[5,6,7,8]])
print(numpy.multiply(a,b.T).T)
# [[ 1  2  3  4]
# [10 12 14 16]]

Other option is to use * and transpose like the following:其他选项是使用*并转置如下:

import numpy
a,b=numpy.array([1,2]), numpy.array([[1,2,3,4],[5,6,7,8]])
print(a*b.T)
# [[ 1 10]
# [ 2 12]
# [ 3 14]
# [ 4 16]]

You can use:您可以使用:

a[:,None]*b

This should be fairly fast with no extra calculation cost.这应该相当快,没有额外的计算成本。

output: output:

[[ 1  2  3  4]
 [10 12 14 16]]

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

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