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

狂风中的少年 提交于 2020-01-04 04:40:15

问题


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

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