Pytorch——CNN Flatten Operation Visualized - Tensor Batch Processing for Deep Learning

Deeplizard高效入门pytorch视频教程笔记 9节 4种方法生成tensor Tensor是constructor,使用默认dtype不能指定,其他都是工厂函数可以从input中inference dtype Share Data Copy Data torch.as_tensor() torch.tensor() torch.from_numpy() torch.Tensor() as_tensor()可以接收任何类似于array的input,所以比from_numpy()适用性更广 12节 reduction operati 阅读详情

Flatten operation for a batch of image inputs to a CNN

Flattening an entire tensor

To flatten a tensor, we need to have at least two axes. This makes it so that we are starting with something that is not already flat.
But what if we want to only flatten specific axes within the tensor? This is typically required when working with CNNs

Flattening specific axes of a tensor

Tensor inputs to a convolutional neural network typically have 4 axes, one for batch size, one for color channels, and one each for height and width.

  • (Batch Size, Channels, Height, Width)

Suppose we have the following three tensors.

t1 = torch.tensor([
    [1,1,1,1],
    [1,1,1,1],
    [1,1,1,1],
    [1,1,1,1]
])

t2 = torch.tensor([
    [2,2,2,2],
    [2,2,2,2],
    [2,2,2,2],
    [2,2,2,2]
])

t3 = torch.tensor([
    [3,3,3,3],
    [3,3,3,3],
    [3,3,3,3],
    [3,3,3,3]
])

Each of these has a shape of 4 x 4, so we have three rank-2 tensors. For our purposes here, we’ll consider these to be three 4 x 4 images that well use to create a batch that can be passed to a CNN.
Remember, batches are represented using a single tensor, so we’ll need to combine these three tensors into a single larger tensor that has three axes instead of 2.

> t = torch.stack((t1, t2, t3))
> t.shape

torch.Size([3, 4, 4])

The axis with a length of 3 represents the batch size while the axes of length 4 represent the height and width respectively. This is what the output for this this tensor representation of batch looks like.

> t
tensor([[[1, 1, 1, 1],
         [1, 1, 1, 1],
         [1, 1, 1, 1],
         [1, 1, 1, 1]],

        [[2, 2, 2, 2],
         [2, 2, 2, 2],
         [2, 2, 2, 2],
         [2, 2, 2, 2]],

        [[3, 3, 3, 3],
         [3, 3, 3, 3],
         [3, 3, 3, 3],
         [3, 3, 3, 3]]])

At this point, we have a rank-3 tensor that contains a batch of three 4 x 4 images. All we need to do now to get this tensor into a form that a CNN expects is add an axis for the color channels. We basically have an implicit single color channel for each of these image tensors, so in practice, these would be grayscale images.
A CNN will expect to see an explicit color channel axis, so let’s add one by reshaping this tensor.

 t = t.reshape(3,1,4,4)
> t
tensor(
[
    [
        [
            [1, 1, 1, 1],
            [1, 1, 1, 1],
            [1, 1, 1, 1],
            [1, 1, 1, 1]
        ]
    ],
    [
        [
            [2, 2, 2, 2],
            [2, 2, 2, 2],
            [2, 2, 2, 2],
            [2, 2, 2, 2]
        ]
    ],
    [
        [
            [3, 3, 3, 3],
            [3, 3, 3, 3],
            [3, 3, 3, 3],
            [3, 3, 3, 3]
        ]
    ]
])

The first axis has 3 elements. Each element of the first axis represents an image. For each image, we have a single color channel on the channel axis. Each of these channels contain 4 arrays that contain 4 numbers or scalar components.
We have the first image.

> t[0]
tensor([[[1, 1, 1, 1],
         [1, 1, 1, 1],
         [1, 1, 1, 1],
         [1, 1, 1, 1]]])

We have the first color channel in the first image.

> t[0][0]
tensor([[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]])

We have the first first row of pixels in the first color channel of the first image.

> t[0][0][0]
tensor([1, 1, 1, 1])

We have the first pixel value in the first row of the first color channel of the first image.

> t[0][0][0][0]
tensor(1)

Flattening the tensor batch

Let’s flatten the whole thing first just to see what it will look like.

> t.reshape(1,-1)[0] # Method 1
tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3])

> t.reshape(-1) # Method 2
tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3])

> t.view(t.numel()) # Method 3
tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3])

> t.flatten() # Method 4
tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3])

We want our flattened batch work well inside our CNN, the way to do it is to flatten each image while still maintaining the batch axis. We want to flatten the, color channel axis with the height and width axes.These axes need to be flattened: (C,H,W)

Flattening specific axes of a tensor

从维度1开始,之后的全部被flatten,保留维度0不变

> t.flatten(start_dim=1).shape
torch.Size([3, 16])

> t.flatten(start_dim=1)
tensor(
[
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
    [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
]
)

The start_dim parameter tells the flatten() method which axis it should start the flatten operation. The one here is an index, so it’s the second axis which is the color channel axis.

Flattening an RGB Image

If we flatten an RGB image, each color channel will be flattened first. Then, the flattened channels will be lined up side by side on a single axis of the tensor. Let’s look at an example in code.

# torch.ones()注意
>torch.ones(2,2)
tensor([[1., 1.],
        [1., 1.]])


> torch.ones(1,2,2)
tensor([[[1., 1.],
         [1., 1.]]])

> torch.ones(2, 2, 2)
tensor([[[1., 1.],
         [1., 1.]],
			
	 [1., 1.],
	 [1., 1.]]])

We’ll build an example RGB image tensor with a height of two and a width of two.

r = torch.ones(1,2,2)
g = torch.ones(1,2,2) + 1
b = torch.ones(1,2,2) + 2

img = torch.cat(
    (r,g,b)
    ,dim=0
)

> img.shape
torch.Size([3, 2, 2])

> img
tensor([
    [
        [1., 1.]
        ,[1., 1.]
    ]
    ,[
        [2., 2.]
        , [2., 2.]
    ],
    [
        [3., 3.]
        ,[3., 3.]
    ]
])

> img.flatten(start_dim=0)
tensor([1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.])

> img.flatten(start_dim=1)
tensor([
    [1., 1., 1., 1.],
    [2., 2., 2., 2.],
    [3., 3., 3., 3.]
])
【pytorch】(deeplizard14-21)CNN 加载数据 | 构建神经网络 | 前向传播 p14 fashion-mnist数据集 mnist数据集是一个非常出名的用于训练机器学习的图像处理系统的数据集,这个数据集是由七万张手写的数字图像组成 p15 torchvision——提取、转换、加载流程 torchvision是pytorch的用于深度学习的计算机视觉包 四个步骤: 1、准备数据:E-T-L 提取(extract)-转换(transfrom)-加载(load) 2、构建模型: 3、训练模型、 4、分析模型结果 准备数据 extract:从源获取fas... 阅读详情

相关推荐

Deep_Learning_Pytorch_WithDeeplizard:主要来自Deeplizard的Neural Network Programming - Deep Learning with PyTorch是Deeplizard的中文+Colab版

Deep_Learning_Pytorch_WithDeeplizard 主要来自Deeplizard的 是Deeplizard的中文+Colab版 1_PyTorch Prerequisites - Neural Network Programming Series 简单的介绍这一系列文章所需要的前置知识和将获取的知识 2_PyTorch Explained - Python Deep Learning Neural Network API 简单的介绍了pytorch的历史、特性、优势 3_PyTorch Install - Quick And Easy pytorch的简单安装(建议百度即可) 查看GPU是否可用 torch.cuda.is_available 查看pytorch的版本 torch.version.cuda 4_CUDA Explained - Why Deep Lea

【PyTorch三天速成】——Deeplizard《Pytorch神经网络高效入门教程》

PyTorch学习笔记

qq_45229186的博客 249

.NET MAUI跨平台串口通讯方案

MAUI跨平台串口通信架构设计采用分层模式,核心是共享业务逻辑层与平台特定实现。通过定义统一的ISerialPortService接口,实现了Windows、Android、iOS和macOS四大平台的串口通信功能。Windows平台使用System.IO.Ports类库,Android通过USB Host模式实现,iOS基于ExternalAccessory框架,macOS则采用IOKit。该设计支持串口连接管理、数据收发等核心功能,并通过事件机制实现异步通信。架构采用条件编译区分各平台实现,确保代码复用

冰茶的博客 1670

Deeplizard

pytorch

qq_43645930的博客 297

二、ROS2完成Docker容器和宿主机通信,使用ros2 topic list看到,但是无法echo

如果容器和主机权限不一致,则会导致无法通信(我的代码中,docker容器是root,宿主机是普通用户),虽然可以查询到相关话题,但是订阅后没有消息输出。比如,docker容器创建了一个共享内存,其所有者为docker容器用户root,当宿主机去访问的时候,由于用户不同,没有权限访问,也就无法进行信息传递。该方法只是临时修改共享内存的权限,每次运行完,需要重新运行上述命令,才可以进行通信。在运行的过程中,ROS2使用了共享内存机制,会共享内存。运行之后,宿主机和容器可能用户名不同,这是因为。

qq_43280851的博客 1269

LD14激光雷达与STM32F103C8T6(标准库)获取雷达360度数据(1)

LD14激光雷达与STM32F103C8T6(标准库)获取雷达360度数据(1)

qq_54206194的博客 3906

DeepLizard学习笔记

DeepLizard:油管地址、对应博客笔记 1. 创建tensor 创建tensor的四种方法即不同:具体解释 2. Tensor Operation Types Reshaping operations Element-wise operations Reduction operations Access operations 2.1 Reshaping operations 常见reshape的操作 链接 CNN最后一层的flatten操作() 1)构建 2)Flatten() 这里我们

超喜欢榴莲呀的博客 1217

基于NXP1778的CAN自动波特率检测

一、概念 NXP1778芯片内部自带一个CAN控制器。CAN模块由两部分组成:控制器和验收滤波器。所有的寄存器和RAM都以32位字宽度来访问。 CAN自动波特率检测主要用于以一种CAN的转换的产品中。产品中CAN部分的波特率以前都是通过网页中修改然后配置下去的,依据实际情况的考虑,如果CAN部分的波特率能够根据客户设备的改变而自动改变,将会增加其灵活性。   二、原理 根据CAN控制器的

菜鸟的痕迹专栏 5276

Deeplizard《Pytorch神经网络高效入门教程》笔记

Deeplizard《Pytorch神经网络高效入门教程》笔记 硬件基础:GPU、Cuda GPU比起CPU更适合并行计算 机器学习中的计算多为可分解为并行计算的问题 Cuda是管理GPU的软件API # 查看GPU的设备数量: print(torch.cuda.device_count()) # 使用Cuda之前都需要检测一下cuda是否可用,没检测就默认没有 print(torch.cuda.is_available()) Pytorch可以使用多块GPU,Cuda可以指定GPU索引 为什么不在GP

m0_52009789的博客 1268

【Milvus】实战指南:利用milvus-backup实现高效数据备份与恢复

本文详细介绍了如何利用官方工具milvus-backup为Milvus向量数据库实施高效的数据备份与恢复。文章从备份的必要性出发,逐步讲解了环境准备、配置要点、全量与按需备份操作,以及恢复数据的关键步骤和验证方法,旨在帮助用户构建可靠的数据安全防线,应对误操作或系统故障风险。

weixin_29217235的博客 134

Quest 3开发第一步:搞定Meta账号登录和Oculus软件连不上设备的那些坑(2024实测)

本文详细介绍了Quest 3开发初期的关键步骤,包括Meta账号注册、Oculus软件安装与设备连接等常见问题的解决方案。针对国内开发者遇到的邮箱限制、验证码接收等难题,提供了实用的应对策略,并分享了开发环境配置和常见问题排查技巧,帮助开发者快速搭建Quest 3开发环境。

weixin_30333885的博客 529

DEEPLIZARD强化学习2----预期收益Expected Return

本系列是依据DEEPLIZARD强化学习课程来的,属于对该课程的一些记录和翻译,有能力的话建议阅读原文,翻译成中文就没有那种味道了。课程的地址为: DEEPLIZARD强化学习课程 B站上的视频地址 该博客的原地址 目录预期收益Expected ReturnEpisodic Vs. Continuing Tasks折扣预期收益Discounted Return 预期收益Expected Return 在上一节我们说到,MDP中agent的目标是使累计奖励(cumulative rewards)最大化,我们

五好市民金闪闪的博客 1048

【计算机视觉 | MMDetection】关于mmdetection如何计算参数量、计算量和速度FPS

【计算机视觉 | MMDetection】关于mmdetection如何计算参数量、计算量和速度FPS

wzk4869的博客 3024

pytorch_deeplizard教程学习记录

pytorch_deeplizard教程学习记录 网站链接:https://deeplizard.com/learn/playlist/PLZbbT5o_s2xrfNyHZsM6ufI0iZENK9xgG 一,第一部分1 syllabus of this course2 pytorch的发展和一些包3 安装和配置pytorch4 CUDA的介绍 1 syllabus of this course 主要就是讲了在后续的课程中会学到什么 2 pytorch的发展和一些包 3 安装和配置pytorch 这里主要

qq_29957205的博客 576

C语言实现惯性导航初始对准全部核心代码

惯性导航初始对准包括间接粗对准和卡尔曼滤波精对准,其中。为基于卡尔曼滤波的精对准,其中。

十八与她的博客 2290

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

【DeepLizard】Pytorch神经网络编程学习笔记(第一部分)

1. 笔记为个人学习笔记,如有错误,欢迎指正! 2. 本篇笔记整理的内容为课程的第一部分,对应视频为$P_1\sim P_{13}$ 3. DeepLizard课程为全英文授课,B站视频为中文字幕,且每个视频都有配套的博客与课后测试题。

张壮壮的博客 1669

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

tensor转换为list_【ML实践笔记】04-DeepLizard教程5-7:tensor基本概念

0 前言这个系列主要是写给自己看的,奉行拿来主义,对于学习过程中使用到的优质的学习资源和教程会直接把链接贴进来(省的自己看完忘了),也会附上我的一些学习笔记,同时也记录一下我在学习过程中踩过的各种坑(血泪史),希望能帮助到和我一样刚刚入门的人吧。这个系列称为“实践笔记”,是因为其主要面向编程实践而非理论学习。因为我的基础还是比较差,很多东西只是自己的理解,不一定对,供参考。教程介绍和目录见此文:季...

weixin_39962758的博客 364

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

DEEPLIZARD强化学习3----策略和价值函数

本系列是依据DEEPLIZARD强化学习课程来的,属于对该课程的一些记录和翻译,有能力的话建议阅读原文,翻译成中文就没有那种味道了。课程的地址为: DEEPLIZARD强化学习课程 B站上的视频地址 该博客的原地址 目录策略Police价值方程Value Functions状态价值函数State-Value Function行为价值函数Action-Value Function 策略Police 策略是将给定state映射为从该state中选择每个可能action的概率的函数,用π\piπ表示。如果age

五好市民金闪闪的博客 1352

张量order和rank的概念区分

参考自论文:《Tamara G. Kolda, Brett W. Bader. Tensor Decompositions and Applications. SIAM. 2009》 仅用作个人区别理解。 1、order order即张量维度,论文中解释为The order of a tensor is the number of dimensions, also known as ways or modes。 Nth-order tensor即N-waytensor,higher-order ..

weixin_42621387的博客 3441

Pytorch——PyTorch - Python deep learning neural network API

Pytorch——Deeplizard视频学习(Part1)PyTorch - Python deep learning neural network APIPytorch Install PyTorch - Python deep learning neural network API A tensor is an n-dimensional array. For example, PyTor...

TonyHsuM的博客 1203

Deeplizard pytorch课程学习笔记

本文是学习deeplizard中PyTorch课程做的笔记。

qq_43152622的博客 2259

Pytorch——Broadcasting and Element-wise Operations with PyTorch

Broadcasting and Element-wise Operations with PyTorchElement-wise tensor operations for deep learningAddition is an element-wise operationArithmetic operations are element-wise operationsBroadcasting ...

TonyHsuM的博客 688

Pytorch——PyTorch Tensors Explained - Neural Network Programming

Pytorch——Deeplizard视频学习(Part2)PyTorch Tensors Explained - Neural Network ProgrammingInstances of the *torch.Tensor* classTensor attributesTensors have a *torch.dtype*Tensors have a *torch.device*Tenso...

TonyHsuM的博客 434

Deeplizard part1

torch:包含其它 torch.nn:包含类的模块、权重、和损失函数 torch.autograd:优化我们的神经网络权重所需的导数计算 torch.nn.functional:各种函数,损失、激活、卷积 torch.optim:各种优化SGD.ADAM torch.utils:数据预处理 torchvision:访问最新的数据集、计算机视觉的模型架构以及图像转换 CUDA:为开发者提供API的软件层。 GPU:适合并行计算,运算速度超过CPU,但是从CPU向GPU中导入数据需要一定的代价。 ...

qq_43444151的博客 253

让PyTorch训练速度更快,你需要掌握这17种方法

作者|LORENZ KUHN来源|机器之心编译掌握这 17 种方法,用最省力的方式,加速你的 Pytorch 深度学习训练。近日,Reddit 上一个帖子热度爆表。主题内容是关于怎样加...

Paper weekly 2131

Pytorch——CNN Image Preparation Code Project - Learn to Extract, Transform, Load -------ETL

CNN Image Preparation Code Project - Learn to Extract, Transform, Load -------ETLThe project (Bird's-eye view)The ETL processPyTorch importsPreparing our data using PyTorchPyTorch Dataset classPyTorch...

TonyHsuM的博客 577
上一篇: Pytorch——Flatten, Reshape, and Squeeze Explained
下一篇: Pytorch——Broadcasting and Element-wise Operations with PyTorch
Logan322
博客等级 码龄9年 55粉丝 41原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Logan322

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址