用Pytorch實現(xiàn)線性回歸模型的步驟
Pytorch實現(xiàn)
步驟
- 準備數(shù)據(jù)集
- 設計模型(計算預測值y_hat):從nn.Module模塊繼承
- 構造損失函數(shù)和優(yōu)化器:使用PytorchAPI
- 訓練過程:Forward、Backward、update
1. 準備數(shù)據(jù)
在PyTorch中計算圖是通過mini-batch形式進行,所以X、Y都是多維的Tensor。
import torch x_data = torch.Tensor([[1.0], [2.0], [3.0]]) y_data = torch.Tensor([[2.0], [4.0], [6.0]])
2. 設計模型
在之前講解梯度下降算法時,我們需要自己計算出梯度,然后更新權重。
而使用Pytorch構造模型,重點時在構建計算圖和損失函數(shù)上。
class LinearModel
通過構造一個 class LinearModel類來實現(xiàn),所有的模型類都需要繼承nn.Module,這是所有神經(jīng)忘了模塊的基礎類。
class LinearModel這種定義的模型類必須包含兩個部分:
- init():構造函數(shù),進行初始化。
def __init__(self): super(LinearModel, self).__init__()#調用父類構造函數(shù),不用管,照著寫。 # torch.nn.Linear(in_featuers, in_featuers)構造Linear類的對象,其實就是實現(xiàn)了一個線性單元 self.linear = torch.nn.Linear(1, 1)
- forward():進行前饋計算(backward沒有被寫,是因為在這種模型類里面會自動實現(xiàn))
Class nn.Linear 實現(xiàn)了magic method call():它使類的實例可以像函數(shù)一樣被調用。通常會調用forward()。
def forward(self, x): y_pred = self.linear(x)#調用linear對象,輸入x進行預測 return y_pred
代碼
class LinearModel(torch.nn.Module): def __init__(self): super(LinearModel, self).__init__()#調用父類構造函數(shù),不用管,照著寫。 # torch.nn.Linear(in_featuers, in_featuers)構造Linear類的對象,其實就是實現(xiàn)了一個線性單元 self.linear = torch.nn.Linear(1, 1) def forward(self, x): y_pred = self.linear(x)#調用linear對象,輸入x進行預測 return y_pred model = LinearModel()#實例化LinearModel()
3. 構造損失函數(shù)和優(yōu)化器
采用MSE作為損失函數(shù)
torch.nn.MSELoss(size_average,reduce)
- size_average:是否求mini-batch的平均loss。
- reduce:降維,不用管。
SGD作為優(yōu)化器torch.optim.SGD(params, lr):
- params:參數(shù)
- lr:學習率
criterion = torch.nn.MSELoss(size_average=False)#size_average:the losses are averaged over each loss element in the batch. optimizer = torch.optim.SGD(model.parameters(), lr=0.01)#params:model.parameters(): w、b
4. 訓練過程
- 預測
- 計算loss
- 梯度清零
- Backward
- 參數(shù)更新
簡化:Forward–>Backward–>更新
#4. Training Cycle for epoch in range(100): y_pred = model(x_data)#Forward:預測 loss = criterion(y_pred, y_data)#Forward:計算loss print(epoch, loss) optimizer.zero_grad()#梯度清零 loss.backward()#backward:計算梯度 optimizer.step()#通過step()函數(shù)進行參數(shù)更新
5. 輸出和測試
# Output weight and bias print('w = ', model.linear.weight.item()) print('b = ', model.linear.bias.item()) # Test Model x_test = torch.Tensor([[4.0]]) y_test = model(x_test) print('y_pred = ', y_test.data)
完整代碼
import torch #1. Prepare dataset x_data = torch.Tensor([[1.0], [2.0], [3.0]]) y_data = torch.Tensor([[2.0], [4.0], [6.0]]) #2. Design Model class LinearModel(torch.nn.Module): def __init__(self): super(LinearModel, self).__init__()#調用父類構造函數(shù),不用管,照著寫。 # torch.nn.Linear(in_featuers, in_featuers)構造Linear類的對象,其實就是實現(xiàn)了一個線性單元 self.linear = torch.nn.Linear(1, 1) def forward(self, x): y_pred = self.linear(x)#調用linear對象,輸入x進行預測 return y_pred model = LinearModel()#實例化LinearModel() # 3. Construct Loss and Optimize criterion = torch.nn.MSELoss(size_average=False)#size_average:the losses are averaged over each loss element in the batch. optimizer = torch.optim.SGD(model.parameters(), lr=0.01)#params:model.parameters(): w、b #4. Training Cycle for epoch in range(100): y_pred = model(x_data)#Forward:預測 loss = criterion(y_pred, y_data)#Forward:計算loss print(epoch, loss) optimizer.zero_grad()#梯度清零 loss.backward()#backward:計算梯度 optimizer.step()#通過step()函數(shù)進行參數(shù)更新 # Output weight and bias print('w = ', model.linear.weight.item()) print('b = ', model.linear.bias.item()) # Test Model x_test = torch.Tensor([[4.0]]) y_test = model(x_test) print('y_pred = ', y_test.data)
輸出結果:
85 tensor(0.2294, grad_fn=)
86 tensor(0.2261, grad_fn=)
87 tensor(0.2228, grad_fn=)
88 tensor(0.2196, grad_fn=)
89 tensor(0.2165, grad_fn=)
90 tensor(0.2134, grad_fn=)
91 tensor(0.2103, grad_fn=)
92 tensor(0.2073, grad_fn=)
93 tensor(0.2043, grad_fn=)
94 tensor(0.2014, grad_fn=)
95 tensor(0.1985, grad_fn=)
96 tensor(0.1956, grad_fn=)
97 tensor(0.1928, grad_fn=)
98 tensor(0.1900, grad_fn=)
99 tensor(0.1873, grad_fn=)
w = 1.711882472038269
b = 0.654958963394165
y_pred = tensor([[7.5025]])
可以看到誤差還比較大,可以增加訓練輪次,訓練1000次后的結果:
980 tensor(2.1981e-07, grad_fn=)
981 tensor(2.1671e-07, grad_fn=)
982 tensor(2.1329e-07, grad_fn=)
983 tensor(2.1032e-07, grad_fn=)
984 tensor(2.0737e-07, grad_fn=)
985 tensor(2.0420e-07, grad_fn=)
986 tensor(2.0143e-07, grad_fn=)
987 tensor(1.9854e-07, grad_fn=)
988 tensor(1.9565e-07, grad_fn=)
989 tensor(1.9260e-07, grad_fn=)
990 tensor(1.8995e-07, grad_fn=)
991 tensor(1.8728e-07, grad_fn=)
992 tensor(1.8464e-07, grad_fn=)
993 tensor(1.8188e-07, grad_fn=)
994 tensor(1.7924e-07, grad_fn=)
995 tensor(1.7669e-07, grad_fn=)
996 tensor(1.7435e-07, grad_fn=)
997 tensor(1.7181e-07, grad_fn=)
998 tensor(1.6931e-07, grad_fn=)
999 tensor(1.6700e-07, grad_fn=)
w = 1.9997280836105347
b = 0.0006181497010402381
y_pred = tensor([[7.9995]])
練習
用以下這些優(yōu)化器替換SGD,得到訓練結果并畫出損失曲線圖。
比如說:Adam的loss圖:
以上就是用Pytorch實現(xiàn)線性回歸模型的步驟的詳細內容,更多關于Pytorch線性回歸模型的資料請關注腳本之家其它相關文章!
相關文章
python使用socket實現(xiàn)的傳輸demo示例【基于TCP協(xié)議】
這篇文章主要介紹了python使用socket實現(xiàn)的傳輸demo,結合實例形式分析了Python使用socket庫基于TCP協(xié)議實現(xiàn)的客戶端與服務器端相關操作技巧,需要的朋友可以參考下2019-09-09Pytorch關于Dataset?的數(shù)據(jù)處理
這篇文章主要介紹了Pytorch關于Dataset?的數(shù)據(jù)處理,學習如何對卷積神經(jīng)網(wǎng)絡編程;首先,需要了解Pytorch對數(shù)據(jù)的使用,也是在我們模型流程中對數(shù)據(jù)的預處理部分,下面我們就一起進入文章查看具體處理過程吧2021-12-12