一維線性回歸pytorch實現

2022-09-10 06:21:11 字數 2305 閱讀 9020

訓練**:

import torch

import numpy as np

x_train = np.array([[

3.3],[

4.4],[

5.5],[

6.71],

[6.93],

[4.168],

[9.799]]

)y_train = np.array([[

1.7],[

2.76],

[2.09],

[3.19],

[1.694],

[1.573],

[3.366]]

)x_train = torch.from_numpy(x_train)

.float()

y_train = torch.from_numpy(y_train)

.float()

print

('x_train:{}'

.format

(x_train)

)print

('y_train:{}'

.format

(y_train)

)class

linearregression

(torch.nn.module)

:def

__init__

(self)

:super

(linearregression, self)

.__init__(

) self.linear = torch.nn.linear(1,

1)#輸入輸出均是一維的

defforward

(self, x)

: out = self.linear(x)

return out

model = linearregression(

)#定義模型

criterion = torch.nn.mseloss(

)#定義損失函式

optimizer = torch.optim.sgd(model.parameters(

), lr =1e-

2)#優化器

num_epochs =

1000

#優化1000次

for epoch in

range

(num_epochs)

: inputs_ = torch.autograd.variable(x_train)

target = torch.autograd.variable(y_train)

#forward

out = model(inputs_)

#由於繼承了nn.module模組,該模組已經呼叫了forward函式,該語句等價於 out = model.forward(inputs_)

loss = criterion(out, target)

#backward

optimizer.zero_grad(

)#每次做反向傳播前都要歸零梯度

loss.backward(

) optimizer.step(

)#更新引數

if(epoch+1)

%20==0

:#每隔一段時間看下訓練結果

print

('epoch[{}/{}], loss: '

.format

(epoch+

1, num_epochs, loss.data)

)

做完訓練後,可以檢視下**結果:

import matplotlib.pyplot as plt

model.

eval()

#將模型變為**模型

Pytorch實現線性回歸 手動

pytorch實現線性回歸 假設我們的基礎模型就是 y wx b 其中w和b均為引數,我們使用y 3 x 0.8來構造資料x,y 所以最後通過模型應該能夠得到w和b應該在3與0.8附近。思路如下 1準備資料 2計算 值 3計算損失,把引數的梯度設定為0,進行反向傳播 4更新引數 5效果視覺化 1準備...

pytorch線性回歸

線性回歸假設輸出與各個輸入之間是線性關係 y wx b pytorch定義線性回歸模型 def linreg x,w,b return torch.mm x,w b線性回歸常用損失函式是平方損失 2優化函式 隨機梯度下降 小批量隨機梯度下降 mini batch stochastic gradien...

pytorch 線性回歸

import torch from torch.autograd import variable import torch.nn.functional as f import matplotlib.pyplot as plt print torch.linspace 1,1,100 x torch....