Pytorch学习笔记

非线性回归问题的参数求解,反向求导基本流程。Variable 计算时, 它在后台一步步默默地搭建着一个庞大的系统, 叫做计算图, computational graph. 这个图将所有的计算步骤 (节点) 都连接起来, 最后进行误差反向传递的时候, 一次性将所有 variable 里面的修改幅度 (梯度) 都计算出来, 而 tensor 就没有这个能力。

 1 from torch.autograd import Variable
 2 dtype = torch.FloatTensor
 3 N, D_in, H, D_out = 64, 1000, 100, 10
 4 x = Variable(torch.randn(N, D_in).type(dtype), requires_grad=False)
 5 y = Variable(torch.randn(N, D_out).type(dtype), requires_grad=False)
 6 w1 = Variable(torch.randn(D_in, H).type(dtype), requires_grad=True)
 7 w2 = Variable(torch.randn(H, D_out).type(dtype), requires_grad=True)
 8 learning_rate = 1e-6
 9 for t in range(500):
10     y_pred = x.mm(w1).clamp(min=0).mm(w2)
11     loss = (y_pred - y).pow(2).sum()
12     print(t, loss.data[0])
13     # Manually zero the gradients before running the backward pass
14     if t > 0:
15         w1.grad.data.zero_()
16         w2.grad.data.zero_()
17     loss.backward()
18     w1.data -= learning_rate * w1.grad.data
19     w2.data -= learning_rate * w2.grad.data