基本公式:
y
=
(
w
,
x
)
+
b
y=(w,x)+b
y=(w,x)+b ,其中b是偏差,w是加权和,x是关键因素。可以看作单层的神经网络,仅有输入层和输出层。
平方损失:
l
(
y
,
y
)
=
12
(
y
−
y
)
2
l(y,y^)=12(y−y^)2
l(y,y)=12(y−y)2 ,用于衡量真实值和估计值。
参数学习:
训练损失:
l
(
X
,
y
,
w
,
b
)
=
12
n
∑
i
=
1
n
(
y
i
−
(
x
i
,
w
)
−
b
)
2
=
12
n
‖
y
−
X
w
−
b
‖
2
l(X,y,w,b)=12n∑i=1n(yi−(xi,w)−b)2=12n‖y−Xw−b‖2
l(X,y,w,b)=12n∑i=1n(yi−(xi,w)−b)2=12n‖y−Xw−b‖2
通过最小化损失来学习参数,找到合适的w和b。
优化方式:
通过梯度优化来优化,选择合适的学习率。使用小批量随机梯度下降,随机采样b个样本来近似损失,b是批量大小。重要的超参数就是批量大小和学习率。
实现:
import random
import torch
from d2l import torch as d2l
# 构造一个人造数据集
def synthesic_data(w, b, num_examples):
X = torch.normal(0, 1, (num_examples, len(w)))# 均值为0,方差为1
y = torch.matmul(X, w) + b
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 = synthesic_data(true_w, true_b, 1000)# 得到训练样本
def data_iter(batch_size, features, labels):
num_examples = len(features)
indices = list(range(num_examples))#生成list下标
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]# 类似于return
batch_size = 10
for X,y in data_iter(batch_size, features,labels):
print(X, '\n', y)
break
# 初始化模型参数
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
#定义损失函数
def squared_loss(y_hat, y):
return (y_hat - y.reshape(y_hat.shape))** 2 / 2 # 平方除2
# 定义优化算法
def sgd(params, lr, batch_size): # params里包含了w和b
with torch.no_grad():# 更新时不用梯度
for param in params:
param -= lr * param.grad / batch_size# 学习率乘梯度,求个均值
param.grad.zero_()# 梯度归零
lr = 0.03
num_epoch = 3
net = linreg
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.sum().backward()
sgd([w, b], lr, batch_size)
with torch.no_grad():
train_l = loss(net(features, w, b), labels)
print(f'epoch{epoch + 1}, loss{float(train_l.mean()):f}')