几种基础的激活函数及其实现
说明:
- 首次发表日期:2024-10-31
- 参考:
神经元(Neuron)
以下为一个神经元:
可以使用向量来表达:
- : 输入(input)
- : 权重(weights)
- :偏置(bias)
假设激活函数为,那么输出为:
激活函数
Binary Threshold
def binary(z : np.array, k: float) -> np.array:
"""
Function to execute the binary threshold activation
Inputs:
z : input dot product w*x + b
Output:
y : determined activation
"""
return np.round(z >= k)
z = np.linspace(-4,4,num=100)
y = binary(z)
Sigmoid
- 如果是一个很大的正数,那么 趋近于 0, 然后 趋近于 1
- 如果是一个很大的负数,那么 趋近于 无穷大, 然后 趋近于 0
- 如果,那么 ,然后
def sigmoid(z : np.array) -> np.array:
"""
Function to execute the sigmoid activation
Inputs:
z : input dot product w*x + b
Output:
y : determined activation
"""
return 1/(1+np.exp(-z))
z = np.linspace(-5,5,num=100)
y = sigmoid(z)
sigmoid 激活函数常用于 binary classification problems
Softmax
Softmax激活函数适用于 Multiclass classification problems
如果有 个输出分类:
softmax是argmax函数的 smooth approximation
def softmax(z : np.array) -> np.array:
"""
Function to execute the softmax activation
Inputs:
z : input dot product w*x + b
Output:
y : determined activation
"""
return np.exp(z)/np.sum(np.exp(z))
ReLU
def relu(z : np.array) -> np.array:
"""
Function to execute the ReLU activation
Inputs:
z : input dot product w*x + b
Output:
y : determined activation
"""
return np.where(z>=0,z,0)
当 为非正数时,输出和梯度均为0,梯度为0会导致训练停止。
PReLU
其中 是一个通过训练来学习的参数 (learnable parameter)。
相比于ReLU,即使 为负数,梯度也不会为0。
- 当 ,, 激活函数被称为 absolute value ReLU
- 当 为一个较小的正数,通常在 0.01 左右,激活函数被称为 leaky ReLU
Tanh
def tanh(z : np.array) -> np.array:
"""
Function to execute the tanh activation
Inputs:
z : input dot product w*x + b
Output:
y : determined activation
"""
return (np.exp(z) - np.exp(-z))/(np.exp(z)+np.exp(-z))
- 当输入 是一个大的正数时, 趋近于0,, 因此 y 趋近于
- 当输入 是一个大的负数时, 趋近于0,, 因此 y 趋近于
- 当输入 为 0 时, , 因此
SoftPlus
SoftPlus 可以看做是 ReLU 的 smooth approximation
其中应用了:
和
另外:
def softplus(z : np.array) -> np.array:
"""
Function to execute the softplus activation
Inputs:
z : input dot product w*x + b
Output:
y : determined activation
"""
return np.log(1 + np.exp(-np.abs(z))) + np.maximum(z, 0)
Swish
def swish(z : np.array) -> np.array:
"""
Function to execute the swish activation
Inputs:
z : input dot product w*x + b
Output:
y : determined activation
"""
return z/(1+np.exp(-z))