RELU(Recitified Linear Unit )线性整流单元又称为线性修正单元,是神经网络中最普遍的激活函数之一,可以用于解决梯度爆炸或梯度消失的问题,相对于其它激活函数其计算效率也比较高。其数学公式为:
函数图像如下图所示:
最近在看论文的时候发现一些计算机视觉领域的大佬已经开始使用GELU激活函数。其基本原理为:受到Dropout、ReLU等机制的影响,它们都希望将不重要的激活信息规整为0,我们可以理解为,对于输入的值,我们根据它的情况乘上1或者0,更数学一点的描述是,对于每一个输入x,其服从标准的正态分布,在之后乘上伯努利分布,其中= 。
GELU的函数表达式可以简化为:
完整形式可以表示为:
可以化简为:
函数图像为:左图函数图,中间一阶导数,右图二阶导数
其matlab代码为:
syms x;
y = 0.5*x.*(1 + tanh(sqrt(2/pi).*(x + 0.044715 * x.^3)));
% title('GELU');
subplot(1,3,1)
fplot(y,[-10,10]) % 绘制原函数图像,[-10;10]代表自变量区间
dy = diff(y,x) ;
% title('一阶导数'); % 求解一阶导数
subplot(1,3,2)
fplot(dy,[-10,10])
ddy=diff(y,x,2) ; % 求解二阶导数
subplot(1,3,3)
% title('二阶导数');
fplot(ddy,[-10,10])
python代码为(引用别的文献):
# -*- coding: utf-8 -*-
# @Time : 2021/7/30 11:01 上午
# @Author : Ada
import numpy as np
import matplotlib.pyplot as plt
import torch
def gelu_1(x):
#使用numpy实现
return 0.5*x*(1 + np.tanh(np.sqrt(2/np.pi)*(x + 0.044715*x**3)))
def gelu_dao(inputs):
return ((np.tanh((np.sqrt(2) * (0.044715 * inputs ** 3 + inputs)) / np.sqrt(np.pi)) + ((np.sqrt(2) * inputs * (
0.134145 * inputs ** 2 + 1) * ((1 / np.cosh(
(np.sqrt(2) * (0.044715 * inputs ** 3 + inputs)) / np.sqrt(np.pi))) ** 2)) / np.sqrt(np.pi) + 1))) / 2
def plot_gelu():
x1=np.arange(-8,8,0.1)
y1=gelu_1(x1)
#plt.plot(x1,y1)
y2=gelu_dao(x1)
plt.plot(x1,y2)
plt.show()
if __name__ == '__main__':
plot_gelu()
python代码来自:知乎