线性回归:使用pytorch框架简洁实现
使用pytorch很够快速定义数据迭代器,损失函数,优化器,和神经网络层,极大的减少代码量和实现难度。
1. 生成数据集
true_w=torch.tensor([2,-3.4])
true_b=4.2
def synthetic_data(w,b,num_examples):
X=torch.normal(0,1,size=(num_examples,len(w)))
y=torch.matmul(X,w)+b
y+=torch.normal(0,0.01,y.shape)
return X,y.reshape((-1,1))
features,lables=synthetic_data(true_w,true_b,1000)
print('features:',features[0],'\n','lables',lables[0])
2. 读取数据集
自定义了load_array函数,能够批量读取数据集,这里使用了data.TensorDataset()将数据封装,再使用data.DataLoader()将数据批量抛出。
def load_array(data_array,batch_size,is_train=True):
dataset=data.TensorDataset(*data_array)
return data.DataLoader(dataset,batch_size,shuffle=is_train)
bath_size=10
data_iter=load_array((features,lables),bath_size)
print(next(iter(data_iter)))
import torch
from torch.utils import data
x=torch.arange(1,13).reshape(3,4)
y=torch.ones(3)
dataset=data.TensorDataset(x,y) # 将x,y封装进dataset
for x,y in dataset:
print('x:',x)
print('y:',y)
3.定义模型
导入torch包的nn工具包,里面的Sequential()能够定义复杂的神经网络,这里的Linear(2,1)是定义一个线性通道,输入2个张量,输出1个张量。
from torch import nn # 导入nn工具包
net=nn.Sequential(nn.Linear(2,1))
4.初始化模型参数
定义了神经网络net后,初始化w和b
# 初始化模型参数
net[0].weight.data.normal_(0,0.01)
net[0].bias.data.fill_(0)
print(net[0])
5. 定义损失函数
nn包中有很多定义好的损失函数,直接调用即可
# 定义损失函数
loss=nn.MSELoss()
6.定义优化算法
定义随机随机梯度下降法SGD,学习率lr.
trainer=torch.optim.SGD(net.parameters(),lr=0.03)
7. 训练
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),lables)
print('epoch:',epoch+1,'\n','loss:',float(l))
print(true_w-net[0].weight)
print(true_b-net[0].bias)
features: tensor([ 1.8632, -1.5988])
lables tensor([13.3648])
[tensor([[-1.3309, -1.0640],
[-1.3686, 0.9578],
[ 1.4033, -0.2112],
[ 0.5657, -0.6395],
[ 0.8588, -1.2384],
[-1.1623, 2.1337],
[ 0.2026, 0.4978],
[-0.7031, 0.3839],
[ 0.1076, -1.0335],
[ 0.3523, 0.2792]]), tensor([[ 5.1573],
[-1.7873],
[ 7.7356],
[ 7.5057],
[10.1277],
[-5.3825],
[ 2.9015],
[ 1.4850],
[ 7.9220],
[ 3.9464]])]
Linear(in_features=2, out_features=1, bias=True)
epoch: 1
loss: 0.00019043585052713752
epoch: 2
loss: 9.712151950225234e-05
epoch: 3
loss: 9.617557225283235e-05
tensor([[-0.0002, 0.0007]], grad_fn=<SubBackward0>)
tensor([-0.0006], grad_fn=<RsubBackward1>)