文章内容如下:
1)构造人造数据集
2)产生batch_size批量数据
3)构造训练模型
4)偏差估计
核心思想,训练的过程是y_hat - y -> 0的过程,训练的本质是找最快方向的梯度使得y_hat - y尽可能快的趋向于0
一。构造人造数据集
第1步,构造人造数据集前需要导入如下模块:
%matplotlib inline
表示 即使未调用plt.show() 函数也可以渲染任何matplotlib 图表
import random
为了随机取出batch_size个数据
import torch
from d2l import torch as d2l
d2l是一些常用的函数,打包放在一起
第2步,
def synthetic_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 = synthetic_data(true_w,true_b,1000)
print('features:',features[0],'\nlabel:',labels[0])
d2l.set_figsize()
d2l.plt.scatter(features[:,1].detach().numpy(),#detach()出来才能numpy()里面去
labels.detach().numpy(),1);
X = torch.normal(0,1,(num_examples,len(w)))表示生成1000组X,每组X均值为0,方差为1,且每组长度为len(w)
y = torch.matmul(X,w)+b表示y=X*W+b
二。产生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)])#最后一组数据可能不够,min(i+batch_size,num_examples)取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
random.shuffle(indices)表示打混indices列表中的元素的顺序,假设最终取出的元素是1,5,2,9,则最终去X中去取第1,5,2,9个元素(yield features[batch_indices],labels[batch_indices]就是做这样的事情),yield表示不停地返回一组又一组数据。
第三步。构造训练模型
// 初始化参数
w = torch.normal(0,0.01,size=(2,1),requires_grad=True)
b = torch.zeros(1,requires_grad=True)#1表示标量
// 线性模型
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*batch_size)
// 参数更新
def sgd(param,lr,batch_size):
with torch.no_grad():
for param in param:
param -= lr *param.grad
param.grad.zero_()
// 训练模型
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)
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}')
可以看到每次epoch后loss逐渐减小,最终很接近0,说明学习率lr的选择没大问题,没有出现震荡现象。