首页 > 其他分享 >深度学习 - PyTorch基本流程 (代码)

深度学习 - PyTorch基本流程 (代码)

时间:2024-03-25 13:32:54浏览次数:20  
标签:loss 代码 test PyTorch train print model True 流程

直接上代码

import torch 
import matplotlib.pyplot as plt 
from torch import nn

# 创建data
print("**** Create Data ****")
weight = 0.3
bias = 0.9
X = torch.arange(0,1,0.01).unsqueeze(dim = 1)
y = weight * X + bias
print(f"Number of X samples: {len(X)}")
print(f"Number of y samples: {len(y)}")
print(f"First 10 X & y sample: \n X: {X[:10]}\n y: {y[:10]}")
print("\n")

# 将data拆分成training 和 testing
print("**** Splitting data ****")
train_split = int(len(X) * 0.8)
X_train = X[:train_split]
y_train = y[:train_split]
X_test = X[train_split:]
y_test = y[train_split:]
print(f"The length of X train: {len(X_train)}")
print(f"The length of y train: {len(y_train)}")
print(f"The length of X test: {len(X_test)}")
print(f"The length of y test: {len(y_test)}\n")

# 显示 training 和 testing 数据
def plot_predictions(train_data = X_train,
                     train_labels = y_train,
                     test_data = X_test,
                     test_labels = y_test,
                     predictions = None):
  plt.figure(figsize = (10,7))
  plt.scatter(train_data, train_labels, c = 'b', s = 4, label = "Training data")
  plt.scatter(test_data, test_labels, c = 'g', label="Test data")

  if predictions is not None:
    plt.scatter(test_data, predictions, c = 'r', s = 4, label = "Predictions")
  plt.legend(prop = {"size": 14})
plot_predictions()

# 创建线性回归
print("**** Create PyTorch linear regression model by subclassing nn.Module ****")
class LinearRegressionModel(nn.Module):
  def __init__(self):
    super().__init__()
    self.weight = nn.Parameter(data = torch.randn(1,
                                                  requires_grad = True,
                                                  dtype = torch.float))
    self.bias = nn.Parameter(data = torch.randn(1,
                                                requires_grad = True,
                                                dtype = torch.float))
    
  def forward(self, x):
    return self.weight * x + self.bias

torch.manual_seed(42)
model_1 = LinearRegressionModel()
print(model_1)
print(model_1.state_dict())
print("\n")

# 初始化模型并放到目标机里
print("*** Instantiate the model ***")
print(list(model_1.parameters()))
print("\\n")

# 创建一个loss函数并优化
print("*** Create and Loss function and optimizer ***")
loss_fn = nn.L1Loss()
optimizer = torch.optim.SGD(params = model_1.parameters(),
                            lr = 0.01)
print(f"loss_fn: {loss_fn}")
print(f"optimizer: {optimizer}\n")

# 训练
print("*** Training Loop ***")
torch.manual_seed(42)
epochs = 300
for epoch in range(epochs):
  # 将模型加载到训练模型里
  model_1.train()

  # 做 Forward
  y_pred = model_1(X_train)

  # 计算 Loss
  loss = loss_fn(y_pred, y_train)

  # 零梯度
  optimizer.zero_grad()

  # 反向传播
  loss.backward()

  # 步骤优化
  optimizer.step()

  ### 做测试
  if epoch % 20 == 0:
    # 将模型放到评估模型并设置上下文
    model_1.eval()
    with torch.inference_mode():
      # 做 Forward
      y_preds = model_1(X_test)
      # 计算测试 loss
      test_loss = loss_fn(y_preds, y_test)
      # 输出测试结果
      print(f"Epoch: {epoch} | Train loss: {loss:.3f} | Test loss: {test_loss:.3f}")

# 在测试集上对训练模型做预测
print("\n")
print("*** Make predictions with the trained model on the test data. ***")
model_1.eval()
with torch.inference_mode():
  y_preds = model_1(X_test)
print(f"y_preds:\n {y_preds}")
## 画图
plot_predictions(predictions = y_preds) 

# 保存训练好的模型
print("\n")
print("*** Save the trained model ***")
from pathlib import Path 
## 创建模型的文件夹
MODEL_PATH = Path("models")
MODEL_PATH.mkdir(parents = True, exist_ok = True)
## 创建模型的位置
MODEL_NAME = "trained model"
MODEL_SAVE_PATH = MODEL_PATH / MODEL_NAME 
## 保存模型到刚创建好的文件夹
print(f"Saving model to {MODEL_SAVE_PATH}")
torch.save(obj = model_1.state_dict(), f = MODEL_SAVE_PATH)
## 创建模型的新类型
loaded_model = LinearRegressionModel()
loaded_model.load_state_dict(torch.load(f = MODEL_SAVE_PATH))
## 做预测,并跟之前的做预测
y_preds_new = loaded_model(X_test)
print(y_preds == y_preds_new)

结果如下

**** Create Data ****
Number of X samples: 100
Number of y samples: 100
First 10 X & y sample: 
 X: tensor([[0.0000],
        [0.0100],
        [0.0200],
        [0.0300],
        [0.0400],
        [0.0500],
        [0.0600],
        [0.0700],
        [0.0800],
        [0.0900]])
 y: tensor([[0.9000],
        [0.9030],
        [0.9060],
        [0.9090],
        [0.9120],
        [0.9150],
        [0.9180],
        [0.9210],
        [0.9240],
        [0.9270]])

**** Splitting data ****
The length of X train: 80
The length of y train: 80
The length of X test: 20
The length of y test: 20

**** Create PyTorch linear regression model by subclassing nn.Module ****
LinearRegressionModel()
OrderedDict([('weight', tensor([0.3367])), ('bias', tensor([0.1288]))])


*** Instantiate the model ***
[Parameter containing:
tensor([0.3367], requires_grad=True), Parameter containing:
tensor([0.1288], requires_grad=True)]

*** Create and Loss function and optimizer ***
loss_fn: L1Loss()
optimizer: SGD (
Parameter Group 0
    dampening: 0
    differentiable: False
    foreach: None
    lr: 0.01
    maximize: False
    momentum: 0
    nesterov: False
    weight_decay: 0
)

*** Training Loop ***
Epoch: 0 | Train loss: 0.757 | Test loss: 0.725
Epoch: 20 | Train loss: 0.525 | Test loss: 0.454
Epoch: 40 | Train loss: 0.294 | Test loss: 0.183
Epoch: 60 | Train loss: 0.077 | Test loss: 0.073
Epoch: 80 | Train loss: 0.053 | Test loss: 0.116
Epoch: 100 | Train loss: 0.046 | Test loss: 0.105
Epoch: 120 | Train loss: 0.039 | Test loss: 0.089
Epoch: 140 | Train loss: 0.032 | Test loss: 0.074
Epoch: 160 | Train loss: 0.025 | Test loss: 0.058
Epoch: 180 | Train loss: 0.018 | Test loss: 0.042
Epoch: 200 | Train loss: 0.011 | Test loss: 0.026
Epoch: 220 | Train loss: 0.004 | Test loss: 0.009
Epoch: 240 | Train loss: 0.004 | Test loss: 0.006
Epoch: 260 | Train loss: 0.004 | Test loss: 0.006
Epoch: 280 | Train loss: 0.004 | Test loss: 0.006


*** Make predictions wit the trained model on the test data. ***
y_preds:
 tensor([[1.1464],
        [1.1495],
        [1.1525],
        [1.1556],
        [1.1587],
        [1.1617],
        [1.1648],
        [1.1679],
        [1.1709],
        [1.1740],
        [1.1771],
        [1.1801],
        [1.1832],
        [1.1863],
        [1.1893],
        [1.1924],
        [1.1955],
        [1.1985],
        [1.2016],
        [1.2047]])


*** Save the trained model ***
Saving model to models/trained model
tensor([[True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True],
        [True]])

第一个结果图
第二个结果图

点个赞支持一下咯~

标签:loss,代码,test,PyTorch,train,print,model,True,流程
From: https://blog.csdn.net/BSCHN123/article/details/137010206

相关文章

  • 吴恩达机器学习笔记第六章逻辑回归分析以及代码实现
    第六章对线性代数和导数的要求比之前几章是要高一些的,对于对应的数学知识点我会在下方顺便仔细地指出来并在能力范围内给予一定的推导,尽量保证各位能明白不用再查来查去的,不用重蹈我的覆辙......
  • 会议室预约小程序源码系统 带完整的安装代码包以及搭建教程
    随着企业会议需求的日益增长,会议室预约管理成为了一项不可或缺的工作。为了提高预约效率,减少资源冲突,会议室预约小程序应运而生。小编给大家介绍一款功能强大、易于安装的会议室预约小程序源码系统,带有完整的安装代码包及搭建教程。以下是部分代码示例:系统特色功能一览: ......
  • 盲盒交友小程序源码系统 带完整的代码包以及安装部署教程
    盲盒交友小程序源码系统的开发背景,源于社交媒体的蓬勃发展和年轻用户对于新颖、有趣社交方式的追求。盲盒交友作为一种新型的社交模式,以其神秘感和刺激性,迅速在年轻人中走红。而小程序作为一种轻量级、易上手的应用形式,更是为盲盒交友提供了便捷的传播渠道。因此,盲盒交友小程序......
  • L2-019 悄悄关注 (25分) c++代码
    新浪微博上有个“悄悄关注”,一个用户悄悄关注的人,不出现在这个用户的关注列表上,但系统会推送其悄悄关注的人发表的微博给该用户。现在我们来做一回网络侦探,根据某人的关注列表和其对其他用户的点赞情况,扒出有可能被其悄悄关注的人。输入格式:输入首先在第一行给出某用户的关注......
  • L2-023 图着色问题(25分) c++代码
    还是别把问题想复杂了。。图着色问题是一个著名的NP完全问题。给定无向图G=(V,E),问可否用K种颜色为V中的每一个顶点分配一种颜色,使得不会有两个相邻顶点具有同一种颜色?但本题并不是要你解决这个着色问题,而是对给定的一种颜色分配,请你判断这是否是图着色问题的一个解。输入格......
  • L2-021 点赞狂魔(25分) c++代码
    微博上有个“点赞”功能,你可以为你喜欢的博文点个赞表示支持。每篇博文都有一些刻画其特性的标签,而你点赞的博文的类型,也间接刻画了你的特性。然而有这么一种人,他们会通过给自己看到的一切内容点赞来狂刷存在感,这种人就被称为“点赞狂魔”。他们点赞的标签非常分散,无法体现出明......
  • L2-022 重排链表(25分) c++代码
    给定一个单链表 L1​→L2​→⋯→Ln−1​→Ln​,请编写程序将链表重新排列为 Ln​→L1​→Ln−1​→L2​→⋯。例如:给定L为1→2→3→4→5→6,则输出应该为6→1→5→2→4→3。输入格式:每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址和结点总个数,即正整数N (......
  • 六、使用jsPlumb实现流程图--Overlays使用
    一、Overlay的功能叠层(Overlay)可以是任意的DOM元素,用于叠加在Connection或Endpoint元素上--绝大部分都是用于叠加在线条上。jsPlumb把Overlay分为了五类:Arrow、Label、PlainArrow、Diamond、Custom。除了Custom和Label类型,其他三类就是jsPlumb提供的可以直接使用的图形;Label类......
  • Base64编解码及C++代码实现
    1.Base64是什么?        Base64是一种二进制到文本的编码方式。如果要更具体一点的话,可以认为它是一种将byte数组编码为字符串的方法,而且编码出的字符串只包含ASCII基础字符。        例如字符串mickey0380对应的Base64为bWlja2V5MDM4MA==。其中那个=......
  • 鸿鹄电子招投标系统源码实现与立项流程:基于Spring Boot、Mybatis、Redis和Layui的企业
    随着企业的快速发展,招采管理逐渐成为企业运营中的重要环节。为了满足公司对内部招采管理提升的要求,建立一个公平、公开、公正的采购环境至关重要。在这个背景下,我们开发了一款电子招标采购软件,以最大限度地控制采购成本,提高招投标工作的公开性和透明性,并确保符合国家电子招投标......