How to calculate a logistic sigmoid function in Python?

后端 未结 15 1673
情话喂你
情话喂你 2020-11-29 16:14

This is a logistic sigmoid function:

\"enter

I know x. How can I calculate F(x

相关标签:
15条回答
  • 2020-11-29 16:55

    Below is the python function to do the same.

    def sigmoid(x) :
        return 1.0/(1+np.exp(-x))
    
    0 讨论(0)
  • 2020-11-29 16:58

    A numerically stable version of the logistic sigmoid function.

        def sigmoid(x):
            pos_mask = (x >= 0)
            neg_mask = (x < 0)
            z = np.zeros_like(x,dtype=float)
            z[pos_mask] = np.exp(-x[pos_mask])
            z[neg_mask] = np.exp(x[neg_mask])
            top = np.ones_like(x,dtype=float)
            top[neg_mask] = z[neg_mask]
            return top / (1 + z)
    
    0 讨论(0)
  • 2020-11-29 17:02

    Another way by transforming the tanh function:

    sigmoid = lambda x: .5 * (math.tanh(.5 * x) + 1)
    
    0 讨论(0)
  • 2020-11-29 17:06

    another way

    >>> def sigmoid(x):
    ...     return 1 /(1+(math.e**-x))
    ...
    >>> sigmoid(0.458)
    
    0 讨论(0)
  • 2020-11-29 17:07

    Here's how you would implement the logistic sigmoid in a numerically stable way (as described here):

    def sigmoid(x):
        "Numerically-stable sigmoid function."
        if x >= 0:
            z = exp(-x)
            return 1 / (1 + z)
        else:
            z = exp(x)
            return z / (1 + z)
    

    Or perhaps this is more accurate:

    import numpy as np
    
    def sigmoid(x):  
        return math.exp(-np.logaddexp(0, -x))
    

    Internally, it implements the same condition as above, but then uses log1p.

    In general, the multinomial logistic sigmoid is:

    def nat_to_exp(q):
        max_q = max(0.0, np.max(q))
        rebased_q = q - max_q
        return np.exp(rebased_q - np.logaddexp(-max_q, np.logaddexp.reduce(rebased_q)))
    

    (However, logaddexp.reduce could be more accurate.)

    0 讨论(0)
  • 2020-11-29 17:09

    Tensorflow includes also a sigmoid function: https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/sigmoid

    import tensorflow as tf
    
    sess = tf.InteractiveSession()
    x = 0.458
    y = tf.sigmoid(x)
    
    u = y.eval()
    print(u)
    # 0.6125396
    
    0 讨论(0)
提交回复
热议问题