网页前端是什么,网站互动优化,桂林刚刚发生的事,网页版微信二维码加载失败环境:练习1的环境
代码详解
0.导入库
import torch
from torch import nn
from d2l import torch as d2l1.初始化数据 这里初始化出train_iter test_iter 可以查一下之前的获取Fashion数据集后的数据格式与此对应
n_train, n_test, num_inputs, batch_size 20, 100, 200, …环境:练习1的环境
代码详解
0.导入库
import torch
from torch import nn
from d2l import torch as d2l1.初始化数据 这里初始化出train_iter test_iter 可以查一下之前的获取Fashion数据集后的数据格式与此对应
n_train, n_test, num_inputs, batch_size 20, 100, 200, 5
true_w, true_b torch.ones((num_inputs, 1)) * 0.01, 0.05
train_data d2l.synthetic_data(true_w, true_b, n_train)
train_iter d2l.load_array(train_data, batch_size)
test_data d2l.synthetic_data(true_w, true_b, n_test)
test_iter d2l.load_array(test_data, batch_size, is_trainFalse)2.简洁实现
这补充个多层的写法 optimizer torch.optim.SGD([ {“params”: net[0].weight, “weight_decay”: wd}, {“params”: net[0].bias}, {“params”: net[1].weight, “weight_decay”: wd}, {“params”: net[1].bias}, {“params”: net[2].weight, “weight_decay”: wd}, {“params”: net[2].bias} ], lrlr)
def train_concise(wd):#定义了一层线性层模型,输入特征个数是num_inputs(怎么来的?) 输出个数是1netnn.Sequential(nn.Linear(num_inputs,1)) for param in net.parameters():#初始化w,b 按照(均值为0方差为1)来初始化,b会被随机初始化为较小的值param.data.normal_()#定义损失函数lossnn.MSELoss(reductionnone)num_epochs,lr100,0.03#定义优化器(这里开始设置限制w^2对于损失函数的影响大小了 - wd)#这段代码包含了神经网络第一层的所有参数并且为这些参数应用了不同的设置或限制#因为这个模型只有一层trainertorch.optim.SGD([{params:net[0].weight,weight_decay: wd},{params:net[0].bias}], lrlr)#x轴是epochs y轴是loss #x轴设置范围从第五轮到 最后一轮 y轴设置对数标度 对数标度:对原始数据进行对数变换后显示的#legend[train, test]: 这为图表设置了图例标识两条曲线分别代表训练集train和测试集test的损失值animator d2l.Animator(xlabelepochs, ylabelloss, yscalelog,xlim[5, num_epochs], legend[train, test])for epoch in range(num_epochs):for X, y in train_iter:trainer.zero_grad()l loss(net(X), y)l.mean().backward()trainer.step()if (epoch 1) % 5 0:#相当于在animator增加数据点 epoch,训练平均损失,测试平均损失animator.add(epoch 1,(d2l.evaluate_loss(net, train_iter, loss),d2l.evaluate_loss(net, test_iter, loss)))print(w的L2范数, net[0].weight.norm().item())#开始测试
train_concise(0)重点理解
1.权重衰减是怎么做到的: LossLosslamb/2 * (w^2) 当w越大Loss越大,Loss越大,越要减小,也同时减小w
2.原理: 多个函数下如何算最值
3.代码实现: trainertorch.optim.SGD([ {“params”:net[0].weight,‘weight_decay’: wd}, {“params”:net[0].bias}], lrlr)
参考视频: https://www.bilibili.com/video/BV1Z44y147xA/?spm_id_from333.999.0.0vd_source302f06b1d8c88e3138547635c3f4de52