最近在写没有用框架的SAE网络,前向传播过程中要用到sigmoid函数,总共30000个样本一起进入sigmoid时会发生上溢(overflow),导致算法失效。然后在csdn上看到python中sigmoid指数溢出的解决方法_innerperceptron的博客-CSDN博客_sigmoid 溢出作者的文章,发现直接抄他的代码会报错TypeError: int object is not subscriptable,所以对他的代码做了一点小小的改动,程序就能跑了。
import numpy as np
def sigmoid(x):
indices_pos=np.nonzero(x>=0)
indices_neg=np.nonzero(x<0)
n_rows,n_cols=np.shape(x)
y=np.zeros((n_rows,n_cols))
y[indices_pos] = 1 / (1 + np.exp(-x[indices_pos]))
y[indices_neg] = np.exp(x[indices_neg]) / (1 + np.exp(x[indices_neg]))
return y
x=np.array([[0,3,-3],[-1,0,6]])
print(sigmoid(x))
[[0.5 0.95257413 0.04742587]
[0.26894142 0.5 0.99752738]]
不足是矩阵比较大的时候运行速度有点慢。