Overflow Error in Python's numpy.exp function

后端 未结 4 1536
囚心锁ツ
囚心锁ツ 2020-11-30 05:31

I want to use numpy.exp like this:

cc = np.array([
    [0.120,0.34,-1234.1]
])

print 1/(1+np.exp(-cc))

But this gives me erro

4条回答
  •  天命终不由人
    2020-11-30 05:49

    A possible solution is to use the decimal module, which lets you work with arbitrary precision floats. Here is an example where a numpy array of floats with 100 digits precision is used:

    import numpy as np
    import decimal
    
    # Precision to use
    decimal.getcontext().prec = 100
    
    # Original array
    cc = np.array(
        [0.120,0.34,-1234.1]
    )
    # Fails
    print(1/(1 + np.exp(-cc)))    
    
    # New array with the specified precision
    ccd = np.asarray([decimal.Decimal(el) for el in cc], dtype=object)
    # Works!
    print(1/(1 + np.exp(-ccd)))
    

提交回复
热议问题