pytorch快速入门--构建线性回归
程序员文章站
2022-06-11 22:46:45
...
准备数据
这里用一组比较简单的数据
x_data = torch.Tensor([[1.0],[2.0],[3.0]])
y_data = torch.Tensor([[3.0],[6.0],[9.0]])
构建线性回归模型
#定义一个线性回归类
class Model(torch.nn.Module):
def __init__(self):
super(Model,self).__init__()
#模型只包含一个线性回归模型
self.linear = torch.nn.Linear(1,1)
#前向运算
def forward(self,x):
y_pred = self.linear(x)
return y_pred
构建目标函数与优化方法
#定义损失函数
criterion = torch.nn.MSELoss(size_average = False)
#随机梯度下降作为优化方法
optimizer = torch.optim.SGD(model.parameters(),lr=0.01)
迭代过程
#开始迭代
for epoch in range(500):
y_pred = model(x_data)
求损失函数
loss = criterion(y_pred,y_data)
print("epoch: ",epoch," loss: ",loss.item())
optimizer.zero_grad()
#反向
loss.backward()
#优化
optimizer.step()
全部代码
import torch
from torch.autograd import Variable
x_data = torch.Tensor([[1.0],[2.0],[3.0]])
y_data = torch.Tensor([[2.0],[4.0],[6.0]])
class Model(torch.nn.Module):
def __init__(self):
super(Model,self).__init__()
self.linear = torch.nn.Linear(1,1)
def forward(self,x):
y_pred = self.linear(x)
return y_pred
model = Model()
criterion = torch.nn.MSELoss(size_average = False)
optimizer = torch.optim.SGD(model.parameters(),lr=0.01)
for epoch in range(500):
y_pred = model(x_data)
loss = criterion(y_pred,y_data)
print("epoch: ",epoch," loss: ",loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
hour_val = torch.Tensor([[4.0]])
print("after training:",4,model.forward(hour_val).data[0][0])
结果
这里只展示最后的结果了
epoch: 496 loss: 0.0005511323106475174
epoch: 497 loss: 0.0005431824829429388
epoch: 498 loss: 0.0005353790475055575
epoch: 499 loss: 0.0005277082673273981
after training: 4 tensor(11.9736)
可以看出最后求得的结果是11.9736,很接近12
上一篇: ASP.NET MVC 实现JSONP
下一篇: php 数组的相同值的有关问题