junfanbl
junfanbl

Reputation: 461

How to calculate a sigmoid function without using an exp() function in Python?

I'm working in somewhat of a limited development environment. I'm writing a neural network in Python. I don't have access to numpy and as it is I can't even import the math module. So my options are limited. I need to calculate the sigmoid function, however I'm not sure how the exp() function works under the hood. I understand exponents and that I can use code like:

base = .57
exp = base ** exponent

However I'm not sure what exponent should be? How do functions like numpy.exp() calculate the exponent? This is what I need to replicate.

Upvotes: 0

Views: 1148

Answers (4)

Rinshan Kolayil
Rinshan Kolayil

Reputation: 1139

def sigmoid(z):
    e = 2.718281828459
    return 1.0/(1.0 + e**(-1.0*z))

# This is the formula for sigmoid in pure python
# where z = hypothesis. You have to find the value of hypothesis 

Upvotes: 1

MisterMiyagi
MisterMiyagi

Reputation: 52029

The exponential function exp(a) is equivalent to e ** a, where e is Euler's number.

>>> e = 2.718281828459045
>>> def exp(a):
...    return e ** a
...
>>> import math  # accuracy test
>>> [math.exp(i) - exp(i) for i in range(1, 12, 3)]
[0.0, 7.105427357601002e-15, 2.2737367544323206e-13, 1.4551915228366852e-11]

Upvotes: 1

Daweo
Daweo

Reputation: 36680

how the exp() function works under the hood

If you mean math.exp from built-in module math in this place it does simply

exp(x, /)
    Return e raised to the power of x.

where e should be understand as math.e (2.718281828459045). If import math is not allowed you might do

pow(2.718281828459045, x)

instead of exp(x)

Upvotes: 0

Gornoka
Gornoka

Reputation: 71

you can use ** just fine for your use case it will work with both float and integer input

print(2**3)
8
print(2**0.5 )
1.4142135623730951

if you really need a drop in replacement for numpy.exp() you can just make a function that behaves like it is written in the docs https://numpy.org/doc/stable/reference/generated/numpy.exp.html

from typing import List
def not_numpy_exp(x:[List[float],float]):
    e = 2.718281828459045 # close enough
    if type(x) == list:
        return [e ** _x for _x in x]
    else:
        return e**x

Upvotes: 0

Related Questions