问题
I'm programming with Python 2.7.6 using numpy. I have this division between two numpy matrixes V/np.dot(W,H)
. Sometimes happens that the denominator has some cell values equal to 0, so i get a Runtime error. I would like to implement a safe division in a efficient way. How can i write a code that performs the Matrix division and for the elements where the denominator is equal to 0 puts 0 in the output Matrix?
回答1:
Numpy actually allows you to set what you'd like to do in the case of a divide by zero error - see seterr. I believe this is a global flag, though - I'm not aware of a more localized solution - if it's an issue I suppose you can just set seterr before and after your safe division.
回答2:
Though you say "matrix", I assume you really want arrays since you want element-wise division. I would just do the division inside a context manager that suppresses the div0 errors. Then I would fix up the result.
# Assume V and D are arrays of the same shape
with np.errstate(divide='ignore'):
# division errors suppressed only within this block
quot = V / D
quot[D == 0] = 0
My gut tells me this is fast because it mostly keeps data in its original shape. But I have never compared it with alternative approaches.
回答3:
Simply search for elements in the denominator that are zero and replace them with infinity.
D = np.dot(W,H)
D[D==0] = float('inf')
result = V / D
This approach is slower than a plain result = V / D
without checking for zeros using D[D==0] = float('inf')
, but it gets better with increasing matrix size. With a 30x30 matrix it takes three times as long, and with a 250x250 matrix it takes twice as long, and as n increases further it approaches 1.8 times as long. And it seems to be about 10% faster than changing the way that floating point exceptions are handled as per Daryl's answer and Adrian's answer.
One thing to bear in mind is that with floating point numbers and lack of precision you may have elements in the denominator that should be zero but aren't quite, and it's easy to incorporate that as follows
epsilon = 1e-8
D[np.abs(D)<epsilon] = float('inf')
来源:https://stackoverflow.com/questions/23041434/efficient-element-wise-matrix-division-when-elements-in-denominator-may-be-zero