神經網路激活函數的公式與特性(帶公式說明)
1. 分段線性激活函數
- ReLU
公式:# Python 實現 ReLU import numpy as np def relu(x): return np.maximum(0, x) x = np.array([-2, -1, 0, 1, 2]) print(relu(x))
- PReLU
公式: ,讓負值不會完全變為 0,避免 ReLU 的死區問題。# Python 實現 PReLU import numpy as np def prelu(x, alpha=0.1): return np.maximum(0, x) + alpha * np.minimum(0, x) x = np.array([-2, -1, 0, 1, 2]) print(prelu(x))
- RReLU
公式: ,提升模型的隨機性和正則化效果。# Python 實現 RReLU import numpy as np def rrelu(x, l=0.1, u=0.3): a = np.random.uniform(l, u) return np.where(x >= 0, x, a * x) x = np.array([-2, -1, 0, 1, 2]) print(rrelu(x))
2. 平滑非線性激活函數
- GELU
公式:# Python 實現 GELU import numpy as np def gelu(x): return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x**3))) x = np.array([-2, -1, 0, 1, 2]) print(gelu(x))
- Swish
公式:# Python 實現 Swish import numpy as np def swish(x): return x / (1 + np.exp(-x)) x = np.array([-2, -1, 0, 1, 2]) print(swish(x))
- Mish
公式:# Python 實現 Mish import numpy as np def mish(x): return x * np.tanh(np.log(1 + np.exp(x))) x = np.array([-2, -1, 0, 1, 2]) print(mish(x))
應用建議
- 基礎應用:ReLU 簡單高效,適合大多數場景。
- 深層模型:Swish、Mish、GELU 等能提高深層網路性能。
- 正則化需求:SELU 和 RReLU 可提供更好的穩定性。
- 數據分佈:Tanh 適合零中心化,SoftPlus 適合平滑輸出場景。