pytorch: 学习笔记8, pytorch激活函数

本文详细介绍了四种常见的激活函数:ReLU、Sigmoid、Tanh和Mish。通过图表展示了每种函数的形状及其导数,帮助读者直观理解不同激活函数的特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

激活函数:

1, relu
2, sigmoid
3, tanh
4, (Mish)

#1, relu激活函数 ReLU(x)=max(x,0)
x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
y = x.relu()  # 激活函数

plt.figure(1, figsize=(8, 6))
plt.subplot(1, 2, 1)
plt.plot(x.detach().numpy(), y.detach().numpy())
plt.xlabel('x')
plt.ylabel('relu' + '(x)')

plt.subplot(1, 2, 2)
y.sum().backward()
plt.plot(x.detach().numpy(), x.grad.detach().numpy())
plt.xlabel('x')
plt.ylabel('grad of relu' + '(x)')
plt.savefig('relu.png')
plt.show()

在这里插入图片描述

# 2, sigmoid函数: sigmoid(x) =1 / (1 + exp(−x))
x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
y = x.sigmoid()  # 激活函数

plt.figure(2, figsize=(8, 6))
plt.subplot(1, 2, 1)
plt.plot(x.detach().numpy(), y.detach().numpy())
plt.xlabel('x')
plt.ylabel('sigmoid' + '(x)')

plt.subplot(1, 2, 2)
y.sum().backward()
plt.plot(x.detach().numpy(), x.grad.detach().numpy())
plt.xlabel('x')
plt.ylabel('grad of sigmoid' + '(x)')
plt.savefig('sigmoid.png')
plt.show()

在这里插入图片描述

# 3, tanh(双曲正切)函数:tanh(x)= (1−exp(−2x)) / (1+exp(−2x))
x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
y = x.tanh()  # 激活函数

plt.figure(3, figsize=(8, 6))
plt.subplot(1, 2, 1)
plt.plot(x.detach().numpy(), y.detach().numpy())
plt.xlabel('x')
plt.ylabel('tanh' + '(x)')

plt.subplot(1, 2, 2)
y.sum().backward()
plt.plot(x.detach().numpy(), x.grad.detach().numpy())
plt.xlabel('x')
plt.ylabel('grad of tanh' + '(x)')
plt.savefig('tanh.png')
plt.show()

在这里插入图片描述

# 4, Mish函数: Mish(x) = x * tanh(log(1 + exp(x)))
x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
y = x * (torch.tanh(F.softplus(x)))  # 实现

plt.figure(4, figsize=(8, 6))
plt.subplot(1, 2, 1)
plt.plot(x.detach().numpy(), y.detach().numpy())
plt.xlabel('x')
plt.ylabel('Mish' + '(x)')

plt.subplot(1, 2, 2)
y.sum().backward()
plt.plot(x.detach().numpy(), x.grad.detach().numpy())
plt.xlabel('x')
plt.ylabel('grad of Mish' + '(x)')
plt.savefig('Mish.png')
plt.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值