4.5.1. 高维线性回归
代码学习笔记(含详细注释)
通过一个简单的例子来演示权重衰减
4.5.1. 高维线性回归
%matplotlib inline
import torch
from torch import nn
from d2l import torch as d2l
若在pycharm上面用到matplotlib库,可以将上述代码中的:%matplotlib inline
替换为:import matplotlib.pyplot as plt
然后在需要输出图像的地方加上 plt.show()
生成公式如下:
我们选择标签是关于输入的线性函数。 标签同时被均值为0,标准差为0.01高斯噪声破坏。 为了使过拟合的效果更加明显,我们可以将问题的维数增加到d=200, 并使用一个只包含20个样本的小训练集。
n_train, n_test, num_inputs, batch_size = 20, 100, 200, 5
# 赋真实值,true_b=0.05,所有true_w=0.0100
true_w, true_b = torch.ones((num_inputs, 1)) * 0.01, 0.05
# 调用d2l库中的synthetic_data构造一个数据集
# 生成 y=X*true_w+true_b+noise
train_data = d2l.synthetic_data(true_w, true_b, n_train)
# 读取数据 调用d2l库中的一个数据迭代器 每次只选取batch_size规模的数据
train_iter = d2l.load_array(train_data, batch_size)
# 原理同上
test_data = d2l.synthetic_data(true_w, true_b, n_test)
test_iter = d2l.load_array(test_data, batch_size, is_train=False)
4.5.2. 从零开始实现
从头开始实现权重衰减,只需将L2的平方惩罚添加到原始目标函数中。
4.5.2.1. 初始化模型参数
# 初始化模型参数
def init_params():
w = torch.normal(0, 1, size=(num_inputs, 1), requires_grad=True