带有Pytorch的线性回归-预测误差

时间:2020-07-28 20:03:20

标签: python machine-learning pytorch linear-regression

我正在使用PyTorch预测因变量的值。

我正在读取数据集的源文件

enter image description here

如您所见,缺陷百分比(因变量为〜0至3)

import torch.nn as nn
import numpy as np
import torch
import pandas as pd
from torch.utils.data import TensorDataset, DataLoader
import torch.nn.functional as F

SourceData=pd.read_excel("Supplier Past Performance.xlsx") # Load the data into Pandas DataFrame


SourceData_train_independent= SourceData.drop(["Defect Per cent"], axis=1) # Drop depedent variable from training dataset

SourceData_train_dependent=SourceData["Defect Per cent"].copy() # Dependent variable value for training dataset


X_train = torch.tensor(SourceData_train_independent.values)
y_train=torch.tensor(SourceData_train_dependent.values)

X_train=X_train.type(torch.FloatTensor) #convert the type of tensor
y_train=y_train.type(torch.FloatTensor) #convert the type of tensor

# Define dataset
train_ds = TensorDataset(X_train, y_train)

# Define data loader
batch_size = 5
train_dl = DataLoader(train_ds, batch_size, shuffle=True)

#Define model
model = nn.Linear(3,1)

#Define optimizer
opt = torch.optim.SGD(model.parameters(), lr=0.02)

#Define loss function
loss_fn = F.mse_loss

#Define a utility function to train the model
def fit(num_epochs, model, loss_fn, opt):
    for epoch in range(num_epochs):
        for xb,yb in train_dl:

            #Generate predictions
            pred = model(xb)

            loss = loss_fn(pred,yb)
            #Perform gradient descent
            loss.backward()
            opt.step()
            opt.zero_grad()
   print('Training loss: ', loss_fn(model(xb), yb))

#Train the model for 100 epochs
fit(100, model, loss_fn, opt)

new_var=torch.Tensor([[5000.0, 33.0, 23.0]])
preds = model(new_var)
print(preds.item())

我对new_var的预测为963.40。该值比他预期的0.1到3高得多。

请帮助

0 个答案:

没有答案
相关问题