Fork me on GitHub

Activation Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#为什么需要激励函数?Why need activation function?
#激励函数就是为了解决不能用线性方程(Linear)解决的问题,y=w*x+b。也就是非线性方程问题(Nonlinear)
#y=Wx-->y=AF(Wx)
#一些常用的AF非线性函数,比如relu,sigmoid,tanh,也就是激励函数
#relu为,x>0,f(x)=1,x<=0,f(x=0)
#你也可以自己创建自己的激励函数,但是函数必须保证是可微分的
#在卷积神经网络中,推荐使用relu激励函数
#在循环神经网络中(Recurrent Nerual Network)推荐适用relu or tanh
#sigmoid函数,也叫Logistics会出现梯度消失
import numpy as np
import matplotlib.pyplot as plt


def sigmoid(x):
y = 1.0 / (1.0 + np.exp(-x))
return y


def elu(x, a):
y = x.copy()
for i in range(y.shape[0]):
if y[i] < 0:
y[i] = a * (np.exp(y[i]) - 1)
return y


def lrelu(x, a):
y = x.copy()
for i in range(y.shape[0]):
if y[i] < 0:
y[i] = a * y[i]
return y


def relu(x):
y = x.copy()
y[y < 0] = 0
return y


def softplus(x):
y = np.log(np.exp(x) + 1)
return y


def softsign(x):
y = x / (np.abs(x) + 1)
return y


def tanh(x):
y = (1.0 - np.exp(-2 * x)) / (1.0 + np.exp(-2 * x))
return y

#invoke this function
x = np.linspace(start=-10, stop=10, num=100)
y_sigmoid = sigmoid(x)
y_elu = elu(x, 0.25)
y_lrelu = lrelu(x, 0.25)
y_relu = relu(x)
y_softplus = softplus(x)
y_softsign = softsign(x)
y_tanh = tanh(x)

tx = 6
ty = 0.9

#display the graph
plt.subplot(331)
plt.title('sigmoid')
plt.plot(x, y_sigmoid)
plt.grid(True)
plt.subplot(332)
plt.title('elu')
plt.plot(x, y_elu)
plt.grid(True)
plt.subplot(333)
plt.title('lrelu')
plt.plot(x, y_lrelu)
plt.grid(True)
plt.subplot(334)
plt.title('relu')
plt.plot(x, y_relu)
plt.grid(True)
plt.subplot(335)
plt.title('softplus')
plt.plot(x, y_softplus)
plt.grid(True)
plt.subplot(336)
plt.title('softsign')
plt.plot(x, y_softsign)
plt.grid(True)
plt.subplot(337)
plt.title('tanh')
plt.plot(x, y_tanh)
plt.grid(True)
plt.show()

Activatoin Function