二分类: -1 或 1
- Vs.回归输出实数
- Vs.Softmax回归输出概率
总结:
- 多层感知机使用隐藏层和激活函数来得到线性模型
- 常用的激活函数是Sigmoid, Tanh, Relu
- 使用Softmax处理多类分类
- 超参数为隐藏层数,和各个隐藏层大小
import torch
from torch import nn
from d2l import torch as d2l
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
# 初始化模型参数
num_inputs, num_outputs, num_hiddens = 784, 10, 256 # 输入特征, 输出类别,隐藏层单元数
W1 = nn.Parameter(torch.randn(num_inputs, num_hiddens, requires_grad=True) * 0.01)
b1 = nn.Parameter(torch.zeros(num_hiddens, requires_grad=True))
W2 = nn.Parameter(torch.randn(num_hiddens, num_outputs, requires_grad=True) * 0.01)
b2 = nn.Parameter(torch.zeros(num_outputs, requires_grad=True))
params = [W1, b1, W2, b2] # 设置参数列表
# 激活函数
def relu(X):
a = torch.zeros_like(X)
return torch.max(X, a)
# 模型
def net(X):
X = X.reshape(-1, num_inputs)
H = relu(X @ W1 + b1) # 这里的@代表矩阵乘法
return (H @ W2 + b2)
# 损失函数(交叉熵损失)
loss = nn.CrossEntropyLoss(reduction='none')
# 训练
num_epochs, lr = 10, 0.1 # 训练轮数与学习率
updater = torch.optim.SGD(params, lr=lr)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)
d2l.predict_ch3(net, test_iter) # 对模型进行评估
d2l.plt.show()