この質問は、他の __rmul__ をクラスの __mul__ でオーバーライドするで尋ねられた内容に近いですが、これは数値データだけよりも一般的な問題であるという印象を受けています。@
また、それは答えられておらず、この操作に行列乗算を使用したくありません。したがって、質問です。
スカラーと数値配列の乗算を受け入れるオブジェクトがあります。いつものように、左の乗算はmyobj()
メソッドが使用されているため問題なく動作しますが、右の乗算では、NumPy はブロードキャスト ルールを使用し、要素ごとの結果を で返しますdtype=object
。
これには、配列のサイズに互換性があるかどうかを確認できないという副作用もあります。
したがって、質問は
__rmul__()
要素ごとにブロードキャストして実行する代わりに、他のオブジェクトのを探すように numpy 配列を強制する方法はあり__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)
これらの定義では、次のコマンドは望ましくない動作を示します。
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