Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding numerical instability when computing 1/(1+exp(x)) python

I would like to compute 1/(1+exp(x)) for (possibly large) x. This is a well behaved function between 0 and 1. I could just do

import numpy as np
1.0/(1.0+np.exp(x))

but in this naive implementation np.exp(x) will likely just return 0 or infinity for large x, depending on the sign. Are there functions available in python that will help me out here?

I am considering implementing a series expansion and series acceleration, but I am wondering if this problem has already been solved.

like image 333
benbo Avatar asked Dec 29 '25 04:12

benbo


1 Answers

You can use scipy.special.expit(-x). It will avoid the overflow warnings generated by 1.0/(1.0 + exp(x)).

like image 145
Warren Weckesser Avatar answered Dec 30 '25 18:12

Warren Weckesser



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!