利用autograd/Variable實現線性迴歸,體會autograd的便捷之處。
from __future__ import print_function
import torch as t
from torch.autograd import Variable as V
from torch.autograd import Function
from matplotlib import pyplot as plt
from IPython import display
# 爲了在不同的計算機上運行時下面的輸出一致,設置隨機數種子
t.manual_seed(1000)
def get_fake_data(batch_size=8):
# 產生隨機數據:y = x * 2 + 3,加上了一些噪聲
x = t.rand(batch_size, 1) * 20
y = x * 2 + (1 + t.randn(batch_size, 1)) * 3
return x, y
# 來看看產生的x-y分佈是什麼樣的
x, y = get_fake_data()
plt.scatter(x.squeeze().numpy(), y.squeeze().numpy())
plt.show()
# 隨機初始化參數
w = V(t.rand(1, 1), requires_grad=True)
b = V(t.zeros(1, 1), requires_grad=True)
# 學習率
lr = 0.001
for ii in range(8000):
x, y = get_fake_data()
x, y = V(x), V(y)
# forward:計算loss
y_pred = x.mm(w) + b.expand_as(y)
loss = 0.5 * (y_pred - y) ** 2
loss = loss.sum()
# backward:自動計算梯度
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.long()) + b.data.expand_as(x)
# predicted
plt.plot(x.numpy(), y.numpy())
x2, y2 = get_fake_data(batch_size=20)
# true data
plt.scatter(x2.numpy(), y2.numpy())
plt.xlim(0, 20)
plt.ylim(0, 41)
plt.show()
plt.pause(0.5)
print(w.data.squeeze().item(), b.data.squeeze().item)
輸出:
1.8774464130401611 2.944983959197998
用autograd實現的線性迴歸最大的不同點就在於利用autograd不需要手動計算梯度,可以自動微分。需要注意的是在每次反向傳播之前記得先把梯度清零。