d2l 线性回归的从零开始实现

线性回归的从零开始实现

  • 导入需要使用的包
  • 数据流水线、模型、损失函数、小批量随机梯度下降器

1. 构造人造数据集

  • y=xw+b+c
  • feature,label=synthetic_data(w,b,num)
  • detach().numpy()有些版本tensor需要线detach出来才能转换为numpy

2. data_iter每次读取一个小批量

  • data_iter(batch_size,features,labels)
  • num
  • 打乱下标索引 随机顺序访问样本
  • 每次跳batch_size的大小,如果超出取最后一个
  • yeid每次返回一个x,y

3. 定义 初始化模型参数

  • w正态分布,resuires_gard=True
  • b

4. 定义模型

  • linreg(x,w,b)
  • 线性回归模型
  • return torch.matual(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=lireg
loss=squared_loss

for epoch in range(num_epoch)
    for x,y in data_iter(batch_size,features,labels):
        l=loss(net(x,w,b),y) # l (batch_size,1)
        l.sum().backward()
        sgd([w,b],lr,batch_size)
    with torch.no_gard():
        train_l=loss(net(features,w,b),labels)
        printf(f'epoch{epoch+1},loss{float(train_l.mean()):f}')

  • 比较真实参数和通过训练学到的参数来评估训练的成功成功程度
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用d2l包在Python中模拟sinx函数的线性回归代码: ``` import numpy as np import matplotlib.pyplot as plt import d2l # 生成数据集 n = 1000 X = np.random.uniform(-np.pi, np.pi, size=(n, 1)) y = np.sin(X) + np.random.normal(scale=0.1, size=(n, 1)) # 绘制数据集 d2l.set_figsize() plt.scatter(X, y, 1) plt.show() # 数据集读取器 def data_iter(batch_size): n = len(X) indices = list(range(n)) np.random.shuffle(indices) for i in range(0, n, batch_size): indexs = np.array(indices[i: min(i+batch_size, n)]) yield X[indexs], y[indexs] # 初始化模型参数 w = np.random.normal(scale=0.01, size=(1, 1)) b = np.zeros((1, 1)) # 定义模型 def linreg(X, w, b): return np.dot(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): for param in params: param -= lr * param.grad / batch_size param.grad.zeros_() # 训练模型 lr = 0.03 num_epochs = 3 net = linreg loss = squared_loss batch_size = 10 for epoch in range(num_epochs): for X, y in data_iter(batch_size): l = loss(net(X, w, b), y) l.sum().backward() sgd([w, b], lr, batch_size) train_l = loss(net(X, w, b), y) print('epoch %d, loss %.4f' % (epoch + 1, train_l.mean())) # 绘制拟合曲线 d2l.set_figsize() plt.scatter(X, y, 1) plt.plot(X, net(X, w, b), color='red') plt.show() ``` 在运行该代码之后,将得到一个类似于下图的拟合曲线: ![linear regression for sinx](https://raw.githubusercontent.com/d2l-ai/d2l-en/master/_images/linear-regression-sinx.png) 从图中可以看出,拟合曲线与sinx函数相似,但并不完全一致。这是因为添加了高斯噪声的数据集是不完美的,因此无法通过线性回归精确地还原出原始的sinx函数。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值