激活函数已经成为神经网络中非常重要的一部分,随着各种类型的神经网络模型被人们开发出来,各种激活函数也应运而生,在不同的场景中,取得良好的效果。本文跟据著名的YOLO系列目标检测模型的源码 AlexeyAB Darknet,整理出目前神经网络模型中应用最广泛的20种激活函数,对它们的计算公式、图像特点进行介绍,并使用python代码实现这些激活函数的计算。
1、stair激活函数
如图1所示,stair激活函数的图像就像阶梯一样。它的计算公式如下:
式子中,表示不大于x的整数,
表示对2取余数。

代码实现如下:
def stair(x):
n=math.floor(x)
if n%2==0:
return math.floor(x/2.0)
else:
return (x-n)+math.floor(x/2.0)
2、hardtan激活函数
如图2所示,hardtan激活函数是通过以直代曲近似实现tan函数,其计算公式如下:

代码实现如下:
def hardtan(x):
if x<-1.0:
return -1.0
elif x>1.0:
return 1.0
else:
return x
3、linear激活函数
linear激活函数是线性激活函数,输入x输出也是x,其函数图像如图3所示。

代码实现:
def linear(x):
return x
4、logistic激活函数
logistic激活函数又叫sigmoid激活函数,如图4所示,logistic函数可以结果映射到0到1之间。其计算公式如下:

代码实现如下:
def logistic(x):
return 1.0/(1.0+math.exp(-x))
5、loggy激活函数
如图5所示,loggy的函数图像跟logistic有点相似,也是把输出映射到0到1之间。其计算公式如下:

代码实现:
def loggy(x):
return 2.0/(1.0+math.exp(-x))-1.0
6、relu激活函数
relu激活函数为线性整流函数,目的是把小于0的数截取掉,其函数图像如图6所示,其计算公式如下:

代码实现如下:
def relu(x):
return x*(x>0)
7、relu6激活函数
relu6和relu一样,也是线性整流函数,不同的是他对大于6的数进行了截断,其函数图像如图7所示,其计算公式如下:

代码实现如下:
def relu6(x):
if x<0:
return 0.0
elif x>6:
return 6.0
else:
return x
8、elu激活函数
elu激活函数的图像如图8所示,其计算公式如下:

代码实现:
def elu(x):
return (x>=0)*x+(x<0)*(math.exp(x)-1.0)
9、selu激活函数
selu激活函数如图9所示,其计算公式如下:

代码实现:
def selu(x):
return (x>=0)*1.0507*x+(x<0)*1.0507*1.6732*(math.exp(x)-1.0)
10、relie激活函数
相比于relu激活函数,relie激活函数对于小于零的数据并不会直接截取为0,二是乘以一个小的系数,这个系数为0.01。其函数图像如图10所示,其计算公式如下:

代码实现:
def relie(x):
if x>0:
return x
else:
return 0.01*x
11、ramp激活函数
如图11所示为ramp激活函数,其计算公式如下:

代码实现:
def ramp(x):
return x*(x>0)+0.1*x
12、leaky激活函数
如图12所示为leaky激活函数的图像,它与relie函数有点像,它的斜率系数要比relie激活函数要大,其计算公式如下:

代码实现如下:
def leaky(x):
if x<0:
return 0.1*x
else:
return x
13、tanh激活函数
tanh激活函数的图像如图13所示,它的取值范围是[-1,1],其计算公式如下:

代码实现:
def tanh(x):
return 2.0/(1.0+math.exp(-2.0*x))-1.0
14、gelu激活函数
gelu激活函数的图像如图14所示,其计算公式如下:
式中,tanh为上文提到过的激活函数。

代码实现如下:
def gelu(x):
return 0.5*x*(1.0+math.tanh(0.797885*x+0.035677*math.pow(x,3.0)))
15、softplus激活函数
softplus激活函数的图像如图15所示,其计算公式如下:

代码实现:
def softplus(x,threshold):
if x>threshold:
return x
elif x<-threshold:
return math.exp(x)
else:
return math.log(math.exp(x)+1.0)
16、plse激活函数
图16位plse激活函数的图像,其计算公式如下:

代码实现:
def plse(x):
if x<-4:
return 0.01*(x+4.0)
elif x>4:
return 0.01*(x-4.0)+1.0
else:
return 0.125*x+0.5
17、lhtan激活函数
图17是lhtan激活函数的图像,其计算公式为:

代码实现:
def lhtan(x):
if x<0:
return 0.001*x
elif x>1:
return 0.001*(x-1.0)+1.0
else:
return x
18、swish激活函数
图18是swish激活函数的图像,其计算公式如下:
式中,logistic为上文所提到的激活函数,也叫sigmoid激活函数。

代码实现:
def logistic(x):
return 1.0/(1.0+math.exp(-x))
def swish(x):
return x*logistic(x)
19、mish激活函数
mish激活函数的图像如图19所示,其计算公式如下:
式中tanh,softplus均为上文描述过的激活函数。

代码实现如下:
def softplus(x,threshold):
if x>threshold:
return x
elif x<-threshold:
return math.exp(x)
else:
return math.log(math.exp(x)+1.0)
def tanh(x):
return 2.0/(1.0+math.exp(-2.0*x))-1.0
def mish(x):
return x*tanh(softplus(x,20.0))
20、hardmish激活函数
hardmish激活函数为mish激活函数的近似形式,它的图像如图20所示,其计算公式如下:

代码实现:
def hardmish(x):
if x>0:
return x
elif x>-2:
return x*x*0.5+x
else:
return 0