PyTorch实现线性回归 | 多维输入单维输出

线性回归

import warnings
warnings.filterwarnings("ignore")
import torch
from torch.autograd import Variable
# train data
x_data = Variable(torch.Tensor([[1.0,2.0,0.5], [2.0,4.0,0.3], [3.0,6.0,0.1]]))
y_data = Variable(torch.Tensor([[1.5], [1.8], [0.9]]))
# x和y一一对应 学习从x到y的映射 例如 (1.0 + 2.0) * 0.5 = 1.5
class Model(torch.nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.linear = torch.nn.Linear(3, 1) # One in and one out
    def forward(self, x):
        y_pred = self.linear(x)
        return y_pred
# our model
model = Model()
criterion = torch.nn.MSELoss(size_average=False) # Defined loss function
optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # Defined optimizer
for epoch in range(100):
    y_pred = model(x_data)
    loss = criterion(y_pred, y_data)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    if epoch % 10 ==0 :
        print(epoch, loss.item())
0 34.39658737182617
10 1.4057011604309082
20 1.149032473564148
30 0.9488809704780579
40 0.7927986979484558
50 0.6710829138755798
60 0.5761667490005493
70 0.5021493434906006
80 0.4444289803504944
90 0.3994176983833313
model.eval()
test_data = Variable(torch.Tensor([[4.0,8.0,0.1]]))
predicted = model(test_data).detach().numpy()[0][0]
print(predicted)
# 当我输入(4+8)*0.1的时候输出十分接近1.2了
1.4094565

你可能感兴趣的:(深度学习CV方向,深度学习,线性回归,pytorch)