社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  机器学习算法

【深度学习】使用 PyTorch 实现回归问题

机器学习初学者 • 1 年前 • 243 次点击  

在这篇博文中,我们将探讨线性回归的概念以及如何使用 PyTorch 实现它。回归是一种基本的统计建模技术,用于建立因变量与一个或多个自变量之间的关系。我们将使用 PyTorch(一种流行的深度学习框架)来开发和训练线性回归模型。

你可以在此处找到有关线性概念的更多详细信息:https://korlakuntasaikamal10.medium.com/understanding-linear-regression-in-machine-learning-bace83acce34

数据集

对于此分析,我们将使用scikit-learn 库中的 make regression() 函数生成的合成数据集。数据集由输入特征和目标变量组成。输入特征代表自变量,而目标变量代表我们想要预测的因变量。

import seaborn as sns
import numpy as sns
import torch
import torch.nn as nn
import torch.optim as optim
import sklearn
from sklearn import datasets
import pandas as pd

# from sklearn we are going to select one dataset
data=datasets.make_regression()
df = pd.DataFrame(data[0], columns=[f"feature_{i+1}" for i in range(data[0].shape[1])])
df["target"] = data[1]

PyTorch 基础知识

PyTorch 是一个功能强大的开源深度学习框架,提供了一种灵活的方式来构建和训练神经网络。它提供了一系列张量运算、自动微分和优化算法的功能。

PyTorch 的动态计算图可以轻松定义和修改复杂的神经网络架构。

在此处学习 Torch 基础知识:https://korlakuntasaikamal10.medium.com/pytorch-for-deep-learning-part-1-af4a1daa3454

使用 sklearn Train-Test-split 准备数据以开发模型



    
x=df.iloc[: , :-1]
y=df.iloc[: , -1]
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)
print(type(X_train))
# X_train=torch.tensor(X_train,dtype=torch.float32)

X_train = torch.tensor(X_train.values, dtype=torch.float32)
X_test = torch.tensor(X_test.values, dtype=torch.float32)
y_train = torch.tensor(y_train.values, dtype=torch.float32)
y_test = torch.tensor(y_test.values, dtype=torch.float32)

模型架构

我们的线性回归模型是作为PyTorch 中nn.Module类的子类实现的。该模型由多个按顺序连接的完全连接(线性)层组成。这些层负责将输入特征转换为预测输出值。该模型架构包括各种大小的隐藏层和具有单个神经元的输出层。

 # since data is ready we can develop the model:

class linearRegression(nn.Module): # all the dependencies from torch will be given to this class [parent class] # nn.Module contains all the building block of neural networks:
  def __init__(self,input_dim):
    super(linearRegression,self).__init__()  # building connection with parent and child classes
    self.fc1=nn.Linear(input_dim,10)          # hidden layer 1
    self.fc2=nn.Linear(10,5)                  # hidden layer 2
    self.fc3=nn.Linear(5,3)                   # hidden layer 3
    self.fc4=nn.Linear(3,1)                   # last layer

  def forward(self,d):
    out=torch.relu(self.fc1(d))              # input * weights + bias for layer 1
    out=torch.relu(self.fc2(out))            # input * weights + bias for layer 2
    out=torch.relu(self.fc3(out))            # input * weights + bias for layer 3
    out=self.fc4(out)                        # input * weights + bias for last layer
    return out                               # final outcome

input_dim=X_train.shape[1]
torch.manual_seed(42)  # to make initilized weights stable:
model=linearRegression(input_dim)

训练过程

为了训练模型,我们使用均方误差 (MSE) 损失函数,该函数测量预测值与实际目标值之间的平均平方差。使用 Adam 优化器执行优化,该优化器根据计算的梯度调整模型的参数。该模型经过指定数量的 epoch 进行训练,其中每个 epoch 都涉及前向传播、损失计算、反向传播和权重更新。

# select loss and optimizers

loss=nn.MSELoss() # loss function
optimizers=optim.Adam(params=model.parameters(),lr=0.01)



# training the model:

num_of_epochs=1000
for i in range(num_of_epochs):
  # give the input data to the architecure
  y_train_prediction=model(X_train)  # model initilizing
  loss_value=loss(y_train_prediction.squeeze(),y_train)   # find the loss function:
  optimizers.zero_grad() # make gradients zero for every iteration so next iteration it will be clear
  loss_value.backward()  # back propagation
  optimizers.step()  # update weights in NN

  # print the loss in training part:
  if i % 10 == 0:
    print(f'[epoch:{i}]: The loss value for training part={loss_value}')

评价与表现

在训练期间,我们监控损失值以评估模型的性能。我们将数据集分为训练集和测试集,以评估模型的泛化能力。使用测试数据集评估训练模型,并计算测试损失。较低的测试损失表明更好的性能。

# we can do check it with test data:

with torch.no_grad():
  model.eval()   # make model in evaluation stage
  y_test_prediction=model(X_test)
  test_loss=loss(y_test_prediction.squeeze(),y_test)
  print(f'Test loss value : {test_loss.item():.4f}')
# Inference with own data:
pr = torch.tensor(torch.arange(1101).unsqueeze(dim=0), dtype=torch.float32).clone().detach()
print(pr)

保存和加载模型

训练后,我们使用 PyTorch 的save()函数保存训练后的模型的参数。这使我们能够在将来重用该模型而无需重新训练。我们可以使用load_state_dict()方法加载保存的模型并对新数据进行预测。

# save the torch model:

from pathlib import Path

filename=Path('models')
filename.mkdir(parents=True,exist_ok=True)

model_name='linear_regression.pth' # model name

# saving path

saving_path=filename/model_name
print(saving_path)
torch.save(obj=model.state_dict(),f=saving_path)

# we can load the saved model and do the inference again:

load_model=linearRegression(input_dim) # creating an instance again for loaded model
load_model.load_state_dict(torch.load('/content/models/linear_regression.pth'))

load_model.eval()   # make model in evaluation stage
with torch.no_grad():
  pred = load_model(torch.tensor([[  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,  12.,
          13.,  14.,  15.,  16.,  17.,  18.,  19.,  20.,  21.,  22.,  23.,  24.,
          25.,  26.,  27.,  28.,  29.,  30.,  31.,  32.,  33.,  34.,  35.,  36.,
          37.,  38.,  39.,  40.,  41.,  42.,  43.,  44.,  45.,  46. ,  47.,  48.,
          49.,  50.,  51.,  52.,  53.,  54.,  55.,  56.,  57.,  58.,  59.,  60.,
          61.,  62.,  63.,  64.,  65.,  66.,  67.,  68.,  69.,  70.,  71.,  72.,
          73.,  74.,  75.,  76.,  77.,  78.,  79.,  80.,  81.,  82.,  83.,  84.,
          85.,  86.,  87.,  88.,  89.,  90.,  91.,  92.,  93.,  94.,  95.,  96.,
          97.,  98.,  99.100.]]))

  print(f'prediction value : {pred.item()}')

结论

在这篇博文中,我们探索了使用 PyTorch 的线性回归分析。我们学习了如何准备数据集、构建线性回归模型、使用梯度下降优化训练模型并评估其性能。PyTorch 的灵活性和广泛的功能使其成为开发和训练各种机器学习模型的强大工具。


☆ END ☆


    
往期精彩回顾




  • 交流群

欢迎加入机器学习爱好者微信群一起和同行交流,目前有机器学习交流群、博士群、博士申报交流、CV、NLP等微信群,请扫描下面的微信号加群,备注:”昵称-学校/公司-研究方向“,例如:”张小明-浙大-CV“。请按照格式备注,否则不予通过。添加成功后会根据研究方向邀请进入相关微信群。请勿在群内发送广告,否则会请出群,谢谢理解~(也可以加入机器学习交流qq群772479961


Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/165119
 
243 次点击