0503-autograd實戰之線性回歸
目錄- 一、用 variable 實作線性回歸(autograd 實戰)
- 二、第五章總結
pytorch完整教程目錄:https://www.cnblogs.com/nickchen121/p/14662511.html
一、用 variable 實作線性回歸(autograd 實戰)
import torch as t
from torch.autograd import Variable as V
# 不是 jupyter 運行請注釋掉下面一行,為了 jupyter 顯示圖片
%matplotlib inline
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 # 噪聲為 |3-((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 i in range(8000):
x, y = get_fake_data()
x, y = V(x), V(y)
# forwad:計算 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 i % 1000 == 0:
# 畫圖
display.clear_output(wait=True)
x = t.arange(0, 20, dtype=t.float).view(-1, 1)
y = x.mm(w.data) + b.data.expand_as(x)
plt.plot(x.numpy(), y.numpy(), color='red') # 預測效果
x2, y2 = get_fake_data(batch_size=20)
plt.scatter(x2.numpy(), y2.numpy(), color='blue') # 真實資料
plt.xlim(0, 20)
plt.ylim(0, 41)
plt.show()
plt.pause(0.5)
break # 注銷這一行,可以看到動態效果

# y = x * 2 + 3
w.data.squeeze(), b.data.squeeze() # 列印訓練好的 w 和 b
(tensor(2.3009), tensor(0.1634))
二、第五章總結
本章介紹了 torch 的一個核心——autograd,其中 autograd 中的 variable 和 Tensor 都屬于 torch 中的基礎資料結構,variable 封裝了 Tensor ,擁有著和 Tensor 幾乎一樣的介面,并且提供了自動求導技術,autograd 是 torch 的自動微分引擎,采用動態計算圖的技術,可以更高效的計算導數,
這篇文章說實話是有點偏難的,可以多看幾遍,尤其是對于還沒有寫過實際專案的小白,不過相信有前面幾個小專案練手,以及最后一個線性回歸的小 demo,相信你差也不差的能看懂,但這都不要緊,在未來的專案實戰中,你將會對 autograd 的體會越來越深刻,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/279799.html
標籤:其他
上一篇:0502-計算圖
下一篇:python對BP神經網路實作
