• 动手学深度学习:1.线性回归从0开始实现



    1.手动构造数据集

    根据带有噪声的线性模型构造一个人造数据集,任务是使用这个有限样本的数据集来恢复这个模型的参数。

    我们使用线性模型参数 w = [ 2 , − 3.4 ] T w = [2,−3.4]^T w=[2,3.4]T b = 4.2 b = 4.2 b=4.2 和噪声项 ϵ \epsilon ϵ 生成数据集及其标签:
    y = X w + b + ϵ y = Xw + b + \epsilon y=Xw+b+ϵ

    def synthetic_data(w, b, num_examples):
        """生成y=Xw+b+噪声"""
        X = torch.normal(0, 1, (num_examples, len(w)))
        y = torch.matmul(X, w) + b
        y += torch.normal(0, 0.01, y.shape) # 加上均值为0,标准差为0.01的噪声
        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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    features中的每一行都包含一个二维数据样本, labels中的每一行都包含一维标签值(一个标量)

    print('features:', features[0],'\nlabel:', labels[0])
    '''
    features: tensor([ 0.2589, -0.6408]) 
    label: tensor([6.8837])
    '''
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.小批量读取数据集

    定义一个函数, 该函数能打乱数据集中的样本并以小批量方式获取数据。下面的``data_iter函数接收批量大小、特征矩阵和标签向量作为输入,生成大小为batch_size`的小批量。 每个小批量包含一组特征和标签。

    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)])
            yield features[batch_indices], labels[batch_indices]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    直观感受一下小批量运算:读取第一个小批量数据样本并打印。 每个批量的特征维度显示批量大小和输入特征数。 同样的,批量的标签形状与batch_size相等。

    batch_size = 10
    
    for X, y in data_iter(batch_size, features, labels):
        print(X, '\n', y)
        break
    
    '''
    tensor([[ 0.9738,  0.9875],
            [-0.8015, -0.2927],
            [ 0.1745,  0.2918],
            [ 1.7484,  0.5768],
            [ 1.1637,  0.6903],
            [ 0.6840,  0.3671],
            [ 0.1465,  0.6662],
            [-1.8122,  0.4852],
            [ 1.0590, -0.0379],
            [-0.9164, -0.4059]]) 
     tensor([[ 2.7853],
            [ 3.5814],
            [ 3.5564],
            [ 5.7416],
            [ 4.1774],
            [ 4.3218],
            [ 2.1962],
            [-1.0674],
            [ 6.4454],
            [ 3.7395]])
    '''
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    3.初始化模型参数

    通过从均值为0、标准差为0.01的正态分布中采样随机数来初始化权重, 并将偏置初始化为0。

    w = torch.normal(0, 0.01, size=(2,1), requires_grad=True)
    b = torch.zeros(1, requires_grad=True)
    
    • 1
    • 2

    在初始化参数之后,我们的任务是更新这些参数,直到这些参数足够拟合我们的数据。 每次更新都需要计算损失函数关于模型参数的梯度。 有了这个梯度,我们就可以向减小损失的方向更新每个参数。

    4.定义模型和损失函数

    我们必须定义模型,将模型的输入和参数同模型的输出关联起来。要计算线性模型的输出, 我们只需计算输入特征 X X X 和模型权重 w w w 的矩阵-向量乘法后加上偏置 b b b。注意,上面的 X w Xw Xw 是一个向量,而 b b b 是一个标量,由于广播机制: 当我们用一个向量加一个标量时,标量会被加到向量的每个分量上。

    def linreg(X, w, b):
        """线性回归模型"""
        return torch.matmul(X, w) + b
    
    • 1
    • 2
    • 3

    因为需要计算损失函数的梯度,所以我们应该先定义损失函数。这里使用平方损失函数。

    def squared_loss(y_hat, y): 
        """均方损失"""
        return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2
    
    • 1
    • 2
    • 3

    5.小批量随机梯度下降更新

    小批量随机梯度下降在每一步中,使用从数据集中随机抽取的一个小批量,然后根据参数计算损失的梯度。接下来,朝着减少损失的方向更新我们的参数。

    下面的函数实现小批量随机梯度下降更新。 该函数接受模型参数集合、学习速率和批量大小作为输入。

    因为我们计算的损失是一个批量样本的总和,所以我们用批量大小(batch_size) 来规范化步长,这样步长大小就不会取决于我们对批量大小的选择。

    def sgd(params, lr, batch_size):
        """小批量随机梯度下降"""
        with torch.no_grad():
            for param in params: # [w,b]
                param -= lr * param.grad / batch_size
                param.grad.zero_()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    6.训练

    在每次迭代中,我们读取一小批量训练样本,并通过我们的模型来获得一组预测。 计算完损失后,我们开始反向传播,存储每个参数的梯度。 最后,我们调用优化算法sgd来更新模型参数。

    在每个迭代周期(epoch)中,我们使用data_iter函数遍历整个数据集, 并将训练数据集中所有样本都使用一次(假设样本数能够被批量大小整除)。 这里的迭代周期个数num_epochs和学习率lr都是超参数,分别设为3和0.03。

    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)  # X和y小批量损失
            # 因为l形状是(batch_size,1),而不是一个标量。l中的所有元素被加到一起,
            # 并以此计算关于[w,b]的梯度
            l.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}')
    
    '''
    epoch 1, loss 0.039035
    epoch 2, loss 0.000149
    epoch 3, loss 0.000050
    '''
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

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

    print(f'w的估计误差: {true_w - w.reshape(true_w.shape)}')
    print(f'b的估计误差: {true_b - b}')
    '''
    w的估计误差: tensor([ 0.0006, -0.0011], grad_fn=)
    b的估计误差: tensor([0.0007], grad_fn=)
    '''
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    完整代码

    import random
    import torch
    
    
    # 1.人为构造数据集
    def synthetic_data(w, b, num_examples):
        """生成y=Xw+b+噪声"""
        X = torch.normal(0, 1, (num_examples, len(w)))
        y = torch.matmul(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)
    print('features:', features[0], '\nlabel:', labels[0])
    
    
    # 2.读取数据集
    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)])
            yield features[batch_indices], labels[batch_indices]
    
    
    batch_size = 10
    for X, y in data_iter(batch_size, features, labels):
        print(X, '\n', y)
        break
    
    # 3.初始化权重和偏置
    w = torch.normal(0, 0.01, size=(2, 1), requires_grad=True)
    b = torch.zeros(1, requires_grad=True)
    
    
    # 4.定义模型定义模型和模型
    def linreg(X, w, b):
        """线性回归模型"""
        return torch.matmul(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 = 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)  # X和y小批量损失
            # 因为l形状是(batch_size,1),而不是一个标量。l中的所有元素被加到一起,
            # 并以此计算关于[w,b]的梯度
            l.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}')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
  • 相关阅读:
    软件开发项目文档系列之十五如何撰写项目结项报告
    hadoop3.x入门到精通-阶段六(深入Hadoop源码达到定制化阶段)
    傻瓜式制作产品图册,一秒就能学会
    (刘二大人)PyTorch深度学习实践-卷积网络(Residual)
    python连接带用户认证mongo,,并进行查询操作
    1-前端基本知识-HTML
    基于蝴蝶优化的BP神经网络(分类应用) - 附代码
    【IPC 通信】信号处理接口 Signal API(2)
    机器人阻抗与导纳控制的区别
    记一次 .NET 某企业采购平台 崩溃分析
  • 原文地址:https://blog.csdn.net/ArthurHai521/article/details/134218571