Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overflow / math range error for log or exp

Line of code in question:

summing +=  yval * np.log(             sigmoid(np.dot(w.transpose(),xi.transpose()))) 
        +(1-yval)* np.log(max(0.001, 1-sigmoid(np.dot(w.transpose(),xi.transpose()))))

Error:

File "classify.py", line 67, in sigmoid
return 1/(1+ math.exp(-gamma))
OverflowError: math range error

The sigmoid function is just 1/(1+ math.exp(-gamma)).

I'm getting a math range error. Does anyone see why?

like image 232
Jobs Avatar asked Mar 28 '16 18:03

Jobs


People also ask

How to handle math range error?

The Python "OverflowError: math range error" occurs when the result of a mathematical calculation is too large. Use a try/except block to handle the error or use the numpy module if you have to manipulate larger numbers.

How do you fix an overflow error in Python?

These errors can be handled by using exception handling. In the below section we will see about this exception handling. In the above programs, we saw the Overflow error that occurred when the current value exceeds the limit value. So to handle this we have to raise overflowError exception.


2 Answers

You can avoid this problem by using different cases for positive and negative gamma:

def sigmoid(gamma):
  if gamma < 0:
    return 1 - 1/(1 + math.exp(gamma))
  else:
    return 1/(1 + math.exp(-gamma))

The math range error is likely because your gamma argument is a large negative value, so you are calling exp() with a large positive value. It is very easy to exceed your floating point range that way.

like image 66
comingstorm Avatar answered Oct 19 '22 15:10

comingstorm


The problem is that, when gamma becomes large, math.exp(gamma) overflows. You can avoid this problem by noticing that

sigmoid(x) = 1 / (1 + exp(-x))
           = exp(x) / (exp(x) + 1)
           = 1 - 1 / (1 + exp(x))
           = 1 - sigmoid(-x)

This gives you a numerically stable implementation of sigmoid which guarantees you never even call math.exp with a positive value:

def sigmoid(gamma):
    if gamma < 0:
        return 1 - 1 / (1 + math.exp(gamma))
    return 1 / (1 + math.exp(-gamma))
like image 26
Timothy Shields Avatar answered Oct 19 '22 15:10

Timothy Shields