当前位置: 代码迷 >> 综合 >> Pytorch学习(二)--用Variable实现线性回归
  详细解决方案

Pytorch学习(二)--用Variable实现线性回归

热度:20   发布时间:2023-09-24 05:05:03.0

Pytorch学习系列(一)至(四)均摘自《深度学习框架PyTorch入门与实践》陈云

与上一篇不同,上一篇采用手动求导的方式计算梯度。本篇采用autograd中的Variable进行自动求导。

#------------------------------------------------------------------------------------------------
#-------------------用variables实现线性回归----------------------------------------
#-------------------------------------------------------------------------------------------------
import torch as t
from torch.autograd import Variable as V
from matplotlib import pyplot as plt
from IPython import displayt.manual_seed(1000)def get_fake_data(batch_size=8):x=t.rand(batch_size,1)*20y=x*2+(1+t.randn(batch_size,1))*3return x,yx,y=get_fake_data()
plt.scatter(x.squeeze().numpy(),y.squeeze().numpy())w=V(t.rand(1,1),requires_grad=True)
b=V(t.zeros(1,1),requires_grad=True)
#w=t.rand(1,1)
#b=t.zeros(1,1)
lr=0.001for ii in range(8000):x,y=get_fake_data()x,y=V(x),V(y)y_pred=x.mm(w)+b.expand_as(y)loss=0.5*(y_pred-y)**2loss=loss.sum()loss.backward()w.data.sub_(lr*w.grad.data)b.data.sub_(lr*b.grad.data)w.grad.data.zero_()b.grad.data.zero_()if ii%1000==0:display.clear_output(wait=True)x=t.arange(0,20).view(-1,1)y=x.mm(w.data)+b.data.expand_as(x)plt.plot(x.numpy(),y.numpy())x2,y2=get_fake_data(batch_size=20)plt.scatter(x2.numpy(),y2.numpy())plt.xlim(0,20)plt.ylim(0,41)plt.show()plt.pause(0.5)print(w.squeeze()[0],b.squeeze()[0])


将本篇与上一篇做一个简单的对比,本篇为实现自动求导,在产生了数据之后,就将数据转换为了Variable类型,使用V类型计算目标函数以及损失函数,再由autograd中的backward方法,进行反向传播,得到梯度。

进行梯度更新时,也体现了Variable类型数据的结构特性。Variable中有data,grad。其中grad也是variable,所以有

 w.data.sub_(lr*w.grad.data)

  相关解决方案