用Pytorch實(shí)現(xiàn)線性回歸模型的步驟
Pytorch實(shí)現(xiàn)
步驟
- 準(zhǔn)備數(shù)據(jù)集
- 設(shè)計(jì)模型(計(jì)算預(yù)測值y_hat):從nn.Module模塊繼承
- 構(gòu)造損失函數(shù)和優(yōu)化器:使用PytorchAPI
- 訓(xùn)練過程:Forward、Backward、update
1. 準(zhǔn)備數(shù)據(jù)
在PyTorch中計(jì)算圖是通過mini-batch形式進(jìn)行,所以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. 設(shè)計(jì)模型
在之前講解梯度下降算法時(shí),我們需要自己計(jì)算出梯度,然后更新權(quán)重。
而使用Pytorch構(gòu)造模型,重點(diǎn)時(shí)在構(gòu)建計(jì)算圖和損失函數(shù)上。
class LinearModel
通過構(gòu)造一個(gè) class LinearModel類來實(shí)現(xiàn),所有的模型類都需要繼承nn.Module,這是所有神經(jīng)忘了模塊的基礎(chǔ)類。
class LinearModel這種定義的模型類必須包含兩個(gè)部分:
- init():構(gòu)造函數(shù),進(jìn)行初始化。
def __init__(self): super(LinearModel, self).__init__()#調(diào)用父類構(gòu)造函數(shù),不用管,照著寫。 # torch.nn.Linear(in_featuers, in_featuers)構(gòu)造Linear類的對象,其實(shí)就是實(shí)現(xiàn)了一個(gè)線性單元 self.linear = torch.nn.Linear(1, 1)
- forward():進(jìn)行前饋計(jì)算(backward沒有被寫,是因?yàn)樵谶@種模型類里面會(huì)自動(dòng)實(shí)現(xiàn))
Class nn.Linear 實(shí)現(xiàn)了magic method call():它使類的實(shí)例可以像函數(shù)一樣被調(diào)用。通常會(huì)調(diào)用forward()。
def forward(self, x): y_pred = self.linear(x)#調(diào)用linear對象,輸入x進(jìn)行預(yù)測 return y_pred
代碼
class LinearModel(torch.nn.Module): def __init__(self): super(LinearModel, self).__init__()#調(diào)用父類構(gòu)造函數(shù),不用管,照著寫。 # torch.nn.Linear(in_featuers, in_featuers)構(gòu)造Linear類的對象,其實(shí)就是實(shí)現(xiàn)了一個(gè)線性單元 self.linear = torch.nn.Linear(1, 1) def forward(self, x): y_pred = self.linear(x)#調(diào)用linear對象,輸入x進(jìn)行預(yù)測 return y_pred model = LinearModel()#實(shí)例化LinearModel()
3. 構(gòu)造損失函數(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:學(xué)習(xí)率
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. 訓(xùn)練過程
- 預(yù)測
- 計(jì)算loss
- 梯度清零
- Backward
- 參數(shù)更新
簡化:Forward–>Backward–>更新
#4. Training Cycle for epoch in range(100): y_pred = model(x_data)#Forward:預(yù)測 loss = criterion(y_pred, y_data)#Forward:計(jì)算loss print(epoch, loss) optimizer.zero_grad()#梯度清零 loss.backward()#backward:計(jì)算梯度 optimizer.step()#通過step()函數(shù)進(jìn)行參數(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__()#調(diào)用父類構(gòu)造函數(shù),不用管,照著寫。 # torch.nn.Linear(in_featuers, in_featuers)構(gòu)造Linear類的對象,其實(shí)就是實(shí)現(xiàn)了一個(gè)線性單元 self.linear = torch.nn.Linear(1, 1) def forward(self, x): y_pred = self.linear(x)#調(diào)用linear對象,輸入x進(jìn)行預(yù)測 return y_pred model = LinearModel()#實(shí)例化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:預(yù)測 loss = criterion(y_pred, y_data)#Forward:計(jì)算loss print(epoch, loss) optimizer.zero_grad()#梯度清零 loss.backward()#backward:計(jì)算梯度 optimizer.step()#通過step()函數(shù)進(jìn)行參數(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)
輸出結(jié)果:
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]])
可以看到誤差還比較大,可以增加訓(xùn)練輪次,訓(xùn)練1000次后的結(jié)果:
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]])
練習(xí)
用以下這些優(yōu)化器替換SGD,得到訓(xùn)練結(jié)果并畫出損失曲線圖。
比如說:Adam的loss圖:
以上就是用Pytorch實(shí)現(xiàn)線性回歸模型的步驟的詳細(xì)內(nèi)容,更多關(guān)于Pytorch線性回歸模型的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python使用socket實(shí)現(xiàn)的傳輸demo示例【基于TCP協(xié)議】
這篇文章主要介紹了python使用socket實(shí)現(xiàn)的傳輸demo,結(jié)合實(shí)例形式分析了Python使用socket庫基于TCP協(xié)議實(shí)現(xiàn)的客戶端與服務(wù)器端相關(guān)操作技巧,需要的朋友可以參考下2019-09-09Matplotlib學(xué)習(xí)筆記之plt.xticks()用法
在matplotlib中ticks表示的是刻度,而刻度有兩層意思,一個(gè)是刻標(biāo)(locs),一個(gè)是刻度標(biāo)簽(tick?labels),下面這篇文章主要給大家介紹了關(guān)于Matplotlib學(xué)習(xí)筆記之plt.xticks()用法的相關(guān)資料,需要的朋友可以參考下2022-09-09Pytorch關(guān)于Dataset?的數(shù)據(jù)處理
這篇文章主要介紹了Pytorch關(guān)于Dataset?的數(shù)據(jù)處理,學(xué)習(xí)如何對卷積神經(jīng)網(wǎng)絡(luò)編程;首先,需要了解Pytorch對數(shù)據(jù)的使用,也是在我們模型流程中對數(shù)據(jù)的預(yù)處理部分,下面我們就一起進(jìn)入文章查看具體處理過程吧2021-12-12