Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient element-wise matrix division when elements in denominator may be zero

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?

like image 209
user3528716 Avatar asked Feb 07 '26 14:02

user3528716


2 Answers

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.

like image 153
Daryl Avatar answered Feb 09 '26 08:02

Daryl


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.

like image 28
Adrian Ratnapala Avatar answered Feb 09 '26 08:02

Adrian Ratnapala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!