Redefine *= operator in numpy

佐手、 提交于 2019-12-30 10:18:08

问题


As mentioned here and here, this doesn't work anymore in numpy 1.7+ :

import numpy
A = numpy.array([1, 2, 3, 4], dtype=numpy.int16)
B = numpy.array([0.5, 2.1, 3, 4], dtype=numpy.float64)
A *= B

A workaround is to do:

def mult(a,b):
    numpy.multiply(a, b, out=a, casting="unsafe")

def add(a,b):
    numpy.add(a, b, out=a, casting="unsafe")

mult(A,B)

but that's way too long to write for each matrix operation!

How can override the numpy *= operator to do this by default?

Should I subclass something?


回答1:


You can use np.set_numeric_ops to override array arithmetic methods:

import numpy as np

def unsafe_multiply(a, b, out=None):
    return np.multiply(a, b, out=out, casting="unsafe")

np.set_numeric_ops(multiply=unsafe_multiply)

A = np.array([1, 2, 3, 4], dtype=np.int16)
B = np.array([0.5, 2.1, 3, 4], dtype=np.float64)
A *= B

print(repr(A))
# array([ 0,  4,  9, 16], dtype=int16)



回答2:


You can create a general function and pass the intended attribute to it:

def calX(a,b, attr):
    try:
        return getattr(numpy, attr)(a, b, out=a, casting="unsafe")
    except AttributeError:
        raise Exception("Please enter a valid attribute")

Demo:

>>> import numpy
>>> A = numpy.array([1, 2, 3, 4], dtype=numpy.int16)
>>> B = numpy.array([0.5, 2.1, 3, 4], dtype=numpy.float64)
>>> calX(A, B, 'multiply')
array([ 0,  4,  9, 16], dtype=int16)
>>> calX(A, B, 'subtract')
array([ 0,  1,  6, 12], dtype=int16)

Note that if you want to override the result you can just assign the function's return to the first matrix.

A = calX(A, B, 'multiply')


来源:https://stackoverflow.com/questions/38673878/redefine-operator-in-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!