ReLU6
函数+导函数
ReLU6
函数
R e L U 6 ( x ) = { 0 x < 0 x 0 ≤ x ≤ 6 6 x > 6 \rm ReLU6(x) = \left\{ \begin{array}{ll} 0 & \quad x < 0 \\ x & \quad 0 \le x \le 6 \\ 6 & \quad x > 6 \end{array} \right. ReLU6(x)=⎩ ⎨ ⎧0x6x<00≤x≤6x>6ReLU6
函数导数
d d x R e L U 6 ( x ) = { 0 x < 0 1 0 < x < 6 0 x > 6 \frac{d}{dx} \rm ReLU6(x) = \left\{ \begin{array}{ll} 0 & \quad x < 0 \\ 1 & \quad 0 < x < 6 \\ 0 & \quad x > 6 \end{array} \right. dxdReLU6(x)=⎩ ⎨ ⎧010x<00<x<6x>6
在 x = 0 x=0 x=0和 x = 6 x=6 x=6处的导数定义可能根据具体实现有所不同,但通常在这些点的导数值可以设为0、1或按照具体应用场景的需求进行定义。ReLU6通过将输出限制在[0, 6]区间内,有助于防止激活值过大导致的梯度消失问题,并且在某些神经网络架构中(如移动网络),它能够帮助减少模型大小和计算复杂度。
函数和导函数图像
画图
import numpy as np from matplotlib import pyplot as plt # 定义 ReLU6 函数 def relu6(x): return np.minimum(np.maximum(0, x), 6) # 定义 ReLU6 的导数 def relu6_derivative(x): return np.where(x < 0, 0, np.where(x > 6, 0, 1)) # 生成数据 x = np.linspace(-2, 8, 1000) y = relu6(x) y1 = relu6_derivative(x) # 绘制图形 plt.figure(figsize=(12, 8)) ax = plt.gca() plt.plot(x, y, label='ReLU6') plt.plot(x, y1, label='Derivative') plt.title('ReLU6 and 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=2) plt.show()
优缺点
ReLU6 函数针对RELU的改进
- 数值稳定性:ReLU6 的设计初衷是为了在低精度计算环境中提高模型的鲁棒性。通过将激活值限制在 0 到 6 之间,ReLU6 可以避免激活值过大导致的数值不稳定问题
- 适用于低精度计算:ReLU6的输出范围有限,使其在低精度计算环境中(如量化神经网络)表现良好,适合在移动设备和嵌入式系统中使用
- 保持ReLU的优点:ReLU6继承了ReLU的大部分优点,如加速梯度下降、稀疏激活和减少计算复杂度
缺点:
- 可能的梯度饱和问题:当输入值大于6时,ReLU6的梯度为0,这可能导致梯度饱和,类似于ReLU的“死亡ReLU”问题。
- 输出范围受限:ReLU6的输出范围被限制在0到6之间,这可能会限制模型对某些数据模式的学习能力。
- 对输入值敏感:ReLU6对输入值的范围较为敏感,如果输入值远大于6,可能会导致梯度饱和。
- 可能的性能损失:在某些任务中,ReLU6的限制可能会导致模型性能不如ReLU或其他激活函数。
pytorch中的ReLU6函数
代码
import torch # 定义 ReLU6 函数 f = torch.nn.ReLU6() # PyTorch 提供的 ReLU6 激活函数模块 x = torch.randn(2) # 生成一个随机张量作为输入 relu6_x = f(x) # 应用 ReLU6 函数 print(f"x: \n{x}") print(f"relu6_x:\n{relu6_x}") """输出""" x: tensor([-0.3638, 0.3948]) relu6_x: tensor([0.0000, 0.3948])
tensorflow 中的ReLU6函数
代码
python: 3.10.9
tensorflow: 2.18.0
import tensorflow as tf # 创建 RELU6 激活函数 relu6 = tf.keras.activations.relu6 # 生成随机输入 # x = tf.random.normal([2]) x = [-0.3638, 0.3948] # 应用 RELU6 激活函数 relu6_x = relu6(x) print(f"x: \n{x}") print(f"relu6_x:\n{relu6_x}") """输出""" x: [-0.3638, 0.3948] relu6_x: [0. 0.3948]