3.1线性回归
矢量计算表达式
import torch
a = torch.ones(1000)
b = torch.ones(1000)
c = torch.zeros(1000)
for i in range(1000):
c[i] = a[i] + b[i]
d = a + b
a = torch.ones(3)
b = 10
print(a+b)
3.2线性回归的从零开始实现
%matplotlib inline
import torch
from IPython import display
from matplotlib import pyplot as plt
import numpy as np
import random
print(torch.__version__)
我们构造一个简单的人工数据集,样本数为1000,输入特征数为2,
我们使用回归模型的真实权重w=[2,-3,4]转置,和偏差b=4.2,以及一个随机噪声生成标签
num_inputs = 2
num_examples = 1000
truew_w = [2, -3.4]
true_b = 4.2
features = torch.from_numpy(np.random.normal(0, 1, (num_examples, num_inputs)))
labels = truew_w[0] * features[:, 0] + truew_w[1] * features[:, 1] + true_b
labels+=torch.from_numpy(np.random.normal(0,0.01,size = labels.size())) # 加噪音
feature是一个每一行长度为2的向量,labels的每一行是一个长度为1的向量
print(features[0],labels[0])
# 这两个函数已经保留在d2lzh包中方便以后使用
def use_svg_display():
# 用矢量图显示
display.set_matplotlib_formats('svg')
def set_figsize(figsize=(3.5, 2.5)):
use_svg_display()
# 设置图的尺寸
plt.rcParams['figure.figsize'] = figsize
# # 在../d2lzh_pytorch里面添加上面两个函数后就可以这样导入
# import sys
# sys.path.append("..")
# from d2lzh_pytorch import *
set_figsize()
plt.scatter(features[:, 1].numpy(), labels.numpy(),1)
plt.scatter(features[:, 1].numpy(), labels.numpy())
读取数据
在训练模型的时候,我们需要遍历数据集并不断读取小批量的数据样本,这里我们定义一个函数,它每次返回batch_size(批量大小)个随机的特征和标签
# 本函数已经保留在d2lzh包中方便以后使用
def data_iter(batch_size,features,labels):
num_examples = len(features)
indices = list(range(num_examples))
for i in range(0,num_examples,batch_size):
j = torch.LongTensor(indices[i:min(i+batch_size,num_examples)]) #最后一次可能不足一个batch
yield features.index_select(0,j),labels.index_select(0,j)
#yield的含义和return差不多,只不过返回的是一个生成器
#torch.index_select(x, 0, indices) 第二个参数0是按照行筛选
#读取一个小批量数据集
batch_size = 10
for X, y in data_iter(batch_size, features=features, labels=labels):
print(X, '\n', y)
break
初始化模型参数
- 我们将权重初始化为均值为0,标准差为0.01的正太随机数,偏差初始化为0
w = torch.tensor(np.random.normal(0,0.01,(num_inputs,1 )),dtype = torch.double)
b = torch.zeros(1,dtype = torch.double)
w = torch.tensor(np.random.normal(0, 0.01, (num_inputs, 1)), dtype=torch.double)
b = torch.zeros(1, dtype=torch.double)
w.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)
定义模型
- 下面是线性回归矢量计算表达式的实现,我们使用mm()函数做矩阵乘法
# 本函数已保存在d2lzh包中方便以后使用
def linreg(X, w, b):
return torch.mm(X, w) + b
定义损失函数
- 使用平方损失函数
def squared_loss(y_hat, y): # 本函数已保存在pytorch_d2lzh包中方便以后使用
# 这里返回的是向量,并且pytorch里的MSEloss并没有除以 2
return (y_hat - y.view(y_hat.size())) ** 2 / 2
定义优化算法
下面的sgd函数实现了上一节中介绍的小批量随机梯度下降算法,它通过不断迭代模型参数来优化损失函数
- 这里自动求得的梯度是批量样本的梯度和,我们将它除以批量大小得到平均值
def sgd(params, lr, batch_size): # 本函数已保存在d2lzh_pytorch包中方便以后使用
for param in params:
param.data -= lr * param.grad / batch_size # 这里更改param时用的param.data
训练模型
- 在训练中,我们将多次迭代模型参数
- 通过求得随机梯度并调用sgd算法迭代模型参数
- 注意在每次更新完参数后,不要忘了将参数的梯度清零
- 在一个迭代周期(epoch)中,我们就完整遍历一遍data_iter函数,并对训练数据集中的所有样本都使用一次
- 这里的迭代周期个数num_epoch和学习率lr都是超参数,在实践中,大多数超参数都得通过反复试错来不断调试
print('hello world')
import torch
from torch.autograd import Variable
lr = 0.03
num_epochs = 5
net = linreg
loss = squared_loss
# training
for epoch in range(num_epochs): # training repeats num_epochs times
# in each epoch, all the samples in dataset will be used once
# X is the feature and y is the label of a batch sample
for X, y in data_iter(batch_size, features, labels):
l = loss(net(X, w, b), y).sum()
# calculate the gradient of batch sample loss
l.backward()
# using small batch random gradient descent to iter model parameters
sgd([w, b], lr, batch_size)
# reset parameter gradient
w.grad.data.zero_()
b.grad.data.zero_()
train_l = loss(net(features, w, b), labels)
print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))
lr = 0.03
num_epochs = 3
net = linreg
loss = squared_loss
for epoch in range(num_epochs): # 训练模型一共需要num_epochs个迭代周期
# 在每一个迭代周期中,会使用训练数据集中所有样本一次(假设样本数能够被批量大小整除)。X
# 和y分别是小批量样本的特征和标签
for X, y in data_iter(batch_size, features, labels):
l = loss(net(X, w, b), y).sum() # l是有关小批量X和y的损失
l=Variable(l,requires_grad=True)
#l=torch.tensor(l,requires_grad=True) #生成变量
l.backward() # 小批量的损失对模型参数求梯度
sgd([w, b], lr, batch_size) # 使用小批量随机梯度下降迭代模型参数
# 不要忘了梯度清零
w.grad.data.zero_()
b.grad.data.zero_()
train_l = loss(net(features, w, b), labels)
print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))
print(true_w, '\n', w)
print(true_b, '\n', b)
线性回归的简洁实现
生成数据集
import torch
from torch import nn #'nn'是neural networks(神经网络)的缩写
import numpy as np
torch.manual_seed(1)
print(torch.__version__)
torch.set_default_tensor_type('torch.FloatTensor')
num_inputs = 2
num_examples = 1000
true_w = [2, -3.4]
true_b = 4.2
features = torch.tensor(np.random.normal(0, 1, (num_examples, num_inputs)), dtype=torch.float)
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)
读取数据
import torch.utils.data as Data
batch_size = 10
# 将训练数据的特征和标签组合
dataset = Data.TensorDataset(features, labels)
# 把 dataset 放入 DataLoader
# 这里的data_iter的使用和上一节中的一样,让我们读取并打印第一个小批量数据样本
data_iter = Data.DataLoader(
dataset=dataset, # torch TensorDataset format
batch_size=batch_size, # mini batch size
shuffle=True, # 要不要打乱数据 (打乱比较好)
num_workers=2, # 多线程来读数据
)
for X, y in data_iter:
print(X, '\n', y)
break
定义模型
- torch.nn模块定义啦大量神经网络的层,并且nn就是利用autograd来定义模型的
- nn的核心数据结构是Module,它是一个抽象的概念,既可以表示神经网络中的某个层,也可以表示一个包含很多层的神经网络
- 实际应用中,最常见的做法是继承nn.Module,撰写自己的网络/层
- 一个nn.Module实例应该包含一