numpy 自定义乘法和数字

bttbmeg0  于 2023-01-13  发布在  其他
关注(0)|答案(2)|浏览(117)

假设我有自己的两个Python对象ab之间的乘法,我们称之为my_multiplication(a, b)
我怎样才能用numpy执行一个矩阵乘法,其中my_multiplication被执行而不是通常的*?这可能吗?

**附录:**我还能从numpy的速度中获益吗?

62o28rlo

62o28rlo1#

你可以在你的函数上使用np.vectorise来获得你的自定义乘法函数,使用所有常见的numpy特性,比如广播。

def my_multiplication(a, b):
    #your code that works on multiplying 2 numbers
    return c
v_my_multiplication = np.vectorize(my_multiplication)
v_my_multiplication([1, 2, 3], [1, 6])

#Will now work for np.array instead of just 2 numbers and utilize the broadcasting and vectorized implementation benefits that numpy has to offer.
5tmbdcev

5tmbdcev2#

尝试numpy.dotx.dot(y)。请参阅文档here

    • 示例**
import numpy as np
x = np.arange(12).reshape((3,4))
y = np.arange(4)
print(x,"\n\n",y,"\n")
print (np.dot(x,y))

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]] 

 [0 1 2 3] 

[14 38 62]

相关问题