目录标题
一、Sigmoid函数
import torch
import matplotlib.pyplot as plt
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函数
import torch
import matplotlib.pyplot as plt
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函数
import torch
import matplotlib.pyplot as plt
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函数
import torch
# n * m 3条样本,5个特征项
x = torch.randn(3,5)
print(x)
#指定是那个维度为分类概率(即一列是一条数据还是一行是一条数据)
y = torch.softmax(x,dim=1)
print(y)