机器学习 - 训练模型

接着这一篇博客做进一步说明:
机器学习 - 选择模型

为了解决测试和预测之间的差距,可以通过更新 internal parameters, the weights set randomly use nn.Parameter() and bias set randomly use torch.randn().
Much of the time you won’t know what the ideal parameters are for a model.
Instead, it is much more fun to write code to see if the model can try and figure them out itself. That is a loss function as well as and optimizer.

FunctionWhat does it do?Where does it live in PyTorch?Common values
Loss functionMeasures how wrong your models predictions (e.g. y_preds) are compared to the truth labels (e.g. y_test). Lower the better.差距越小越好PyTorch has plenty of built-in loss functions in torch.nnMean absolute error (MAE) for regression problems (torch.nn.L1Loss()). Binary cross entropy for binary classification problems (torch.nn.BCELoss())
OptimizerTells your model how to update its internal parameters to best lower the loss.You can find various optimization function implementations in torch.optimStochastic gradient descent (torch.optim.SGD()). Adam.optimizer (torch.optim.Adam())

介绍 MAE: Mean absolute error 也称为平均绝对误差,是一种用于衡量预测值与真实值之间差异的损失函数。MAE计算的是预测值与真实值之间的绝对差值的平均值,即平均误差的绝对值。在 PyTorch 中可以使用 torch.nn.L1Loss 来计算MAE.

介绍Stochastic gradient descent:
这是一种常用的优化算法,用于训练神经网络模型。它是梯度下降算法的变种,在每次更新参数时都使用随机样本的梯度估计来更新参数。SGD的基本思想是通过最小化损失函数来调整模型参数,使得模型的预测结果与真实标签尽可能接近。在每次迭代中,SGD随机选择一小批样本 (mini-batch) 来计算损失函数关于参数的梯度,并使用该梯度来更新参数。由于每次更新只使用了一部分样本,因此SGD通常具有更快的收敛速度和更低的计算成本。在 PyTorch 中,可以使用 torch.optim.SGD(params, lr) 来实现,其中

  • params is the target model parameters you’d like to optimize (e.g. the weights and bias values we randomly set before).
  • lr is the learning rate you’d like the optimizer to update the parameters at, higher means the optimizer will try larger updates (these can sometimes be too large and the optimizer will fail to work), lower means the optimizer will try smaller updates (these can sometimes be too small and the optimizer will take too long to find the ideal values). Common starting values for the learning rate are 0.01, 0.001, 0.0001.

介绍 Adam 优化器:
Adam优化器是一种常用的优化算法,它结合了动量法和自适应学习率调整的特性,能够高效地优化神经网络模型的参数。Adam优化器的基本思想是在梯度下降的基础上引入了动量项和自适应学习率调整项。动量项可以帮助优化器在更新参数时保持方向性,从而加速收敛;而自适应学习率调整项可以根据参数的历史梯度来调整学习率,从而在不同参数上使用不同的学习率,使得参数更新更加稳健。

介绍学习率:
学习率是在训练神经网络时控制参数更新步长的一个超参数。它决定了每次参数更新时,参数沿着梯度方向更新的程度。学习率越大,参数更新的步长越大;学习率越小,参数更新的步长越小。选择合适的学习率通常是训练神经网络时需要调节的一个重要超参数。如果学习率过大,可能导致参数更新过大,导致模型不稳定甚至发散;如果学习率过小,可能导致模型收敛速度过慢,训练时间变长。

代码如下:

import torch# Create the loss function 
loss_fn = nn.L1Loss()  # MAE loss is same as L1Loss# Create the optimizer
optimizer = torch.optim.SGD(params = model_0.parameters(),lr = 0.01)

现在创造一个optimization loop
The training loop involves the model going through the training data and learning the relationships between the features and labels.
The testing loop involves going through the testing data and evaluating how good the patterns are that the model learned on the training data (the model never sees the testing data during training).
Each of these is called a “loop” because we want our model to look (loop through) at each sample in each dataset. 所以,得用 for 循环来实现。

PyTorch training loop

NumberStep nameWhat does it do?Code example
1Forward passThe model goes through all of the training data once, performing its forward() function calculations.model(x_train)
2Calculate the lossThe model’s outputs (predictions) are compared to the ground truth and evaluated to see how wrong they are.loss = loss_fn(y_pred, y_train)
3Zero gradientsThe optimizers gradients are set to zero (they are accumulated by default) so they can be recalculated for the specific training step.optimizer.zero_grad()
4Perform backpropagation on the lossComputes the gradient of the loss with respect for every model parameter to be updated (each parameter with requires_grad=True). This is known as backpropagation, hence “backwards”.loss.backward()
5Update the optimizer (gradient descent)Update the parameters with requires_grad=True with respect to the loss gradients in order to improve them.optimizer.step()

PyTorch testing loop
As for the testing loop (evaluating the model), the typical steps include:

NumberStep nameWhat does it do?Code example
1Forward passThe model goes through all of the training data once, performing its forward() function calculations.model(x_test)
2Calculate the lossThe model’s outputs (predictions) are compared to the ground truth and evaluated to see how wrong they are.loss = loss_fn(y_pred, y_test)
3Calculate evaluation metrics (optional)Alongside the loss value you may want to calculate other evaluation metrics such as accuracy on the test set.Custom functions

下面是代码实现

# Create the loss function
# 那你。L1Loss() 是用于计算平均绝对误差 (MAE) 的损失函数。
loss_fn = nn.L1Loss()  # MAE loss is same as L1Loss# Create the optimizer
# torch.optim.SGD() 是用于创建随机梯度下降优化器的函数。
# parameters() 返回一个包含了模型中所有需要进行梯度更新的参数的迭代器
optimizer = torch.optim.SGD(params = model_0.parameters(),lr = 0.01)# Set the number of epochs (how many times the model will pass over the training data)
epochs = 200# Create empty loss lists to track values
train_loss_values = []
test_loss_values = []
epoch_count = []for epoch in range(epochs):### Training # Put model in training mode (this is the default state of a model)# train() 函数通常用于将模型设置为训练模式model_0.train()# 1. Forward pass on train data using the forward() method insidey_pred = model_0(X_train)# 2. Calculate the loss (how different are our models predictions to the ground truth)loss = loss_fn(y_pred, y_train)# 3. Zero grad of the optimizeroptimizer.zero_grad() # 4. Loss backwardsloss.backward()# 5. Progress the optimizer# step() 用于执行一步参数更新操作。optimizer.step() ### Testing# Put the model in evaluation modemodel_0.eval() with torch.inference_mode():# 1. Forward pass on test data test_pred = model_0(X_test)# 2. Calculate loss on test data test_loss = loss_fn(test_pred, y_test.type(torch.float))  # predictions come in torch.float datatype, so comparisons need to be done with tensors of the same type # Print out if epoch % 10 == 0:epoch_count.append(epoch)# detach() 方法用于将这个张量从计算图中分离出来,目的是为了避免在将张量转换为numpy数组时保留计算图的依赖关系,减少内存占用并加速代码的执行train_loss_values.append(loss.detach().numpy())test_loss_values.append(test_loss.detach().numpy())print(f"Epoch: {epoch} | MAE Train Loss: {loss} | MAE Test Loss: {test_loss}")plt.plot(epoch_count, train_loss_values, label="Train loss")
plt.plot(epoch_count, test_loss_values, label="Test loss")
plt.title("Training and test loss curves")
plt.ylabel("Loss")
plt.xlabel("Epochs")
plt.legend()print("The model learned the following values for weights and bias: ")
print(model_0.state_dict())
print("\nAnd the original values for weights and bias are: ")
print(f"weights: {weight}, bias: {bias}")# 结果如下:
Epoch: 0 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 10 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 20 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 30 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 40 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 50 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 60 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 70 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 80 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 90 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 100 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 110 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 120 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 130 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 140 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 150 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 160 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 170 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 180 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
Epoch: 190 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882
The model learned the following values for weights and bias: 
OrderedDict([('weights', tensor([0.6990])), ('bias', tensor([0.3093]))])And the original values for weights and bias are: 
weights: 0.7, bias: 0.3

Loss is the measure of how wrong your model is. Loss 的值越低,效果越好。

效果图

都看到这了,点个赞支持下呗~

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/764903.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

STM32之HAL开发——手动移植HAL库

HAL库移植步骤 创建目录 配置启动文件 在\Drivers\CMSIS\Device\ST\stm32f1xx\Source\Templates\ARM目录下,根据你的芯片型号选择对应的启动文件,不同容量大小的芯片,对应的启动文件也不一样。 注意:在HAL库中,不同容…

HTML网页文档和DOM结构介绍

HTML网页文档和DOM结构介绍 HTML网页文档 HTML,全称为超文本标记语言(Hypertext Markup Language),是用来描述并定义内容结构的标记语言,它是构建任何网页和网络应用的最基础的组成部分。HTML文档由一系列的元素构成…

[SAP ABAP] SE11查询数据库表中的数据

我们可以通过事务码SE11查询对应数据库表中的详细数据 本次查询使用的数据库表名为MARA,具体操作如下所示: ① 输入事务码SE11进入ABAP字典操作界面,在数据库表搜索框中输入目标表名MARA,并点击【显示】按钮 ② 进入到显示表界面&#xff0…

c++翁恺

1、面向对象 Data:杯子的属性 Opera:杯子提供的服务 老师上课: C:按流程执行 C:定一个教室,有很多学生,投影仪,灯,每个学生反映不一样。 这个场景有什么东西&#xff0c…

关于Rust的项目结构的笔记

层级 PackageCrateModulePath Package cargo的特性, 构建、测试、共享Crate 组成: 一个 Cargo.toml 文件, 描述了如何构建这些 Crates至少包含一个 crate最多只能包含一个 library crate可以包含任意个 binary crate cargo new demo-pro 会产生一个名为 demo-pro 的 Packa…

【C语言】linux内核pci_set_master

一、__pci_set_master static void __pci_set_master(struct pci_dev *dev, bool enable) {u16 old_cmd, cmd;pci_read_config_word(dev, PCI_COMMAND, &old_cmd); // 读取设备的PCI命令寄存器的当前值if (enable)cmd old_cmd | PCI_COMMAND_MASTER; // 如果要启用总线…

力扣● 503.下一个更大元素II ● 42. 接雨水

503.下一个更大元素II 与496.下一个更大元素 I的不同是要循环地搜索元素的下一个更大的数。那么主要是对于遍历结束后,单调栈里面剩下的那些元素。 如果直接把两个数组拼接在一起,然后使用单调栈求下一个最大值就可以。 代码实现的话,不用直…

蓝桥杯练习——神秘咒语——axios

目标 完善 index.js 中的 TODO 部分,通过新增或者修改代码,完成以下目标: 点击钥匙 1 和钥匙 2 按钮时会通过 axios 发送请求,在发送请求时需要在请求头中添加 Authorization 字段携带 token,token 的值为 2b58f9a8-…

瑞_23种设计模式_状态模式

文章目录 1 状态模式(State Pattern)1.1 介绍1.2 概述1.3 状态模式的结构1.4 状态模式的优缺点1.5 状态模式的使用场景 2 案例一2.1 需求2.2 代码实现(未使用状态模式)2.3 代码实现(状态模式) 3 案例二3.1 …

[BT]BUUCTF刷题第4天(3.22)

第4天(共两题) Web [极客大挑战 2019]Upload 这是文件上传的题目,有一篇比较详细的有关文件上传的绕过方法文件上传漏洞详解(CTF篇) 首先直接上传带一句话木马的php文件,发现被拦截,提示不是图…

Linux安装Nacos

安装前必要准备 准备Java环境 ,8以上的版本,mysql(集群相关信息),nginx(进行代理) 安装Nacos 首先我们要有一个nacos的包,我们可以在线下载,也可以提前下载好&#xf…

Nginx 全局块配置 worker 进程的两个指令

1. 前言 熟悉 nginx 运行原理的都知道,nginx 服务启动后,会有一个 master 进程和多个 worker 进程,master 进程负责管理所有的 worker 进程,worker 进程负责处理和接收用户请求 在这里我们所要研究的是 master 进程一定要创建 wo…

如何进行设备的非对称性能测试

非对称性能测试介绍 RFC2544是RFC组织提出的用于评测网络互联设备(防火墙、IDS、Switch等)的国际标准。主要是对RFC1242中定义的性能评测参数的具体测试方法、结果的提交形式作了较详细的规定。标准中定义了4个重要的参数:吞吐量&#xff08…

Uni-app/Vue/Js本地模糊查询,匹配所有字段includes和some方法结合使用e

天梦星服务平台 (tmxkj.top)https://tmxkj.top/#/ 1.第一步 需要一个数组数据 {"week": "全部","hOutName": null,"weekendPrice": null,"channel": "门市价","hOutId": 98,"cTime": "…

打造新质生产力,亚信科技2024年如何行稳致远?

引言:不冒进、不激进,稳扎稳打, 一个行业一个行业地深度拓展。 【全球云观察 | 科技热点关注】 基于以往“一巩固、三发展”的多年业务战略,亚信科技正在落实向非通信行业、标准产品、软硬一体产品和国际市场的“四…

Spring异步注解@Async线程池配置

系列文章目录 文章目录 系列文章目录前言前言 前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看懂了就去分享给你的码吧。 从Spring3开始提供了@Async注解,该注解可以被标注在方法上,以便异步地调…

多段智能功率分配,双设备同时快充,乐得瑞LDR6020 一分拖二PD 快充线方案

随着移动设备的普及和功能的日益增强,电池续航成为了用户关注的重点之一。为了满足用户对于快速充电的需求,各大厂商纷纷推出了各种快充技术和产品。在这个背景下,乐得瑞公司推出了一款名为LDR6020的一分二PD快充线方案,该方案采用…

处理登录失效后提示多个错误

问题: 我的场景是后端规定,即使登录失效返回的code仍是200,然后data的code是999什么的; 原本代码: 修改版代码: 通过节 const NotLoginEvent () > {router.replace("/login");localStorage.clear();M…

python的ITS 信息平台的设计与实现flask-django-nodejs-php

第二,陈列说明该系统实现所采用的架构、系统搭建采用的服务器、系统开发环境和使用的工具,以及系统后台采用的数据库。 最后,对系统进行全面测试,主要包括功能测试、查询性能测试、安全性能测试。 分析系统存在的不足以及将来改进…

ios symbolicatecrash 符号化crash

一、准备 1.1 .crash 文件获取 设备连接电脑 打开XCode, 依次 XCode -> Windows -> Device and Simulator -> Open Recent Logs 找到 (对应app名+时间点) -> 右键 Show in Finder 1.2 .dSYM 和 .app 文件获取 .dSYM是十六进制函数地址映射信息的中转文件,调试的…