几种基础的激活函数及其实现
几种基础的激活函数及其实现
说明:
- 首次发表日期: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)
当
PReLU
其中
相比于ReLU,即使
- 当
, , 激活函数被称为 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))
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)