3.7.0 头文件
import torch
from torch import nn
from d2l import torch as d2l
from matplotlib import pyplot as plt
3.7.1 下载fashion_mnist数据集
# 定义批量大小
batch_size = 256
# 下载fashion_mnist,并对数据集进行打乱和按批量大小进行切割的操作,得到可迭代的训练集和测试集(训练集和测试集的形式都为(特征数据集合,数字标签集合))
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
3.7.2 网络模型
# 定义网络模型
# nn.Flatten:展平层,将输入张量压成一维,即一行多列
# nn.Linear:全连接层,有784(28×28)个输入特征,输出为10个类别
net = nn.Sequential(nn.Flatten(), nn.Linear(784, 10))
3.7.3 初始化模型参数
# 初始化全连接层权重
def init_weights(m):
# 如果这个模块是全连接层,将全连接层的权重元素随机初始化为均值为0,方差为0.01的正态分布
if type(m) == nn.Linear:
nn.init.normal_(m.weight, std=0.01)
# 将网络模型中所有子模块都调用nit_weights函数
net.apply(init_weights);
3.7.4 损失函数
# 定义交叉熵损失函数,得到的结果为每个样本的损失
loss = nn.CrossEntropyLoss(reduction='none')
3.7.5 优化器
# 定义小批量梯度下降优化器
trainer = torch.optim.SGD(net.parameters(), lr=0.15)
3.7.6 训练过程
# 定义训练轮数
num_epochs = 10
# 开始训练
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)
3.7.7 训练结果可视化
plt.savefig('OutPut.png')
本小节完整代码如下
import torch
from torch import nn
from d2l import torch as d2l
from matplotlib import pyplot as plt
# ------------------------------下载fashion_mnist数据集------------------------------------
# 定义批量大小
batch_size = 256
# 下载fashion_mnist,并对数据集进行打乱和按批量大小进行切割的操作,得到可迭代的训练集和测试集(训练集和测试集的形式都为(特征数据集合,数字标签集合))
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
# ------------------------------网络模型------------------------------------
# 定义网络模型
# nn.Flatten:展平层,将输入张量压成一维,即一行多列
# nn.Linear:全连接层,有784(28×28)个输入特征,输出为10个类别
net = nn.Sequential(nn.Flatten(), nn.Linear(784, 10))
# ------------------------------初始化模型参数------------------------------------
# 初始化全连接层权重
def init_weights(m):
# 如果这个模块是全连接层,将全连接层的权重元素随机初始化为均值为0,方差为0.01的正态分布
if type(m) == nn.Linear:
nn.init.normal_(m.weight, std=0.01)
# 将网络模型中所有子模块都调用nit_weights函数
net.apply(init_weights);
# ------------------------------损失函数------------------------------------
# 定义交叉熵损失函数,得到的结果为每个样本的损失
loss = nn.CrossEntropyLoss(reduction='none')
# ------------------------------优化器------------------------------------
# 定义小批量梯度下降优化器
trainer = torch.optim.SGD(net.parameters(), lr=0.15)
# ------------------------------训练过程------------------------------------
# 定义训练轮数
num_epochs = 10
# 开始训练
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)
# ------------------------------训练结果可视化------------------------------------
plt.savefig('OutPut.png')
浙公网安备 33010602011771号