線性回歸是機器學習入門知識,應用十分廣泛。
線性回歸利用數理統計中回歸分析,來確定兩種或兩種以上變量間相互依賴的定量關系的,其表達形式為 ??=????+??+?? , ?? 為誤差服從均值為0的正態分布。首先讓我們來確認線性回歸的損失函數:
1591246478(1).png
import torch as t
%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
return x, y···
# 來看看產生的x-y分布
x, y = get_fake_data()
plt.scatter(x.squeeze().numpy(), y.squeeze().numpy())
1591246587(1).jpg
# 隨機初始化參數
w = t.rand(1, 1)
b = t.zeros(1, 1)
lr =0.001 # 學習率
for ii in range(20000):
x, y = get_fake_data()
# forward:計算loss
y_pred = x.mm(w) + b.expand_as(y) # x@W等價于x.mm(w);for python3 only
loss = 0.5 * (y_pred - y) ** 2 # 均方誤差
loss = loss.sum()
# backward:手動計算梯度
dloss = 1
dy_pred = dloss * (y_pred - y)
dw = x.t().mm(dy_pred)
db = dy_pred.sum()
# 更新參數
w.sub_(lr * dw)
b.sub_(lr * db)
if ii%1000 ==0:
# 畫圖
display.clear_output(wait=True)
x = t.arange(0, 20).view(-1, 1)
x = t.tensor(x, dtype=t.float32)
y = x.mm(w) + b.expand_as(x)
plt.plot(x.numpy(), y.numpy()) # predicted
x2, y2 = get_fake_data(batch_size=20)
plt.scatter(x2.numpy(), y2.numpy()) # true data
plt.xlim(0, 20)
plt.ylim(0, 41)
plt.show()
plt.pause(0.5)
print(w.squeeze().item(), b.squeeze().item())
1591246641(1).jpg
最后結果已經基本學出w=2、b=3,已經實現較好的擬合。
參考書籍:深度學習框架 pytorch入門與實踐 陳云