d2l 线性回归的从零开始实现

线性回归的从零开始实现

  • 导入需要使用的包
  • 数据流水线、模型、损失函数、小批量随机梯度下降器

1. 构造人造数据集

  • y=xw+b+c
  • feature,label=synthetic_data(w,b,num)
  • detach().numpy()有些版本tensor需要线detach出来才能转换为numpy

2. data_iter每次读取一个小批量

  • data_iter(batch_size,features,labels)
  • num
  • 打乱下标索引 随机顺序访问样本
  • 每次跳batch_size的大小,如果超出取最后一个
  • yeid每次返回一个x,y

3. 定义 初始化模型参数

  • w正态分布,resuires_gard=True
  • b

4. 定义模型

  • linreg(x,w,b)
  • 线性回归模型
  • return torch.matual(x,w)+b

5. 定义损失函数

def squared_loss(y_hat,y)
    return (y_hat-y.reshape(y_hat.shape))**2/2

6. 定义优化算法

def sgd(params,lr,batch_size)
    with torch.no_grad():
        for param in params:
            param-=lr*param.grad/batch_size
            param.grad.zero_()

7. 训练过程

lr=0.03 # 调整超参数对结果产生的影响
num_epochs=3
net=lireg
loss=squared_loss

for epoch in range(num_epoch)
    for x,y in data_iter(batch_size,features,labels):
        l=loss(net(x,w,b),y) # l (batch_size,1)
        l.sum().backward()
        sgd([w,b],lr,batch_size)
    with torch.no_gard():
        train_l=loss(net(features,w,b),labels)
        printf(f'epoch{
      
      epoch+1},loss{
      
      float(train_l.mean()):f}')

  • 比较真实参数和通过训练学到的参数来评估训练的成功成功程度

猜你喜欢

转载自blog.csdn.net/m0_68312479/article/details/132124419