多层感知机
隐藏层
多层感知机(MLP)通常包括输入层、一个或多个隐藏层以及输出层。输入层接收外部数据,隐藏层对数据进行处理和变换,输出层则产生最终的结果
单隐藏层 多隐藏层
可以通过在网络中加入一个或多个隐藏层来克服线性模型的限制, 使其能处理更普遍的函数关系类型。
激活函数
sigmoid函数
import torch
import matplotlib.pyplot as plt
# 创建自变量x
x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
# 计算y = sigmoid(x)
y = torch.sigmoid(x)
# 绘制sigmoid(x)的图像
plt.figure(figsize=(5, 2.5))
plt.plot(x.detach().numpy(), y.detach().numpy())
plt.xlabel('x')
plt.ylabel('sigmoid(x)')
plt.title('Sigmoid Activation Function')
plt.grid()
plt.show()
# 清除以前的梯度
if x.grad is not None:
x.grad.data.zero_()
# 计算y相对于x的梯度
y.backward(torch.ones_like(x), retain_graph=True)
# 绘制sigmoid的梯度图像
plt.figure(figsize=(5, 2.5))
plt.plot(x.detach().numpy(), x.grad.numpy())
plt.xlabel('x')
plt.ylabel('grad of sigmoid')
plt.title('Gradient of Sigmoid')
plt.grid()
plt.show()
运行结果:
sigmoid(x)的图像 sigmoid(x)的梯度图像(该函数导数图像)
ReLU函数
import torch
import matplotlib.pyplot as plt
# 创建自变量x
x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
# 计算y = relu(x)
y = torch.relu(x)
# 绘制relu(x)的图像
plt.figure(figsize=(5, 2.5))
plt.plot(x.detach().numpy(), y.detach().numpy())
plt.xlabel('x')
plt.ylabel('relu(x)')
plt.title('ReLU Activation Function')
plt.grid()
plt.show()
# 计算y相对于x的梯度
y.backward(torch.ones_like(x), retain_graph=True)
# 绘制relu的梯度图像
plt.figure(figsize=(5, 2.5))
plt.plot(x.detach().numpy(), x.grad.numpy())
plt.xlabel('x')
plt.ylabel('grad of relu')
plt.title('Gradient of ReLU')
plt.grid()
plt.show()
运行结果:
relu(x)的图像