线性回归-pytorch
方式1-自构造
%matplotlib inline
import random
import torch
from d2l import torch as d2l
根据带有噪声的线性模型构造一个人造数据集,我们使用线性模型参数w =[2,-3.4].T、b=4.2和噪声向e生成数据集及其标签:y = Xw+b+e
def synthetic_data(w,b,num_examples):
X = torch.normal(0,1,(num_examples,len(w)))
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])
features: tensor([ 1.2775, -0.2630])
label: tensor([7.6531])
d2l库 可换成matplotlib库
d2l.set_figsize()
d2l.plt.scatter(features[:,1].detach().numpy(),labels.detach().numpy(),1) #detach出来才能转到numpy里面去
定义一个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] #产生随机index的特征和标号
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 linereg(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 #y.reshape(y_hat.shape)) y reshape 成 y_hat 的 shape
定义优化算法
def sgd(params,lr,batch_size):
'''小批量sgd'''
with torch.no_grad():
for param in params:
param -= lr*param.grad / batch_size
param.grad.zero_() #手动梯度置为0,防止下一次计算的梯度与上一次计算的梯度相关
训练
lr = 0.01
num_epochs = 10
net = linereg
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.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}')
方式2-调torch.nn
import numpy as np
import torch
from torch.utils import data
from d2l import torch as d2l
ture_w = torch.tensor([2,-3.4])
ture_b = 4.2
features, labels = d2l.synthetic_data(ture_w,ture_b,10000)
构造数据迭代器
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 = 10
data_iter = load_array((features,labels),batch_size)
next = (iter(data_iter))
回归网络 (回归相当于单层全连接网络)
from torch import nn
net = nn.Sequential(nn.Linear(2,1))
net[0].weight.data.normal_(0,0.01) #normal_ 用正态分布替换data的值
net[0].bias.data.fill_(0)
MSE损失
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()
l = loss(net(features),labels)
print(f'epoch {epoch + 1},loss {float(train_l.mean()):f}')