# PyTorch线性回归用法图解

Y = AX + b

• A是斜率。
• b是y截距。

## 1.模型类

### 线性层使用

1. 初始化：用于定义线性模块。
2. 前瞻：借助前瞻方法, 在进行预测的基础上, 我们将训练线性回归模型

## 2.优化器

``````Optimizer=optim.SGD(model.parameters(), lr=0.01, momentum=0.9)

### 例：

``````for input, target in dataset:
output=model(input)
loss=loss_fn(output, target)
loss.backward()
optimizer.step()``````

### 2)Optimizer.step(关闭)

``````for input, target in dataset:
def closure():
output = model(input)
loss = loss_fn(output, target)
loss.backward()
return loss
optimizer.step(closure)``````

## 标准

``criterion = torch.nn.MSELoss(size_average = False)``

### 所需的功能和对象

1. 进口PyTorch

``````xdata=Variable(torch.Tensor([[1.0], [2.0], [3.0]]))
ydata=Variable(torch.Tensor([[2.0], [4.0], [6.0]]))``````

``````import torch
xdata = Variable(torch.Tensor([[1.0], [2.0], [3.0]]))
ydata = Variable(torch.Tensor([[2.0], [4.0], [6.0]]))
class LRM(torch.nn.Module):
def __init__(self):
super(LRM, self).__init__()
self.linear = torch.nn.Linear(1, 1)
def forward(self, x):
ypred = self.linear(x)
return ypred
ourmodel = LRM()
criterion = torch.nn.MSELoss(size_average = False)
optimizer = torch.optim.SGD(ourmodel.parameters(), lr = 0.01)
for epoch in range(500):
predy = our_model(xdata)
loss = criterion(predy, ydata)
loss.backward()
optimizer.step()
print('epoch {}, loss {}'.format(epoch, loss.item()))
newvar = Variable(torch.Tensor([[4.0]]))
predy = ourmodel(newvar)
print("predict (after training)", 4, our_model(newvar).data[0][0])``````

``````epoch0, loss1.7771836519241333
epoch1, loss1.0423388481140137
epoch2, loss0.7115973830223083
epoch3, loss0.5608030557632446
.
.
.
.
epoch499, loss0.0003389564517419785
predict (after training) 4 tensor(7.9788)``````

1. 做出预测
2. 线性类
3. 定制模块
4. 创建数据集
5. 损失函数
6. 梯度下降
7. 均方误差
8. 训练

• 回顶