pytorch-torch.nn-激活函数

激活函数

p y t o r c h pytorch pytorch中,常用的激活函数为:
s i g m o i d 激 活 函 数 ( S 型 激 活 函 数 ) / l o g i s t i c 激 活 函 数 T a n h 激 活 函 数 ( 双 曲 正 切 激 活 函 数 ) R e l u 激 活 函 数 ( 线 性 修 正 单 元 激 活 函 数 ) sigmoid激活函数(S型激活函数)/logistic激活函数\\ Tanh激活函数(双曲正切激活函数)\\ Relu激活函数(线性修正单元激活函数) sigmoid(S)/logisticTanh()Relu(线)
s i g m o i d 函 数 sigmoid函数 sigmoid:

输出为(0,1)开区间,当输入远离坐标原点时,函数的梯度就会变的很小,几乎为0,所以会影响参数的更新速度。
f ( x ) = 1 1 + e − x f(x)=\frac{1}{1+e^{-x}} f(x)=1+ex1
T a n h Tanh Tanh函数:

输出为(-1,1)开区间,整个函数是以0为中心,与sigmoid函数一样在输入很大或者很小时,梯度很小,不利于权重的更新,但是 T a n h Tanh Tanh函数输出是以0对称的,所以使用效果会比sigmoid函数好很多。
f ( x ) = e x − e − x e x + e − x f(x)=\frac{e^x-e^{-x}}{e^x+e^{-x}} f(x)=ex+exexex
R e L U ReLU ReLU函数:

只保留大于0的输出,其他输出则会设置为0,在输入正数时,不存在梯度饱和问题,计算速度相对于其他激活函数要快很多,而且ReLU函数只有线性关系,所以不管是向前传播还是向后传播,速度都很快。
f ( x ) = m a x ( 0 , x ) f(x)=max(0,x) f(x)=max(0,x)
R e L U ReLU ReLU函数的平滑近似:

β \beta β默认取值为1,该函数对任意位置都是可导的,而且尽可能的保存了 R e L U ReLU ReLU函数的优点
f ( x ) = 1 β l o g ( 1 + e β x ) f(x)=\frac{1}{\beta}log(1+e^{\beta x}) f(x)=β1log(1+eβx)

import torch as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
x = nn.linspace(-6, 6, 100)
print(x)
# sigmoid函数
ysigmoid = nn.sigmoid(x)
# tanh函数
ytanh = nn.tanh(x)
# relu函数
yrelu = nn.relu(x)
# softplus函数
ysoftplus = F.softplus(x)
plt.figure(figsize=(14, 3))
plt.subplot(1, 4, 1)
plt.plot(x.data.numpy(), ysigmoid.data.numpy(), 'r--')
plt.title("Sigmoid")
plt.grid()
plt.subplot(1, 4, 2)
plt.plot(x.data.numpy(), ytanh.data.numpy(), 'r--')
plt.title("Tanh")
plt.grid()
plt.subplot(1, 4, 3)
plt.plot(x.data.numpy(), yrelu.data.numpy(), 'r--')
plt.title("ReLU")
plt.grid()
plt.subplot(1, 4, 4)
plt.plot(x.data.numpy(), ysoftplus.data.numpy(), 'r--')
plt.title("Softplus")
# 生成网格
plt.grid()
plt.show()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45955630/article/details/112103015