强制乘法使用 __rmul__() 而不是 Numpy 数组 __mul__() 或绕过广播

per*_*sse 5 python arrays numpy python-3.x array-broadcasting

这个问题与Overriding other __rmul__ with your class's __mul__中提出的问题很接近,但我的印象是,这是一个比数值数据更普遍的问题。另外,这个问题没有得到解答,我真的不想使用矩阵乘法@来进行此操作。因此,问题。

我确实有一个接受标量和数值数组相乘的对象。与往常一样,左乘法工作得很好,因为它myobj()使用的是方法,但在右乘法中,NumPy 使用广播规则并给出元素级结果dtype=object。

这还有一个副作用,即无法检查数组的大小是否兼容。

因此,问题是

有没有办法强制 numpy 数组查找__rmul__()另一个对象的 ,而不是广播和按元素执行__mul__()?

在我的特定情况下,对象是 MIMO(多输入、多输出)传递函数矩阵(或者滤波器系数矩阵,如果您愿意),因此矩阵乘法在线性系统的加法和乘法方面具有特殊含义。因此在每个条目中都有SISO系统。

import numpy as np

class myobj():
    def __init__(self):
        pass

    def __mul__(self, other):
        if isinstance(other, type(np.array([0.]))):
            if other.size == 1:
                print('Scalar multiplication')
            else:
                print('Multiplication of arrays')

    def __rmul__(self, other):
        if isinstance(other, type(np.array([0.]))):
            if other.size == 1:
                print('Scalar multiplication')
            else:
                print('Multiplication of arrays')

A = myobj()
a = np.array([[[1+1j]]])  # some generic scalar
B = np.random.rand(3, 3)
Run Code Online (Sandbox Code Playgroud)

通过这些定义,以下命令将显示不需要的行为。

In [123]: A*a
Scalar multiplication

In [124]: a*A
Out[124]: array([[[None]]], dtype=object)

In [125]: B*A
Out[125]: 
array([[None, None, None],
       [None, None, None],
       [None, None, None]], dtype=object)

In [126]: A*B
Multiplication of arrays

In [127]: 5 * A

In [128]: A.__rmul__(B)  # This is the desired behavior for B*A
Multiplication of arrays
Run Code Online (Sandbox Code Playgroud)

sho*_*yer 3

默认情况下,NumPy 假定未知对象(不是从 ndarray 继承)是标量,并且需要对任何 NumPy 数组的每个元素进行“向量化”乘法。

要自己控制操作,您需要设置__array_priority__(向后兼容)或__array_ufunc__(仅限 NumPy 1.13+)。例如:

class myworkingobj(myobj):
    __array_priority__ = 1000

A = myworkingobj()
B = np.random.rand(3, 3)
B * A  # Multiplication of arrays
Run Code Online (Sandbox Code Playgroud)