一、线性模型
线性模型:可以看做是单层的神经网络

衡量指标:

参数学习:
总结:

二、优化算法
1、梯度下降

(1)小批量随机提取下降


三、线性回归从零开始实现
1、人工构造数据
#从零实现整个方法,包括数据流水线、模型、损失函数和小批量随机梯度下降优化器
%matplotlib inline
import random
import torch
#根据带有噪声的线性模型构造一个人造数据集。我们是用线性模型参数 W = [2, -3,4]T,b=4.2和噪声项θ生成数据集及其标签
#用 y = Xw + b + θ
def synthetic_data(w, b, num_examples):
"""生成y = y = Xw + b + 噪声"""
x = torch.normal(0, 1, (num_examples, len(w))) #均值为0,方差为1的随机数
y = torch.matmul(x, w) + b #matmul == mm,维度大于1的张量乘法运算
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)
查看数据
#features中的每一行都包含一个二维数据样本,labels中的每一行都包含一维标签值(一个标量)
print('features: ', features[0], '\nlabel:', labels[0])
#draw figure
from matplotlib import pyplot as plt
plt.scatter(features[:, 1].detach().numpy(), labels.detach().numpy(), 1)

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:每一次都返回一组值
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_grad=True)
b = torch.zeros(1, requires_grad=True)
#定义模型
def linreg(x, w, b):
return torch.matmul(x,w) + b
#定义损失函数,y_hat预测值,y真实值
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_()
4、训练过程
#训练过程
lr = 0.01
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_l = loss(net(features, w, b), labels)
#f表示格式化字符串,加f后可以在字符串里面使用用花括号括起来的变量和表达式,如果字符串里面没有表达式,那么前面加不加f输出应该都一样
print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')

5、训练评估
#比较真实参数和通过训练学习到的参数来评估训练的成功程度
print(f'w的误差为:{true_w - w.reshape(true_w.shape)}')
print(f'b的误差为:{true_b - b}')

四、Pytorch框架实现版
from matplotlib import pyplot as plt
import numpy as np
import torch
from torch.utils import data #处理数据的模块
#根据带有噪声的线性模型构造一个人造数据集。我们是用线性模型参数 W = [2, -3,4]T,b=4.2和噪声项θ生成数据集及其标签
#用 y = Xw + b + θ
def synthetic_data(w, b, num_examples):
"""生成y = y = Xw + b + 噪声"""
x = torch.normal(0, 1, (num_examples, len(w))) #均值为0,方差为1的随机数
y = torch.matmul(x, w) + b #matmul == mm,维度大于1的张量乘法运算
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)
#调用现有的API来读取数据
def load_array(data_arrays, batch_size, is_train=True):
"""构造一个PyTorch的数据迭代器"""
dataset = data.TensorDataset(*data_arrays)
return data.DataLoader(dataset, batch_size, shuffle=is_train)
batch_size = 2
data_iter = load_array((features, labels), batch_size)
next(iter(data_iter)) #通过next函数得到x和y
#模型定义
from torch import nn #nn是神经网络的缩写
net = nn.Sequential(nn.Linear(2,1)) #输入维度为2, 输出维度为1
#初始化模型参数
net[0].weight.data.normal_(0, 0.01) #用均值为0,方差为0.01的随机数替换原来的w
net[0].bias.data.fill_(0) #用0填充偏差
#计算均方误差 MSELoss类,也称为平方L2范数
loss = nn.MSELoss()
#实例化SGD
trainer = torch.optim.SGD(net.parameters(), lr=0.03)
#训练模块
num_epochs = 3
for epoch in range(num_epochs):
for x, y in data_iter:
l = loss(net(x), y)
trainer.zero_grad()
l.backward()
trainer.step() #step函数来进行一次模型的更新
l = loss(net(features), labels)
print(f'epoch {epoch+1}, loss {l:f}')