Introduction to Deep Learning with PyTorch

news2024/9/21 20:41:30

1、Introduction to PyTorch, a Deep Learning Library

1.1、Importing PyTorch and related packages

import torch

# supports:
## image data with torchvision
## audio data with torchaudio
## text data with torchtext

1.2、Tensors: the building blocks of networks in PyTorch

1.2.1、Load from list

import torch

lst = [[1,2,3], [4,5,6]]
tensor = torch.tensor(lst)

1.2.2、Load from NumPy array

np_array = np.array(array)
np_tensor = torch.from_numpy(np_array)

1.3、Creating our first neural network

1.3.1、A basic, two-layer network with no hidden layers

import torch.nn as nn

# Create input_tensor with three features
input_tensor = torch.tensor([0.3471, 0.4547, -0.2356])

# Define our first linear layer
linear_layer = nn.Linear(in_features=3, out_features=2

# Pass input through linear layer
output = linear_layer(input_tensor)



# Show the output
print(output)

# Each linear layer has a .weight and .bias property
linear_layer.weight
linear_layer.bias
  • Networks with only linear layers are called fully connected networks.

1.3.2、Stacking layers with nn.Sequential()

# Create network with three linear layers
model = nn.Sequential(
    nn.Linear(10,18),
    nn.Linear(18,20),
    nn.Linear(20, 5),
)

1.4、Discovering activation functions

  • Activation functions add non-linearity to the network.
  • A model can learn more complex relationships with non-linearity.
  • Two-class classification: Sigmoid function demo:

     
    import torch
    import torch.nn as nn
    
    input_tensor = torch.tensor([[6.0]])
    sigmoid = nn.Sigmoid()
    output = sigmoid(input_tensor)
    
    # tensor([[0.9975]])
  • Application for Sigmoid function:
    model = nn.Sequential(
        nn.Linear(6,4),
        nn.Linear(4,1),
        nn.Sigmoid()
    )
  • Multi-class classification: Softmax demo:

     
    import torch
    import torch.nn as nn
    
    input_tensor = torch.tensor([[4.3, 6.1, 2.3]])
    
    # dim=-1 indicates softmax is applied to the input tensor's last dimension
    # nn.Softmax() can be used as last step in nn.Sequential()
    probabilities = nn.Softmax(dim=-1)
    output_tensor = probabilities(input_tensor)
    
    print(output_tensor)
    
    # tensor([[0.1392, 0.8420, 0.0188]])

2、Training Our First Neural Network with PyTorch

2.1、Running a forward pass

2.1.1、Forward pass

  • Input data is passed forward or propagated through a network.
  • Coputations performed at each layer.
  • Outputs of each layer passed to each subsequent layer.
  • Output of final layer: "prediction".
  • Used for both training and prediction.
  • Some possible outputs:

2.1.2、Backward pass

2.1.3、Binary classification: forward pass

2.1.4、Multi-class classification: forward pass

2.1.5、Regression: forward pass

2.2、Using loss functions to assess model predictions

2.2.1、Why we need a loss function?

  • Give feedback to model during training.
  • Take in model prediction \hat{y} and ground truth {y} .
  • Output a float.

2.2.2、One-hot encoding concepts

import torch.nn.functional as F

F.one_hot(torch.tensor(0), num_classes = 3)
# tensor([1,0,0]) --- first class

F.one_hot(torch.tensor(1), num_classes = 3)
# tensor([0,1,0]) --- second class

F.one_hot(torch.tensor(2), num_classes = 3)
# tensor([0,0,1]) --- third class

2.2.3、Cross entropy loss in PyTorch

from torch.nn import CrossEntropyLoss

scores = tensor([[-0.1211, 0.1059]])
one_hot_target = tensor([[1, 0]])

criterion = CrossEntropyLoss()
criterion(scores.double(), one_hot_target.double())
# tensor(0.8131, dtype=torch.float64)

2.2.4、Bringing it all together

2.3、Using derivatives to update model parameters

2.3.1、Minimizing the loss

  • High loss: model prediction is wrong
  • Low loss: model prediction is correct

2.3.2、Connecting derivatives and model training

2.3.3、Backpropagation concepts

2.3.4、Gradient descent

2.4、Writing our first training loop

2.4.1、Training a neural network

2.4.2、Mean Squared Error (MSE) Loss

2.4.3、Before the training loop

2.4.4、The training loop

3、Neural Network Architecture and Hyperparameters

3.1、Discovering activation functions between layers

3.1.1、Limitations of the sigmoid and softmax function

3.1.2、Introducing ReLU

3.1.3、Introducing Leaky ReLU

3.2、A deeper dive into neural network architecture

3.2.1、Counting the number of parameters

3.3、Learning rate and momentum

3.4、Layer initialization and transfer learning

3.4.1、Layer initialization

3.4.2、Transfer learning and fine tuning

4、Evaluating and Improving Models

4.1、A deeper dive into loading data

4.1.1、Recalling TensorDataset

4.1.2、Recalling DataLoader

4.2、Evaluating model performance

4.2.1、Model evaluation metrics

4.2.2、Calculating training loss

4.2.3、Calculating validation loss

4.2.4、Calculating accuracy with torchmetrics

4.3、Fighting overfitting

4.4、Improving model performance

  • Overfit the training set
  • Reduce overfitting
  • Fine-tune the hyperparameters

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

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

相关文章

磁盘加密工具 | VeraCrypt v1.26.15 绿色版

VeraCrypt 是一个开源项目,旨在提供强大的加密解决方案,以创建和管理加密的磁盘分区和加密容器。它继承了著名的加密软件 TrueCrypt 的特性,并在此基础上进行了扩展和改进。 主要特性 1. 高级加密算法 VeraCrypt 支持多种加密算法&#xf…

假如你是HR,你怎么招「游戏策划」?

你是一名从业十余年, 拥有丰富面试经历、掌握多种话术的 资深游戏行业人事。 想知道策划岗位该怎么入行可点击蓝链 你不满足于在名不见经传的小企业 拿一份凑合过的薪资, 于是你成功跳槽来到国内顶级游戏大厂“猪厂”, 并且接手了你的…

Redis集群技术1——nosql简述

一、关系型数据库和 NoSQL 数据库 1.1 数据库主要分为两大类:关系型数据库与 NoSQL 数据库 关系型数据库,是建立在关系模型基础上的数据库,其借助于集合代数等数学概念和方法来处理数据库 中的数据主流的 MySQL、Oracle、MS SQL Server 和 …

谷歌排名SEO优化#蜘蛛池软件(搜索大客户)

谷歌排名SEO优化#蜘蛛池软件(搜索大客户) 如何检测你的网站是否能被谷歌搜索引擎蜘蛛抓取 通过一个工具快速检测你的网站,是否能被谷歌搜索引擎,bing搜索引擎的蜘蛛爬取收录。网站是否能被蜘蛛抓取收录是谷歌SEO的基础&#xff0…

C_深入理解指针(五) —— sizeof和strlen的对比、数组和指针笔试题解析、指针运算笔试题解析

目录 一、sizeof和strlen的对比 1、sizeof 2、strlen 3、sizeof 和 strlen的对比 二、数组和指针笔试题解析 1、⼀维数组 重点学习代码:sizeof与一维整型数组类型 2、字符数组 代码1:sizeof与字符数组类型 代码2:strlen与字符数组类…

log4j 和 java.lang.OutOfMemoryError PermGen space

还是OneCoder在项目中沙箱的问题,用classloader隔离做的沙箱,反复运行用户的任务,出现永生区内存溢出: java.lang.OutOfMemoryError: PermGen space 这个问题在tomcat重复热部署的时候其实比较常见。其道理也和我们沙箱的道理基本…

【重学 MySQL】十二、SQL 语言的规则与规范

【重学 MySQL】十二、SQL 语言的规则与规范 基本规则注释语法规则命名规则基本命名规则具体命名规范其他注意事项 数据导入指令 SQL(Structured Query Language,结构化查询语言)的规则与规范是确保SQL语句能够正确执行、提高代码可读性和可维…

HarmonyOS开发实战( Beta5.0)Native Drawing自绘制能力替代Canvas提升性能

简介 Canvas 画布组件是用来显示自绘内容的组件,它具有保留历史绘制内容、增量绘制的特点。Canvas 有 CanvasRenderingContext2D/OffscreenCanvasRenderingContext2D 和 DrawingRenderingContext 两套API,应用使用两套API绘制的内容都可以在绑定的 Canv…

语音测试(一)ffmpeg视频转音频

视频转音频 下载ffmpeg工具进入bin目录cmd进入控制台输入命令 ffmpeg.exe -i ./视频.mp4 ./音频.wav命令说明 ffmpeg -i input.mp4 output.mkv FFmpeg 可能会尝试自动选择合适的编码器对视频和音频进行重新编码,以便适应 MKV 格式的要求ffmpeg -i input.mp4 -c c…

Java项目:140 springboot203医疗挂号管理系统

作者主页:舒克日记 简介:Java领域优质创作者、Java项目、学习资料、技术互助 文中获取源码 项目介绍 一共有管理员、挂号人员、划价人员、医生 四个角色 管理员登录进入本系统操作的功能包括对挂号人员,划价人员,患者&#xff0…

初始QT!

作业:了解QT文件夹初始代码的意义 QT core gui #QT工程所需得类库 core是核心库 gui图形化界面相关库类 greaterThan(QT_MAJOR_VERSION, 4): QT widgets #版本超过4.0会加上widgetsCONFIG c11 #该编辑器支持c11后的版本 # The following define makes you…

ngrok forward本地argocd并设置为github repo webhook

为什么需要ngrok 我们刚学了argocd的安装和部署应用,但是argocd什么时候部署部署我们的应用,就取决于repo的sync机制。我们采用以下cmd设置为autosync。 argocd app list # to get our app argocd app set argocd/tekton-learning-nginx --sync-polic…

小试牛刀-SOL链创建Token

目录 1.编写目的 2.账户结构 3.环境及使用依赖 4.步骤分解 4.1.导入相关依赖 4.2. 初始化变量 4.3. 创建并初始化Mint Account 4.4. 创建并初始化Metadata Account 4.5. 发送创建和初始化mint Account 4.6 铸造Token 5.源码分享 Welcome to Code Blocks blog 本篇文…

震惊,从仿真走向现实,3D Map最大提升超12,Cube R-CNN使用合成数据集迁移到真实数据集

震惊,从仿真走向现实,3D Map最大提升超12,Cube R-CNN使用合成数据集迁移到真实数据集 Abstract 由于摄像机视角多变和场景条件不可预测,在动态路边场景中从单目图像中准确检测三维物体仍然是一个具有挑战性的问题。本文介绍了一…

基于飞桨paddle2.6.1+cuda11.7+paddleRS开发版的目标提取-道路数据集训练和预测代码

基于飞桨paddle2.6.1cuda11.7paddleRS开发版的目标提取-道路数据集训练和预测代码 预测结果: 预测影像: (一)准备道路数据集 下载数据集地址: https://aistudio.baidu.com/datasetdetail/56961 mass_road.zip …

国际标准图像分辨率测试ISO12233 - 2017中文翻译

参考:https://blog.csdn.net/jgw2008/article/details/116519404?spm1035.2023.3001.6557&utm_mediumdistribute.pc_relevant_bbs_down_v2.none-task-blog-2~default~OPENSEARCH~Rate-2-116519404-bbs-392397517.264^v3^pc_relevant_bbs_down_v2_default&d…

SpringBoot与Minio的极速之旅:解锁文件切片上传新境界

目录 一、前言 二、对象存储(Object Storage)介绍 (1)对象存储的特点 (2)Minio 与对象存储 (3)对象存储其他存储方式的区别 (4)对象存储的应用场景 三、…

万龙觉醒辅助:VMOS云手机助力资源采集!挂机升级!

《万龙觉醒》是一款策略型游戏,玩家需要合理规划资源采集、建筑升级、科技研发等来提升实力。在本文中,我们将为您提供一篇详细的游戏辅助攻略,并介绍如何使用VMOS云手机来提升您的游戏体验,实现24小时的自动化管理。 使用VMOS云…

R3M: A Universal Visual Representation for Robot Manipulation

R3M [25] explores how visual representations obtained by training on diverse human video data using time-contrastive learning and video-language can enable data-efficient learning(实际上就是小样本学习) of downstream robotic manipulati…

【FreeRTOS】事件组实验-改进姿态控制

目录 0 前言1 事件组实验_改进姿态控制2 改进思路2.1 创建事件2.2 等待事件2.3 设置事件2.4 Debug2.5 设置MPU6050寄存器 3 总结 0 前言 学习视频: 【FreeRTOS 入门与工程实践 --由浅入深带你学习 FreeRTOS(FreeRTOS 教程 基于 STM32,以实际项…