神经网络常见激活函数 7-ELU函数
文章目录
- ELU
- 函数+导函数
- 函数和导函数图像
- 优缺点
- pytorch中的ELU函数
- tensorflow 中的ELU函数
ELU
- 指数线性单元:ELU(Exponential Linear Unit)
函数+导函数
-
ELU
函数
E L U = { x x > = 0 α ( e x − 1 ) x < 0 \rm ELU = \left\{ \begin{array}{} x \quad &x>=0 \\ \alpha(e^x - 1) \quad &x<0 \end{array} \right. ELU={xα(ex−1)x>=0x<0
其中 是一个大于 0 的超参数,通常取值为 1。 -
ELU
函数导数
d d x E L U = { 1 x > = 0 α e x x < 0 \frac{d}{dx} \rm ELU = \left\{ \begin{array}{} 1 \quad &x >= 0 \\ \alpha e^x \quad &x < 0 \end{array} \right. dxdELU={1αexx>=0x<0
函数和导函数图像
-
画图
下面的 α \alpha α 取值为 1
import numpy as np from matplotlib import pyplot as plt # 定义 ELU 函数 def elu(x, alpha=1.0): return np.where(x > 0, x, alpha * (np.exp(x) - 1)) # 定义 ELU 的导数 def elu_derivative(x, alpha=1.0): return np.where(x > 0, 1, alpha * np.exp(x)) # 生成数据 x = np.linspace(-2, 2, 1000) alpha = 1 # 可以调整 alpha 的值 y = elu(x, alpha) y1 = elu_derivative(x, alpha) # 绘制图形 plt.figure(figsize=(12, 8)) ax = plt.gca() plt.plot(x, y, label='ELU') plt.plot(x, y1, label='Derivative') plt.title(f'ELU (α={alpha}) 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=2) plt.show()
优缺点
-
ELU 的优点
- 处理梯度消失问题:ELU通过在负输入时引入非零梯度,缓解了梯度消失问题。
- 引入负值:ELU允许负值,这使得模型能够学习更好的表示。
- 平滑过渡:ELU函数是平滑的,避免了ReLU在零点处的不连续性,这有助于优化和梯度流。
- 加速收敛:ELU通常能够更快地收敛,并在训练的早期阶段实现更好的准确率。
- 避免死神经元:与ReLU不同,ELU确保所有单元保持活跃,避免了“死神经元”问题。
- 推动零均值激活:ELU的负值有助于将激活值推向零均值,从而改善学习动态。
-
ELU 的缺点
- ELU也是为了解决 Dead RELU 而剔除的改进型。计算上稍微比Leaky ReLU复杂一点,但是从精度上看似乎并未提高多少。
- 尽管理论上比ReLU更好,但目前在实践中没有充分的证据表明ELU总是比ReLU好。
pytorch中的ELU函数
-
代码
import torch # 定义 ELU 函数 f = torch.nn.ELU(alpha=1) # PyTorch 提供的 ELU 激活函数模块 x = torch.randn(2) # 生成一个随机张量作为输入 elu_x = f(x) # 应用 ELU 函数 print(f"x: \n{x}") print(f"elu_x:\n{elu_x}") """输出""" x: tensor([ 0.3435, -2.3949]) elu_x: tensor([ 0.3435, -0.9088])
tensorflow 中的ELU函数
-
代码
python: 3.10.9
tensorflow: 2.18.0
import tensorflow as tf # 创建 ELU 激活函数层 elu = tf.keras.layers.ELU(alpha=1.0) # 生成随机输入 x = tf.random.normal([2]) # 应用 ELU 激活函数 elu_x = elu(x) print(f"x: \n{x}") print(f"elu_x:\n{elu_x}") """输出""" x: [-1.4998378 -0.2037226] elu_x: [-0.77683365 -0.18431139]