免费网站登录口看完你会感谢我,学校网站怎么做的好,网站修改关键词不收录,怎么建设境外网站动手学深度学习#xff1a;1.线性回归从0开始实现 1.手动构造数据集2.小批量读取数据集3.初始化模型参数4.定义模型和损失函数5.小批量随机梯度下降更新6.训练完整代码 1.手动构造数据集
根据带有噪声的线性模型构造一个人造数据集#xff0c;任务是使用这个有限样本的数据集… 动手学深度学习1.线性回归从0开始实现 1.手动构造数据集2.小批量读取数据集3.初始化模型参数4.定义模型和损失函数5.小批量随机梯度下降更新6.训练完整代码 1.手动构造数据集
根据带有噪声的线性模型构造一个人造数据集任务是使用这个有限样本的数据集来恢复这个模型的参数。
我们使用线性模型参数 w [ 2 , − 3.4 ] T w [2,−3.4]^T w[2,−3.4]T b 4.2 b 4.2 b4.2 和噪声项 ϵ \epsilon ϵ 生成数据集及其标签 y X w b ϵ y Xw b \epsilon yXwbϵ
def synthetic_data(w, b, num_examples):生成yXwb噪声X torch.normal(0, 1, (num_examples, len(w)))y torch.matmul(X, w) by 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)features中的每一行都包含一个二维数据样本 labels中的每一行都包含一维标签值一个标量
print(features:, features[0],\nlabel:, labels[0])features: tensor([ 0.2589, -0.6408])
label: tensor([6.8837])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]直观感受一下小批量运算读取第一个小批量数据样本并打印。 每个批量的特征维度显示批量大小和输入特征数。 同样的批量的标签形状与batch_size相等。
batch_size 10for 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]])3.初始化模型参数
通过从均值为0、标准差为0.01的正态分布中采样随机数来初始化权重 并将偏置初始化为0。
w torch.normal(0, 0.01, size(2,1), requires_gradTrue)
b torch.zeros(1, requires_gradTrue)在初始化参数之后我们的任务是更新这些参数直到这些参数足够拟合我们的数据。 每次更新都需要计算损失函数关于模型参数的梯度。 有了这个梯度我们就可以向减小损失的方向更新每个参数。
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因为需要计算损失函数的梯度所以我们应该先定义损失函数。这里使用平方损失函数。
def squared_loss(y_hat, y): 均方损失return (y_hat - y.reshape(y_hat.shape)) ** 2 / 25.小批量随机梯度下降更新
小批量随机梯度下降在每一步中使用从数据集中随机抽取的一个小批量然后根据参数计算损失的梯度。接下来朝着减少损失的方向更新我们的参数。
下面的函数实现小批量随机梯度下降更新。 该函数接受模型参数集合、学习速率和批量大小作为输入。
因为我们计算的损失是一个批量样本的总和所以我们用批量大小batch_size 来规范化步长这样步长大小就不会取决于我们对批量大小的选择。
def sgd(params, lr, batch_size):小批量随机梯度下降with torch.no_grad():for param in params: # [w,b]param - lr * param.grad / batch_sizeparam.grad.zero_()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(fepoch {epoch 1}, loss {float(train_l.mean()):f})
epoch 1, loss 0.039035
epoch 2, loss 0.000149
epoch 3, loss 0.000050通过比较真实参数和通过训练学到的参数来评估训练的成功程度
print(fw的估计误差: {true_w - w.reshape(true_w.shape)})
print(fb的估计误差: {true_b - b})w的估计误差: tensor([ 0.0006, -0.0011], grad_fnSubBackward0)
b的估计误差: tensor([0.0007], grad_fnRsubBackward1)完整代码
import random
import torch# 1.人为构造数据集
def synthetic_data(w, b, num_examples):生成yXwb噪声X torch.normal(0, 1, (num_examples, len(w)))y torch.matmul(X, w) by 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_gradTrue)
b torch.zeros(1, requires_gradTrue)# 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_sizeparam.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(fepoch {epoch 1}, loss {float(train_l.mean()):f})print(fw的估计误差: {true_w - w.reshape(true_w.shape)})
print(fb的估计误差: {true_b - b})