跟李沐学AI--线性回归的代码实现

先说一些简单的知识点:

1. 线性回归:自变量x和因变量y之间的关系是线性的,其模型可表示为:y=wx+b。对于具体的求解线性回归问题,其目的是给定一个数据集,根据x和y的值求解最接近的模型权重w和偏置项b。

2. 损失函数:量化目标的实际值和预测值之间的差距。在线性回归问题上,可以计算预测值\hat{y}和真实的y之间的差距,从而度量模型的质量。例如,均方损失的表达式如下:

L(w,b)=\tfrac{1}{n}\sum_{i=1}^{n} \frac{1}{2}(wx^{i}+b-y^{i})^{2}

3. 求解:线性回归的求解问题就是求损失L(w,b)最小的问题。

4. 随机梯度下降:计算损失函数关于参数的导数(也叫梯度),沿着梯度的负方向更新该参数。(公式不想打了,在这个编辑器里打公式真的好难受啊~~~~)

废话不多说,上代码:

import random
import torch
from d2l import torch as d2l


# ***************************************** 构造数据集 ***************************************
def synthetic_data(w, b, num_examples):
    """生成y=wx+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))


# **************************************** 读取数据集 *******************************************
def data_iter(batch_size, features, labels):
    num_example = len(features)
    indices = list(range(num_example))
    random.shuffle(indices)   # 打乱顺序,随机读取
    for i in range(0, num_example, batch_size):
        batch_indices = torch.tensor(indices[i:min(i + batch_size, num_example)])
        yield features[batch_indices], labels[batch_indices]


# *************************************** 初始化模型参数 *********************************************
w = torch.normal(0, 0.01, size=(2, 1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)


# *************************************** 定义模型 ***************************************************
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):
    with torch.no_grad():
        for param in params:
            param -= lr * param.grad / batch_size
            param.grad.zero_()


# *************************************** 训练 *******************************************************
def train():
    true_w = torch.tensor([2, -3.4])
    true_b = 4.2
    features, labels = synthetic_data(true_w, true_b, 1000)

    batch_size = 10
    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.sum().backward()                           # 对小批量损失求和
            sgd([w, b], lr, batch_size)                  # 更新梯度
        with torch.no_grad():   # 在该模块下,所有计算得出的tensor的requires_grad都自动设置为False,可以节约内存
            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}')


if __name__ == "__main__":
    train()

以上是通过代码手动实现线性回归,还可以在torch框架中简洁实现以上回归,代码如下:

import torch
from torch import nn
from torch.utils import data
from d2l import torch as d2l


def load_array(data_arrays, batch_size, is_train=True):
    dataset = data.TensorDataset(*data_arrays)
    return data.DataLoader(dataset, batch_size, shuffle=is_train)


def train():
    true_w = torch.tensor([2, -3.4])
    true_b = 4.2  
    features, labels = d2l.synthetic_data(true_w, true_b, 1000)  # 生成数据集

    batch_size = 10
    data_iter = load_array((features, labels), batch_size)   # 读取数据集
    # next(iter(data_iter))
    net = nn.Sequential(nn.Linear(2, 1))   # 定义网络
    # 初始化模型参数
    net[0].weight.data.normal_(0, 0.01)    
    net[0].bias.data.fill_(0)

    loss = nn.MSELoss()    # 定义损失函数:均方损失
    trainer = torch.optim.SGD(net.parameters(), lr=0.03)     # 定义优化算法:随机梯度下降
    num_epochs = 3
    for epoch in range(num_epochs):
        for x, y in data_iter:    # 读取小批量数据集
            l = loss(net(x), y)   # 计算损失
            trainer.zero_grad()   # 梯度归零
            l.backward()          # 反向传播计算梯度
            trainer.step()        # 用优化器更新模型参数
        l = loss(net(features), labels)  
        print(f'epoch {epoch + 1}, loss{l:f}')

    w = net[0].weight.data
    b = net[0].bias.data
    print(f'w的估计误差:{true_w - w.reshape(true_w.shape)}')
    print(f'b的估计误差:{true_b - b}')


if __name__ == "__main__":
    train()

运行两种方法,均会得到如下形式的结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值