线性回归从0到1实践

导入需要的包

from idlelib.configdialog import tracers
%matplotlib inline
import random
import torch
from d2l import torch as d2l

根据有噪声的线性模型构造一个人造数据集。我们使用线性模型参数 w = [ 2 , − 3 , 4 ] T w = [2,-3,4]^T w=[2,3,4]T、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)
    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.reshape(-1,1) 解释:

  • -1: 让库根据原始数据的大小自动推断这一维的大小,确保数据的总数保持不变。
  • 1: 强制将数组的列数设置为 1。
print("features:",features[0],'\nlabels:',labels[0])
features: tensor([-0.6632, -0.1771]) 
labels: tensor([3.4713])
# 这个不要理会
d2l.set_figsize()
d2l.plt.scatter(features[:,(1)].detach().numpy(),labels.detach().numpy(),1)

在这里插入图片描述

定义一个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]
batch_size = 10

for X,y in data_iter(batch_size,features,labels):
    print(X,"\n",y)
    break
tensor([[-0.7705, -0.1793],
        [ 0.6317,  1.4700],
        [-0.1015, -2.5528],
        [ 2.7295,  0.4477],
        [-0.0854,  1.0438],
        [-0.9627, -0.0421],
        [-2.6444,  0.5648],
        [ 0.2786,  1.0552],
        [-1.2454, -1.7555],
        [-0.8601, -0.8605]]) 
 tensor([[ 3.2769],
        [ 0.4713],
        [12.6764],
        [ 8.1384],
        [ 0.4931],
        [ 2.4080],
        [-3.0041],
        [ 1.1742],
        [ 7.6635],
        [ 5.4063]])
# 定义初始化模型参数
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_()
# 训练过程
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():
        train_1 = loss(net(features,w,b),labels)
        print(f'epoch {epoch+1}, loss {float(train_1.mean()):f}')
epoch 1, loss 0.046590
epoch 2, loss 0.000186
epoch 3, loss 0.000050
# 比较真实参数和通过训练学到的参数来评估训练的成功程度
print(f'w的估计误差: {true_w - w.reshape(true_w.shape)}')
print(f'b的估计误差:{true_b - b}」')
w的估计误差: tensor([ 2.8789e-04, -6.0797e-05], grad_fn=<SubBackward0>)
b的估计误差:tensor([0.0005], grad_fn=<RsubBackward1>)」

Summary

总结一下这一个总的线性回归的一个过程

  1. 准备了一下初始的数据,在这个实验的过程中也就是真实的线性回归的 w,和 b
  2. 然后根据真实的w和b,依靠正态分布生成人造数据,用于进行模型的一个训练
  3. 为数据创造迭代起,就是给数据分成一批一批的,因为如何数据很大,不分成一批一批的话就会很耗费资源(计算梯度的时候,是最耗费资源的,这里也涉及到一个超参数,批大小batch_size)
  4. 定义初始化模型参数,这里为什么要定义成形状是(2,1)的呢,要进行矩阵的乘法进行线性回归模拟,因为数据是 x 是(1000,2)所以 w 得是 (2,1)
  5. 定义模型,就是一个线性回归嘛 y = a x + b y = ax+b y=ax+b 这里的x可以是 x = [ x 1 , x 2 , x 3 … … ] x=[x_1,x_2,x_3……] x=[x1,x2,x3……]
  6. 然后定义了损失函数
  7. 定义了优化函数,也就是随机梯度下降函数,这个函数就是寻找较好的拟合的解,通过求导达到优解。(这里会涉及一个超参数lr学习率,也就是往梯度下降的方向前进的步长,这个不能太大,也不能太小,需要合适的选择)
  8. 然后就是进行多个轮次的训练
  9. 最后得到结果,进行模型结果的评价

模型训练流程:

  1. 数据如何读取
  2. 模型的定义
  3. 参数的初始化
  4. 损失函数
  5. 训练模块
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xwhking

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值