Pytorch——Flatten, Reshape, and Squeeze Explained

PyTorch基础(15)-- torch.flatten()方法 前言 最近在复现论文中一个块的时候需要使用到torch.flatten()这个方法,这个方法其实很简单,但其中有一些细节可能需要注意,且有个关键点很容易忘记,故在此记录以备查阅。 方法解析 flatten的中文含义为“扁平化”,具体怎么理解呢?我们可以尝试这么理解,假设你的数据为1维数据,那么这个数据天然就已经扁平化了,如果是2维数据,那么扁平化就是将2维数据变为1维数据,如果是3维数据,那么就要根据你自己所选择的“扁平化程度”来进行操作,假设需要全部扁平化,那么就直接将3维数据变为1维数据,如果只需要部分 阅读详情

Tensor operation types

1.Reshaping operations
2.Element-wise operations
3.Reduction operations
4.Access operations

Reshaping operations for tensors

Tensors are the primary ingredient that neural network programmers use to produce their product, intelligence.Our networks operate on tensors, after all, and this is why understanding a tensor’s shape and the available reshaping operations are super important.
Here is an example:

> t = torch.tensor([
    [1,1,1,1],
    [2,2,2,2],
    [3,3,3,3]
], dtype=torch.float32)

To determine the shape of this tensor, we look first at the rows 3 and then the columns 4, and so this tensor is a 3 x 4 rank 2 tensor. Remember, rank is a word that is commonly used and just means the number of dimensions present within the tensor.

  • We have two ways to get the shape:
    In PyTorch the size and shape of a tensor mean the same thing.
> t.size()
torch.Size([3, 4])

> t.shape
torch.Size([3, 4])
  • The rank of a tensor is equal to the length of the tensor’s shape.
> len(t.shape)
2
  • The number of elements inside a tensor (12 in our case) is equal to the product of the shape’s component values.
> torch.tensor(t.shape).prod()
tensor(12)

In PyTorch, there is a dedicated function for this:

> t.numel()
12

The number of elements contained within a tensor is important for reshaping because the reshaping must account for the total number of elements present. Reshaping changes the tensor’s shape but not the underlying data. Our tensor has 12 elements, so any reshaping must account for exactly 12 elements. 变形只改变张量的形状而不改变内容。

Reshaping a tensor in PyTorch

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

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

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

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

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

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

Using the reshape() function, we can specify the row x column shape that we are seeking. Notice how all of the shapes have to account for the number of elements in the tensor. In our example this is: rows * columns = 12 elements

We can use the intuitive words rows and columns when we are dealing with a rank 2 tensor. The underlying logic is the same for higher dimensional tenors even though we may not be able to use the intuition of rows and columns in higher dimensional spaces.
当我们处理一个二阶张量时,我们可以用直观的词行和列。即使我们可能无法在高维空间中使用行和列的直觉,但对于高维的tensor来说,其基本逻辑是相同的。比如

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

    [
        [2., 2., 3.],
        [3., 3., 3.]
    ]
])

In this example, we increase the rank to 3, and so we lose the rows and columns concept. However, the product of the shape’s components (2,2,3) still has to be equal to the number of elements in the original tensor (12).
Note that PyTorch has another function that you may see called view() that does the same thing as the reshape() function, but don’t let these names through you off. No matter which deep learning framework we are using, these concepts will be the same.

Changing shape by squeezing and unsqueezing

The next way we can change the shape of our tensors is by squeezing and unsqueezing them.

  • Squeezing a tensor removes the dimensions or axes that have a length of one.
  • Unsqueezing a tensor adds a dimension with a length of one.
    These functions allow us to expand or shrink the rank (number of dimensions) of our tensor.这些函数允许我们扩展或缩小张量的秩(维数)。
> print(t.reshape([1,12]))
> print(t.reshape([1,12]).shape)
tensor([[1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.]])
torch.Size([1, 12])

> print(t.reshape([1,12]).squeeze())
> print(t.reshape([1,12]).squeeze().shape)
tensor([1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.])
torch.Size([12])

> print(t.reshape([1,12]).squeeze().unsqueeze(dim=0))
> print(t.reshape([1,12]).squeeze().unsqueeze(dim=0).shape)
tensor([[1., 1., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3.]])
torch.Size([1, 12])

Flatten a tensor

A flatten operation on a tensor reshapes the tensor to have a shape that is equal to the number of elements contained in the tensor. This is the same thing as a 1d-array of elements.
对一个张量进行平坦化操作可以重塑这个张量,使其形状等于张量中包含的元素的数目。这和元素的一维数组是一样的。
Flattening a tensor means to remove all of the dimensions except for one.
Let’s create a Python function called flatten():
The flatten() function takes in a tensor t as an argument.

def flatten(t):
    t = t.reshape(1, -1)
    t = t.squeeze()
    return t

Since the argument t can be any tensor, we pass -1 as the second argument to the reshape() function.
In PyTorch, the -1 tells the reshape() function to figure out what the value should be based on the number of elements contained within the tensor. (-1会让函数自动求出第二个值的大小,在第一个值和元素数量已知的情况下)
Remember, the shape must equal the product of the shape’s component values. This is how PyTorch can figure out what the value should be, given a 1 as the first argument.
因为形状大小必须要和不同维度元素数量的乘积相同,所有以1作为第一个参数值,Pytorch可以计算出第二个数的值

Since our tensor t has 12 elements, the reshape() function is able to figure out that a 12 is required for the length of the second axis.
After squeezing, the first axis (axis-0) is removed, and we obtain our desired result, a 1d-array of length 12.

> t = torch.ones(4, 3)
> t
tensor([[1., 1., 1.],
    [1., 1., 1.],
    [1., 1., 1.],
    [1., 1., 1.]])

> flatten(t)
tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])

We’ll see that flatten operations are required when passing an output tensor from a convolutional layer to a linear layer.

It is possible to flatten only specific parts of a tensor. For example, suppose we have a tensor of shape [2,1,28,28] for a CNN. This means that we have a batch of 2 grayscale images with height and width dimensions of 28 x 28, respectively.
Here, we can specifically flatten the two images to get the following shape: [2,1,784]. We could also squeeze off the channel axes to get the following shape: [2,784].

Concatenating tensors

We combine tensors using the cat() function, and the resulting tensor will have a shape that depends on the shape of the two input tensors.

> t1 = torch.tensor([
    [1,2],
    [3,4]
])
> t2 = torch.tensor([
    [5,6],
    [7,8]
])

# We can combine t1 and t2 row-wise (axis-0) in the following way:
> torch.cat((t1, t2), dim=0)
tensor([[1, 2],
        [3, 4],
        [5, 6],
        [7, 8]])

> torch.cat((t1, t2), dim=0).shape
torch.Size([4, 2])

# We can combine them column-wise (axis-1) like this:
> torch.cat((t1, t2), dim=1)
tensor([[1, 2, 5, 6],
        [3, 4, 7, 8]])

> torch.cat((t1, t2), dim=1).shape
torch.Size([2, 4])

When we concatenate tensors, we increase the number of elements contained within the resulting tensor. This causes the component values within the shape (lengths of the axes) to adjust to account for the additional elements.

SillyTavern角色卡制作全攻略:如何用AI还原你喜欢的虚构角色(附三叶完整角色卡JSON) 本文详细介绍了如何使用SillyTavern制作高质量AI角色卡,以《你的名字》中的宫水三叶为例,从角色特征提取、对话风格捕捉到JSON结构优化,全面解析AI角色扮演的创作技巧。通过具体的写作示例和完整角色卡JSON,帮助二次元爱好者和同人创作者实现虚构角色的精准还原与生动互动。 阅读详情

相关推荐

保姆级教程:在NXPS32144环境下安装EB TRESOS 29.0.0并配置MCAL开发环境

本文提供了一份详细的保姆级教程,指导如何在NXP S32K144环境下安装EB TRESOS 29.0.0并配置MCAL开发环境。内容涵盖从前期资源准备、软件安装步骤、核心的MCAL关联配置,到首次创建AUTOSAR工程并进行模块配置的全流程,旨在帮助汽车电子开发者搭建稳定、可用的底层软件开发地基。

wind6的博客 970

Pytorch常用函数-Flatten

flatten的中文含义为“扁平化”,具体怎么理解呢?我们可以尝试这么理解,假设你的数据为1维数据,那么这个数据天然就已经扁平化了,如果是2维数据,那么扁平化就是将2维数据变为1维数据,如果是3维数据,那么就要根据你自己所选择的“扁平化程度”来进行操作,假设需要全部扁平化,那么就直接将3维数据变为1维数据,如果只需要部分扁平化,那么有一维的数据不会进行扁平操作。torch.flatten()方法有三个参数,分别: 部分扁平化 总结 torch.flatten(x, start_dim, end_di

helloworld_Fly的博客 4618

一文了解英伟达(NVIDIA)所有显卡芯片

英伟达(NVIDIA)的产品线庞杂繁复,从面向游戏玩家的GeForce RTX系列,到数据中心的H100、B200,再到Jetson、DRIVE等边缘智能平台,一般人很难以厘清其全貌。这篇文章将用通俗而专业的语言,一文打通英伟达显卡芯片体系,让你彻底读懂这个GPU帝国是如何运转的。

bjdx_001的博客 6407

Reshapeing operations

Reshapeing operations Suppose we have the following tensor: t = torch.tensor([ [1,1,1,1], [2,2,2,2], [3,3,3,3] ], dtype=torch.float32) We have two ways to get the shape: > t.size() torc...

weixin_30876945的博客 146

从零配置华为S5720交换机VLAN:Web界面与命令行双模式详解(附拓扑图)

本文详细解析华为S5720交换机VLAN配置的全过程,涵盖Web界面与命令行(CLI)双模式操作指南。从基础环境准备到多交换机环境配置同步,特别针对S5720-52X系列交换机的VLANif接口、端口分配策略及交换机堆叠技术进行深入讲解,并附实用拓扑图与配置示例,助力企业网络管理员高效完成VLAN部署。

happy2的博客 1381

MVDR算法: 自适应波束形成在信号处理领域中扮演着重要的角色。本文将介绍MVDR(最小方差无失真响应)算法,并提供相应的Matlab源代码实现。

MVDR算法是一种用于抑制干扰信号并增强感兴趣信号的自适应波束形成算法。它的基本思想是通过对干扰信号进行空间滤波,使其在感兴趣信号方向上的输出功率最小化。这种方法可以提高信号的质量和可辨识度,特别是在存在多个干扰源的复杂环境中。本文将介绍MVDR(最小方差无失真响应)算法,并提供相应的Matlab源代码实现。使用MVDR算法,我们可以通过对观测信号进行波束形成来抑制干扰信号并增强感兴趣信号。以上是MVDR算法的Matlab实现。的每一列代表一个阵列元素的观测信号。表示期望的波束指向,即感兴趣信号的方向。

HackWhisper的博客 1248

深度学习(PyTorch)——flatten函数的用法及其与reshape函数的区别

深度学习(PyTorch)——flatten函数的用法及其与reshape函数的区别

qq_42233059的博客 1万+

CTK Plugin Framework插件框架学习1--Qt编译CTK

【代码】Qt编译CTK。

贝勒里恩的博客 7439

PyTorch中的Flatten

"""将通道维度移到最后的展平层"""# 输入形状: [B, C, H, W]

深之JohnChen的专栏 1682

MATLAB代码实现了一个柱塞泵配流盘过流面积的计算和可视化功能

该MATLAB代码实现了一个柱塞泵配流盘过流面积的计算和可视化功能。输出曲线可直接用于验证设计的合理性(如是否存在过流面积突变或不足)。的不同范围,选择对应的几何模型计算过流面积。通过分段逻辑计算柱塞腔在不同旋转角度(过流面积在特定条件下会被限制(如。),确保结果符合物理实际。条件分支,根据旋转角度。

huanghm88的专栏 590

怎么调用onenet平台的API从而读取我们的设备数据和下发命令,做到控制开关

怎么调用onenet平台的API从而读取我们的设备数据和下发命令,做到控制开关 1、首先是怎么读取数据 读取的API是:http://api.heclouds.com/devices/datapoints?devIds=629063002 其中devids这个指的是你的设备ID 然后在我们的headers里面添加一些必要参数,就可以调用了 其中api-key的是你产品里面的master-apikey 把我们的参数写好就可以调用了,选择get方式,点击发送 这个value就是我们需要获取到的参数值了,

zyh960的博客 2万+

Pytorch基础:Tensor的flatten()方法

本文介绍了PyTorch中flatten()函数/方法的三种返回情况。flatten()用于展平张量维度,可通过参数指定展平范围。其返回结果有三种可能:(1)未展平时返回原张量;(2)能通过view()展平时返回共享存储的视图;(3)否则返回数据副本。通过三个示例演示了这三种情况:未展平时返回同一对象;view展平时返回共享存储的视图;转置张量展平时返回独立副本。文中还提供了相关文章链接,介绍张量连续性和view()方法等基础概念。

保持终身学习的能力,温故而知新 3858

华为OD机试双机位C卷-组装新的数组(Py/Java/C/C++/Js/Go)

华为OD机试(机考)双机位C卷 【组装新的数组】,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试 - 组装新的数组。

qq_45776114的博客 1149

Pytorch详细教程——10.Flatten, Reshape, And Squeeze Explained

因为输入的张量是任何形状的,我们通过-1来表示重塑函数的第二个参数,在pytorch中-1会告诉reshape函数,根据一个张量中的包含的其他值和元素的个数来求出值应该是多少(可以理解为占位符?),因为t有12个元素,这个被重塑的函数能够计算出第二个轴的长度是12个,以确保一个张量中的元素空间足够大。flatten一个tensor意味着除去所有的轴,只保留一个,它创造了一个单轴的张量,它包含了张量的元素,所以本质上是把一个张量拉平,我们创建了一个一维数组,它包含了张量的所有标量分量。...

weixin_43872169的博客 951

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

PyTorch-----torch.flatten()函数

函数会将输入张量的指定维度范围内的所有元素展平到一个一维张量中。展平后的张量保持与原始张量相同的数据顺序。例如,如果输入张量是一个 3x4x5 的三维张量,然后你使用。函数将它展平,那么结果将是一个包含 60 个元素的一维张量,其中包含原始张量中所有的元素。是 PyTorch 中的一个函数,用于将输入张量展平为一维张量。函数将其展平为一个一维张量,并打印出了结果张量的大小。是一个形状为 (3, 4, 5) 的三维张量,使用。

xinxin的博客 2506

深度学习之Pytorch中的flatten()、transpose()和permute()

flatten():压缩维度;transpose():转置(两个维度);permute():按照指定维度排列进行转置(多个维度)

zero_ling 3596

Pytorch中常见调整维度函数总结

函数接受一个或多个参数作为新的形状,并返回一个具有新形状的张量,同时保持张量中的数据不变。这意味着,对于一个具有 12 个元素的张量,你可以将其视图调整为一个形状为 (3, 4) 的二维张量,或者是一个形状为 (2, 2, 3) 的三维张量,只要满足新形状的总元素数量等于原始张量的元素数量。是一个用于改变张量形状的函数,它可以用来调整张量的维度和大小,但不会改变张量中元素的数量。方法来将张量(可以是多维的)平铺为一个一维张量。例如,如果有一个形状为 (3, 4) 的张量,使用。方法将其平铺为一个一维张量。

WSSZJZ的博客 1470

pytorch flatten函数_1. PyTorch中的基本数据类型——张量

在PyTorch中,张量属于一种基本的数据类型,和Numpy库中的ndarry类似,无论是标量、向量、矩阵还是高维数组都是以张量(Tensor)这种数据类型来表示。因此,有必要对该基本数据类型有所了解。(在PyTorch 0.4版本以前,还有个Variable类,主要是用于计算梯度,在后续版本中已经和Tensor合并,本专栏主要以最新的1.7.0版本做实验)目录 1. 张量的数据类型2. 张量的创...

weixin_39646021的博客 1481

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

PyTorch学习笔记

qq_45229186的博客 249

Pytorch阅读文档之flatten函数

pytorch中flatten函数 torch.flatten() #展平一个连续范围的维度,输出类型为Tensor torch.flatten(input, start_dim=0, end_dim=-1) → Tensor # Parameters:input (Tensor) – 输入为Tensor #start_dim (int) – 展平的开始维度 #end_dim (int) – 展...

GhostintheCode的博客 6万+

pytorch flatten函数_pytorch学习笔记(一)——张量

在学习pytorch的用法之前,首先要明白张量的概念及相关用法。数学中定义的张量是基于向量和矩阵的推广,换而言之,标量可视为零阶张量,矢量可视为一阶张量,矩阵可视为二阶张量。在pytorch中,张量Tensor是最基础的运算单位,与NumPy中的NDArray类似,张量表示的是一个多维矩阵,但是pytorch中的张量运算可以运行在GPU,运算速度会大大提高。1、Tensor的秩 张量的秩是指张量中...

weixin_28312391的博客 2837

PyTorch中的flatten+transpose函数说明

a.flatten(m),这个意思是将a这个tensor,从第m(m取值从0开始)维度开始堆叠,一直堆叠到最后一个维度。flatten函数就是对tensor类型进行扁平化处理,就是在不同维度上进行堆叠操作。

ym62033的博客 597

Pytorch教程(十三):reshape、squeeze、flatten

reshape 首先我们创建一个tensor,shape:3×43 \times 43×4,是一个两个轴的二阶张量。第一个轴的长度是3,第二个轴的长度是4,第一个轴的元素是数组,第二个轴的元素是数字 我们可以用torch.size()或者torch.shape来获取形状 张量形状给出的另一个重要特征是张量中包含的元素的个数,也可以通过获取shape中各分量的值乘积来推导出来: 因为我们的元素有12个,因此任何reshape操作都必须考虑这12个元素。 squeeze压缩 squeeze()压缩一个

vincent_duan的专栏 1742

Pytorch详细教程——11.CNN Flatten Operation Visualized

我们看这个变平的结果,我们把所有的图像都映射到了一个单独的轴上面,1代表第一张图的像素,2代表第二张图的像素,3代表第三张图的像素,4代表第四张图的像素,这个flatten的效果不太好,因为所有的图像都被压缩成一个,我们需要对每一个图像进行单独预测,这里的解决方法就是保持批轴的同时使每个图像都变平。第一个轴有三个元素,第一个轴的每个元素代表一个图像,对于每个图像,我们有一个包含单个通道的彩色通道轴,在每个通道轴中我们有四个数组,其中包含四个数字或张量的标量分量。在第一个图像的第一个颜色通道中有第一行像素。.

weixin_43872169的博客 692

Pytorch维度转换操作:view,reshape,permute,flatten函数详解

Pytorch维度转换操作:view,reshape,permute,flatten函数详解

qq_41920323的博客 1793

PyTorch中flatten() 函数的用法

此时x的维度是2×3×4=24,x = flatten(0) 和 x = flatten()的结果相同。被设置为0,表示从第一个维度(通常是批大小)开始展平。如果设置为其他整数值,则会从指定的维度开始展平。1.start_dim(可选参数):指定从哪个维度开始展平张量。被设置为-1,表示展平直到最后一个维度。如果设置为其他整数值,则会在指定的维度结束展平。此时x是从1维度开始展开,最后的x维度为(2,3×4),也就是(2,12)(1). 首先随机定义一个满足正态分布的(2,3,4)的数据x。

纽约恋情的博客 1285
上一篇: Anaconda_python3.6 安装libtiff包
下一篇: Pytorch——CNN Flatten Operation Visualized - Tensor Batch Processing for Deep Learning
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、付费专栏及课程。

余额充值
⌂ 换网址