ReLU
- 修正线性单元 (Rectified Linear Unit)
函数+求导
-
ReLU
函数
ReLU = max ( 0 , x ) = { x x ≥ 0 0 x < 0 \begin{aligned} \operatorname{ReLU} & =\max (0, \mathrm{x}) \\ & = \begin{cases}x & x \geq 0 \\ 0 & x<0\end{cases} \end{aligned} ReLU=max(0,x)={x0x≥0x<0 -
ReLU
函数求导
d d x R e L U = { 1 x ≥ 1 0 x < 0 \frac{d}{dx} \rm ReLU = \left\{ \begin{array}{} 1 \quad x \ge1 \\ 0 \quad x < 0 \end{array} \right. dxdReLU={1x≥10x<0ReLU 函数的导数计算简单,x 大于等于零的时候,导数值恒为 1,在反向传播 过程中,它既不会放大梯度,造成梯度爆炸(Gradient exploding)现象;也不会缩小梯度,造 成梯度弥散(Gradient vanishing)现象
函数和导函数图像
-
画图
pythonimport pandas as pd import numpy as np from matplotlib import pyplot as plt def relu(x): return np.maximum(0,x) def relu_derivative(x): d = np.array(x, copy=True) # 用于保存梯度的张量 d[x < 0] = 0 # 元素为负的导数为 0 d[x >= 0] = 1 # 元素为正的导数为 1 return d x = np.linspace(-2,2,1000) y = [relu(i) for i in x] y1 = [relu_derivative(i) for i in x] plt.figure(figsize=(12,8)) ax = plt.gca() plt.plot(x,y,label='ReLU') plt.plot(x,y1,label='Derivative') plt.title('ReLU and Partial Derivative') #设置上边和右边无边框 ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') #设置x坐标刻度数字或名称的位置 ax.xaxis.set_ticks_position('bottom') #设置边框位置 ax.spines['bottom'].set_position(('data', 0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data',0)) plt.legend(loc = 6)
-
在 ReLU 函数被广泛应用之前,神经网络中激活函数采用 Sigmoid 居多,但是 Sigmoid 函数容易出现梯度弥散现象,当网络的层数增加后,较前层的参数由于梯度值非常微小, 参数长时间得不到有效更新,无法训练较深层的神经网络,导致神经网络的研究一直停留 在浅层。随着 ReLU 函数的提出,很好地缓解了梯度弥散的现象,神经网络的层数能够地 达到较深层数,如 AlexNet 中采用了 ReLU 激活函数,层数达到了 8 层,后续提出的上百 层的卷积神经网络也多是采用 ReLU 激活函数。
优缺点
-
Relu 函数优点
- 当输入为正时,ReLU 的导数为 1,能够完整传递梯度,不存在梯度消失问题(梯度饱和问题)。
- 计算速度快。ReLU 函数中只存在线性关系,且无论是函数还是其导数都不包含复杂的数学运算,因此它的计算速度比 Sigmoid 和 Tanh 更快。
- 当输入大于 0 时,梯度为 1,能够有效避免链式求导法则中梯度逐层相乘引起的梯度消失和梯度爆炸。
- 当输入为正时,梯度不为零,从而允许基于梯度的学习(尽管在 x=0,导数是未定义的)。当输入为负时,ReLU 的学习速度可能会变得很慢,甚至使神经元直接失效,因为此时输入小于零且梯度为零。
-
Relu 函数 缺点
- 当 ReLU 的输入为负时,输出始终为 0,其一阶导数也始终为 0,这会导致神经元不能更新参数,也就是神经元停止学习了,这种现象叫做"Dead Neuron"。为了解决 ReLU 函数的这个缺点,可以在 ReLU 函数的负半区间引入一个泄露(Leaky)值,这种改进称为 Leaky ReLU 函数。
- 与 Sigmoid 一样,ReLU 的输出不是以 0 为中心的(ReLU 的输出为 0 或正数)。
- ReLU 在输入小于 0 时梯度为零,这可能导致某些神经元永远被抑制,最终造成特征学习不充分;这是典型的 Dead ReLU 问题,因此需要改进随机初始化,避免将过多的负数特征送入 ReLU。
pytorch 中的 ReLU 函数
-
代码
pythonimport torch f = torch.nn.ReLU() x = torch.randn(2) relu_x = f(x) print(f"x: \n{x}") print(f"relu_x:\n{relu_x}") """输出""" x: tensor([ 0.5781, -0.4898]) relu_x: tensor([0.5781, 0.0000])
注意看,随机生成的 tensor 中,小于 0 的经过 relu 被抑制成为 0
tensorflow 中的ReLU函数
-
代码
python: 3.10.9
tensorflow: 2.18.0
pythonimport tensorflow as tf f = tf.nn.relu x = tf.random.normal([2]) relu_x = f(x) print(f"x: \n{x}") print(f"relu_x:\n{relu_x}") """输出""" x: [ 1.5739431 -0.5497837] relu_x: [1.5739431 0. ]