李沐深度学习——线性回归从零开始实现-代码理解

注释理解
这边有更详尽的代码注释(我只是为了记录一下)
https://blog.csdn.net/lj_FLR/article/details/123760433

import random
import torch
from d2l import torch as d2l
#人造数据集
def synthetic_data(w, b, num_example):
    """生成 y = Xw + b + 噪声"""
    X = torch.normal(0, 1, (num_example, len(w))) #生成均值为0, 方差为1 的随机数,num_example 个样本,列数为 w 的长度
    y = torch.matmul(X, w) + b
    print("y_shape:", y.shape)
    y += torch.normal(0, 0.01, y.shape) # 加入随机噪音
    print("y:", y[0])
    return X, y.reshape((-1, 1))  # y从行向量转为列向量 

true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = synthetic_data(true_w, true_b, 1000)
print("features:", features[0])
print("labels:", labels[0]) # y 等价于 label, X 等价于 features
d2l.set_figsize()  # 以房价为例,label是真实售价,feature是预测标签的因素
d2l.plt.scatter(features[:, 1].detach().numpy(),  # 从计算图中detach出来再转到numpy中去,此处 1 表示第一列的数据,对应 上面-3.4,因为是负数,所以和label呈负相关
               labels.detach().numpy(), 1);  # 最后一个数值 1 表示绘制点直径的大小

在这里插入图片描述

#读数据集
def data_iter(batch_size, features, labels):
    num_examples = len(features)
    indices = list(range(num_examples))
    random.shuffle(indices) #将序列的元素随机打乱
    for i in range(0, num_examples, batch_size):
        batch_indices = torch.tensor(
            indices[i : min(i + batch_size, num_examples)]) #这里取 min(),可能最后的数据不到一个batch_size的长度,
        yield features[batch_indices], labels[batch_indices] #yield 每次不断返回通过 batch_indices 索引取出的数值
        
batch_size = 10

for X, y in data_iter(batch_size, features, labels):
    print("X:",X, '\n y:', y)
    break  #此处 break ,返回一次迭代,即返回一个 batch_size 的数据

在这里插入图片描述

#初始化模型参数
w = torch.normal(0, 0.01, size=(2, 1), requires_grad = True) # requures_grad = True 表明需要计算梯度
b = torch.zeros(1, requires_grad = True) # 偏差 b 直接赋值为 0, 标量
#定义模型
def linreg(X, w, b):
    """线性回归模型"""
    return torch.matmul(X, w) + b 

#定义损失函数
def squared_loss(y_hat, y):
    """均方损失"""
    return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2

#定义优化算法
def sgd(params, lr, batch_size): # param: [w, b], lr 即学习率
    """小批量随机梯度下降(mini-batch stochastic gradient descent)"""
    with torch.no_grad():  #首先定义不要计算梯度,因为我们更新的时候不需要参与梯度计算
        for param in params:
            param -= lr * param.grad / batch_size
            param.grad.zero_() # #接下来把梯度设成0,因为pytorch不会帮你自动梯度设0,这样下一次计算梯度的时候,就不会跟上一次相关了
lr = 0.03
num_epochs = 3
net = linreg
loss = squared_loss

for epoch in range(num_epochs):
    for X, y in data_iter(batch_size,features, labels):
        l = loss(net(X, w, b), y) #因为 l 形状是(batch_size,1),而不是一个标量
        l.sum().backward() #沐神这边说,求导 x.backward() 等价于 x.sum().backward()
        sgd([w,b],lr, batch_size)
    with torch.no_grad():
        train_l = loss(net(features, w, b), labels)
        print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')

print(f'w的估计误差: {true_w - w.reshape(true_w.shape)}')
print(f'b的估计误差: {true_b - b}')

在这里插入图片描述

其实,关于 with torch.no_grad() 和 l.sum().backward() 这两处并不很理解(虽然写了注释),不是很懂sum()的含义,希望后续深入之后加深理解,希望大佬指正。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值