ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – 强制乘法使用__rmul __()而不是Numpy数组__mul __()或绕过广播

2019-06-27 22:45:39  阅读:385  来源: 互联网

标签:python arrays python-3-x numpy numpy-broadcasting


这个问题与Overriding other __rmul__ with your class’s __mul__中提出的问题很接近,但我认为这是一个更普遍的问题,只有数字数据.这也没有回答,我真的不想使用矩阵乘法@来进行此操作.因此,问题.

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

这也具有无法检查阵列大小是否兼容的副作用.

因此,问题是

Is there a way to force numpy array to look for the __rmul__() of the other object instead of broadcasting and performing elementwise __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

解决方法:

默认情况下,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

标签:python,arrays,python-3-x,numpy,numpy-broadcasting
来源: https://codeday.me/bug/20190627/1309212.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有