动手学深度学习3.2-从零手动实现线性回归

1,673 阅读2分钟

这是我参与11月更文挑战的第1天,活动详情查看:2021最后一次更文挑战

import random
import torch
from d2l import torch as d2l

d2l这个包是李沐老师团队自己为这个书整的一个配套的package,需要自己下载一下。

# 生成 y = Xw + b + 噪声
def synthetic_data(w, b, num_examples):
    X = torch.normal(0, 1, (num_examples, len(w)))  # torch.normal(means, std, out=None) 
    # num_examples 样本数量
    # len(w) 每组数据特征值的数量要和权重一样多
    y = torch.mv(X, w) + b
    # 加入高斯噪声
    y += torch.normal(0, 0.01, y.shape)
    return X, y.reshape((-1, 1))
    
true_w = torch.tensor([2, -3.4])
true_b = 4.2

features, labels = synthetic_data(true_w, true_b, 1000)
  • 这一步是手动生成一个数据集,因为没现成数据集,所以我们自己造一个y=Xw+by = Xw+b

  • torch.normal(means, std, out=None) 生成服从均值为means,标准差为std的正态分布的随机数张量。

  • y是X*w+b,结果是一维的tensor,使用y.reshape((-1, 1))将其变为二维的tensor。就是从size(m)变为size(m,1),其中m是样本数量。

  • 手动设定真实的W和b,并生成feature和labels即我们观念上的x和y

# 设定mini-batch读取批量的大小
batch_size=10

def data_iter(batch_size, features, labels):
    # 获取y的长度
    num_examples = len(features)
    # 生成对每个样本的index
    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)])
        yield features[batch_indices], labels[batch_indices]

# 随机初始化w,b
w = torch.normal(0, 0.01, size=(2,1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)

# 线性回归模型。
def linear_regression(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):
    with torch.no_grad():
        for param in params:
            param -= lr * param.grad / batch_size
            param.grad.zero_()
  • 这一步就是正常的定义梯度下降过程中用到的东西。应该不用解释。
lr = 0.003
num_epochs = 3
loss = squared_loss
  • 设定learning rate

  • 设定梯度下降步长

  • 给损失起个别名

# epochs即梯度下降要执行多少步
for epoch in range(num_epochs):
    # 每次从generator中取一个mini-batch
    for X, y in data_iter(batch_size, features, labels):
        # 用线性回归计算y的预测值
        y_pred = linear_regression(X, w, b)
        # 计算损失,loss()出来是一个batch大小的向量,需要求和,因为loss是一个数,不理解的看平方损失的公式
        l = loss(y_pred, y).sum()
        # 反向传播
        l.backward()
        # 使用参数的梯度更新参数
        sgd([w, b], lr, batch_size)
        
    with torch.no_grad():
        train_l = loss(linear_regression(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()里边是用每一步下降之后的w和b带回样本整体中看看效果如何。

  • with torch.no_grad()(PyTorch autograd过程解析以及遇到的一些小东西)

  • 最后两句被我注释掉的是看梯度下降最终结果和你手动设定的w和b差多少。