線性迴歸模型原理模擬
原書來自Dive-into-DL-pytorch
%matplotlib inline
import torch
from IPython import display
from matplotlib import pyplot as plt
import numpy as np
import random
我們構造⼀個簡單的⼈⼯訓練數據集
它可以使我們能夠直觀⽐較學到的參數和真實的模型參數的區別。
設訓練數據集樣本數爲1000,輸⼊個數(特徵數)爲2。
給定隨機⽣成的批量樣本特徵爲1000*2的矩陣,
我們使⽤線性迴歸模型真實權重(2,-3.4)和偏差b=4.2 ,
以及⼀個隨機噪聲來⽣成標籤
num_inputs = 2
num_examples = 1000
true_w = [2, -3.4]
true_b = 4.2
features = torch.from_numpy(np.random.normal(0, 1, (num_examples,num_inputs)))
# 生成1000*2 的隨機輸入(數據集)
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] +true_b
labels += torch.from_numpy(np.random.normal(0, 0.01,
size=labels.size()))
在訓練模型的時候,我們需要遍歷數據集並不斷讀取⼩批量數據樣本。這⾥我們定義⼀個函數:
它每次返回 batch_size (批量⼤⼩)個隨機樣本的特徵和標籤
def data_iter(batch_size, features, labels):
num_examples = len(features)
indices = list(range(num_examples))
random.shuffle(indices) # 樣本的讀取順序是隨機的
for i in range(0, num_examples, batch_size):
j = torch.LongTensor(indices[i: min(i + batch_size,num_examples)]) # 最後⼀次可能不⾜⼀個batch
yield features.index_select(0, j), labels.index_select(0, j)
我們將權重初始化成均值爲0、標準差爲0.01的正態隨機數,偏差則初始化成0。
之後的模型訓練中,需要對這些參數求梯度來迭代參數的值,因此我們要讓它們的requires_grad=True
w = torch.tensor(np.random.normal(0, 0.01, (num_inputs, 1)),dtype=torch.float32)
b = torch.zeros(1, dtype=torch.float32)
w.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)
tensor([0.], requires_grad=True)
定義乘法
def linreg(X, w, b):
return torch.mm(X, w) + b
定義損失函數
def squared_loss(y_hat, y):
# 注意這⾥返回的是向量, 另外, pytorch⾥的MSELoss並沒有除以 2
return (y_hat - y.view(y_hat.size())) ** 2 / 2
定義優化算法
def sgd(params, lr, batch_size):
for param in params:
param.data -= lr * param.grad / batch_size # 注意這⾥更改param時⽤的param.data
在⼀個迭代週期(epoch)中,我們將完整遍歷⼀遍 data_iter 函數,
並對訓練數據集中所有樣本都使⽤⼀次(假設樣本數能夠被批量⼤⼩整除)。
這⾥的迭代週期個數 num_epochs 和學習率 lr 都是超參數,
分別設3和0.03。在實踐中,⼤多超參數都需要通過反覆試錯來不斷調節。
lr = 0.03
num_epochs = 3
net = linreg
loss = squared_loss
batch_size = 10
for epoch in range(num_epochs):
for X, y in data_iter(batch_size, features, labels):
l = loss(net(X, w, b), y).sum() # l是有關⼩批量X和y的損失
l.backward() # ⼩批量的損失對模型參數求梯度
sgd([w, b], lr, batch_size) # 使⽤⼩批量隨機梯度下降迭代模型參數
# 不要忘了梯度清零
w.grad.data.zero_()
b.grad.data.zero_()
train_l = loss(net(features, w, b), labels)
print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))
訓練完成後,我們可以⽐較學到的參數和⽤來⽣成訓練集的真實參數。它們應該很接近
print(true_w, '\n', w)
print(true_b, '\n', b)