☰
深度学习21:PyTorch:激活函数(Sigmoid,Tanh,ReLU,Softmax)
2026/10/28 18:56:19 网站建设 项目流程

目录标题

      • 一、Sigmoid函数
      • 二、Tanh函数
      • 三、ReLU函数
      • 四、Softmax函数

一、Sigmoid函数

importtorchimportmatplotlib.pyplotasplt x=torch.linspace(-10,10,steps=1000,requires_grad=True)y=torch.sigmoid(x)# 画图fig,ax=plt.subplots(nrows=1,ncols=2,figsize=(12,4))# 1. 原函数图像ax[0].plot(x.data,y.data,"purple")ax[0].set_title("sigmoid(x)")# 绘制参考线ax[0].axhline(y=0.5,color='gray',alpha=0.5,linewidth=1)ax[0].axhline(y=1,color='gray',alpha=0.5,linewidth=1)# 图的边框ax[0].spines['top'].set_visible(False)ax[0].spines['right'].set_visible(False)ax[0].spines['left'].set_position('zero')ax[0].spines['bottom'].set_position('zero')# 反向传播,计算 x 的梯度y.sum().backward()# 2. 导数函数图像ax[1].plot(x.data,x.grad,"purple")ax[1].set_title("sigmoid'(x)")# 图的边框ax[1].spines['top'].set_visible(False)ax[1].spines['right'].set_visible(False)ax[1].spines['left'].set_position('zero')ax[1].spines['bottom'].set_position('zero')# plt.show()plt.savefig('sigmoid_result.png')

二、Tanh函数

importtorchimportmatplotlib.pyplotasplt x=torch.linspace(-5,5,steps=1000,requires_grad=True)y=torch.tanh(x)# 画图fig,ax=plt.subplots(nrows=1,ncols=2,figsize=(12,4))# 1. 原函数图像ax[0].plot(x.data,y.data,"purple")ax[0].set_title("tanh(x)")# 绘制参考线ax[0].axhline(y=-1,color='gray',alpha=0.5,linewidth=1)ax[0].axhline(y=1,color='gray',alpha=0.5,linewidth=1)# 图的边框ax[0].spines['top'].set_visible(False)ax[0].spines['right'].set_visible(False)ax[0].spines['left'].set_position('zero')ax[0].spines['bottom'].set_position('zero')# 反向传播,计算 x 的梯度y.sum().backward()# 2. 导数函数图像ax[1].plot(x.data,x.grad,"purple")ax[1].set_title("tanh'(x)")#图的边框ax[1].spines['top'].set_visible(False)ax[1].spines['right'].set_visible(False)ax[1].spines['left'].set_position('zero')ax[1].spines['bottom'].set_position('zero')# plt.show()plt.savefig('tanh_result.png')

三、ReLU函数

importtorchimportmatplotlib.pyplotasplt x=torch.linspace(-5,5,steps=1000,requires_grad=True)y=torch.relu(x)# 画图fig,ax=plt.subplots(nrows=1,ncols=2,figsize=(12,4))# 1. 原函数图像ax[0].plot(x.data,y.data,"purple")ax[0].set_title("relu(x)")ax[0].spines['top'].set_visible(False)ax[0].spines['right'].set_visible(False)ax[0].spines['left'].set_position('zero')ax[0].spines['bottom'].set_position('zero')# 反向传播,计算 x 的梯度y.sum().backward()# 2. 导数函数图像ax[1].plot(x.data,x.grad,"purple")ax[1].set_title("relu'(x)")ax[1].spines['top'].set_visible(False)ax[1].spines['right'].set_visible(False)ax[1].spines['left'].set_position('zero')ax[1].spines['bottom'].set_position('zero')# plt.show()plt.savefig('relu_result.png')

四、Softmax函数

importtorch# n * m 3条样本,5个特征项x=torch.randn(3,5)print(x)#指定是那个维度为分类概率(即一列是一条数据还是一行是一条数据)y=torch.softmax(x,dim=1)print(y)

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询