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)
#1.初始化模型参数:为了实现我们的模型,我们只需在Sequential中添加一个带有10个输出的全连接层
#同样,在这里Sequential并不是必要的,但它是实现深度模型的基础。我们仍然以均值0和标准差0.01随机初始化权重。
#pytorch不会隐式地调整输入的形状。在线性层前定义了展平层(flatten),来调整网络输入的形状
net = nn.Sequential(nn.Flatten(),nn.Linear(784,10))
def init_weights(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight,std=0.01)
net.apply(init_weights);
#2.重新审视Softmax的实现:没有将softmax概率传递到损失函数中,而是在交叉熵损失函数中传递未规范化的预测,并同时计算softmax及其对数,这是一种类似“LogSumExp技巧”的聪明方式。
loss = nn.CrossEntropyLoss(reduction='none')
#3.优化算法:使用学习率为0.1的小批量随机梯度下降作为优化算法。这与我们在线性回归例子中的相同,这说明了优化器的普适性。
trainer = torch.optim.SGD(net.parameters(), lr=0.1)
#4.训练
num_epochs = 10
d2l.train_ch3(net,train_iter,test_iter,loss,num_epochs,trainer)
d2l.plt.show()
1.台式机运行代码后,出现各种错误,“页面文件太小,无法完成操作”等等,耗费大量时间和精力还是改不掉,遂用笔记本跑,结果只出现了一个d2l包的错误:AttributeError: module ‘d2l.torch‘ has no attribute ‘train_ch3‘-优快云博客
2.接着动画不显示,按照这个网页的办法改掉了。李沐动手学深度学习 pytorch 在pycharm中无法显示动图_李沐 图不出来-优快云博客
最后结果如上图所示。