Pytorch view函数讲解

通讯软件013——分分钟学会Kepware OPC AE Server仿真配置 本文介绍如何使用Kepware软件仿真OPC AE Server配置。 阅读详情

view()函数作用和reshape函数类似,就是对tensor的shape进行调整,可以通过view函数将tensor的shape调整成一个你希望的样子。

import torch

torch.manual_seed(2)
a=torch.randn(4,5)
print(a)

print(a.view(-1,2)) # 此时 -1,代表默认值,代表根据后面的列数来计算行数


'''
a
=
tensor([[-1.0408,  0.9166, -1.3042, -1.1097,  0.0299],
        [-0.0498,  1.0651,  0.8860, -0.8110,  0.6737],
        [-1.1233, -0.0919,  0.1405,  1.1191,  0.3152],
        [ 1.7528, -0.7396, -1.2425, -0.1752,  0.6990]])


a.view(-1,2)
=
tensor([[-1.0408,  0.9166],
        [-1.3042, -1.1097],
        [ 0.0299, -0.0498],
        [ 1.0651,  0.8860],
        [-0.8110,  0.6737],
        [-1.1233, -0.0919],
        [ 0.1405,  1.1191],
        [ 0.3152,  1.7528],
        [-0.7396, -1.2425],
        [-0.1752,  0.6990]])
'''

此时通过view调整,将一个 45,一共20个数字,变成了 102 (10为 view中 -1的默认数,代表按照后面的列数来计算的行数)

在训练神经网络时,经常会遇到这样的一段代码

x = x.view(x.size(0), -1)

x.size(0)指batchsize的值。这句话的出现就是为了将前面多维度的tensor展平成一维,然后再输入给 nn.Linear()结构,-1指在不告诉函数有多少列的情况下,根据原tensor数据和batchsize自动分配列数。

一桶令牌的时间账本:四类限流算法的边界推演与Guava RateLimiter源码精读 限流的难点不在背出算法名,而在算清每一笔账:按哪一秒计数、超额请求排队还是拒绝、空闲后能否突发、集群总量如何约束。本文在可复现的虚拟时间实验台上对比固定窗口、滑动窗口、漏桶与令牌桶,实测边界双倍突发与分桶滑动的真实上界,拆解Nginx limit_req的千分位记账与延迟机制,纠正Resilience4j常被误称漏桶的说法,并逐行精读Guava SmoothRateLimiter的预消费、懒惰补账与预热积分,复刻迷你限流器与其完成七万次零差异对账,最后给出集群配额、分层防护与参数确定的方法。 阅读详情

相关推荐

易康eCognition9.0分类|规则集和机器学习的方法的面向对象的多尺度分割分类

基于易康eCognition9.0软件的规则集和机器学习的方法的面向对象的多尺度分割分类

weixin_46493028的博客 1万+

Pytorch学习笔记(六):view()和nn.Linear()函数详解

相关文章 Pytorch学习笔记(一):torch.cat()模块的详解 Pytorch学习笔记(二):nn.Conv2d()函数详解 Pytorch学习笔记(三):nn.BatchNorm2d()函数详解 Pytorch学习笔记(四):nn.MaxPool2d()函数详解 Pytorch学习笔记(五):nn.AdaptiveAvgPool2d()函数详解 Pytorch学习笔记(六):out.view(out.size(0), -1)和nn.Linear()函数详解 文章目录1.函数语法格式和作用2.

源的博客 6765

洛谷 P5736 【深基7.例2】质数筛

题目描述 输入 n(n\le100)n(n≤100) 个不大于 100000 的整数。要求全部储存在数组中,去除掉不是质数的数字,依次输出剩余的质数。 输入格式 无 输出格式 无 输入输出样例 输入 #1 复制 5 3 4 5 6 7 输出 #1 复制 3 5 7 板子题,使用一下线性筛 #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using n

qq_37978559的博客 1117

pytorch 中的view 参数使用方法

最近在看pytorch 代码时发现了使用了view 这个参数。一开始还不知道是啥。查看之后发现原来跟 keras 中的flat和reshape 类似。 class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) ...

skyfengye的博客 3465

通过python+openCV实现对图片中箭头方向的判断

摘要: 针对YOLOv8算法在箭头方向识别效果不佳的问题,提出了一种基于OpenCV的解决方案。该方法通过图像预处理、轮廓分析、几何特征提取(凸包、质心、外接矩形)和方向向量计算,准确判断箭头的上下左右方向。代码示例展示了从图像读取到方向识别的完整流程,并提供了优化建议(如调整二值化阈值、处理多轮廓)。该方案在Windows11+Python3.12+OpenCV环境下验证有效,适用于需要简单几何特征分析的箭头方向检测场景。

AnChenliang_1002的博客 702

YOLOv13添加OREPA模块 准确率提升10.56个点,map提升11.87个点。小目标轻量化

本文提出了一种新的OREPA(Optimal Recursive Edge-Preserving Attention)模块,通过结合递归和边缘保留注意力机制,显著提升了目标检测模型的性能。实验结果表明,添加OREPA模块后,准确率提升了10.56个百分点,mAP提升了11.87个百分点。OREPA模块包含三个核心组件:OREPA1处理特征图并保留边缘信息,Bottleneck_OREPA作为瓶颈模块降低计算量,OREPA类通过堆叠多个Bottleneck_OREPA增强网络表达能力。文章详细介绍了如何将OR

FJN110的博客 2761

pytorch基础 x.view()与nn.Linear()

展平:将卷积输出的多维特征图转换为适合全连接层的一维向量。全连接层:通过矩阵乘法将高维特征映射到低维空间。最终输出→ 这里是(32, 128),为后续分类做准备。

weixin_43973181的博客 375

uniapp - H5网页打包运行报错Failed to load resource: net::ERR_FILE_NOT_FOUND(uniApp打包成H5部署到服务器,打包h5白屏并报错页面空白)

Failed to load resource: net::ERR_FILE_NOT_FOUND,uniapp 坑之打包之后白屏,uniapp打包h5,HBuilderX 打包H5后空白报错 Failed to load resource: net::ERR FILE NOT_FOUND,UNI-APP H5应用白屏(空白页)解决方案,白屏并报错Failed to load resource: net::ERR_FILE_NOT_FOUND,uniapp开发,打包成H5部署到服务器,uniapp打包之后首页

🏆 前端领域优质创作者 3578

tensorrt的view以及../builder/Network.cpp::addPoolingNd问题解决

一、问题       在项目中对某些项目进行tensorrt加速的时候发现会报如下的错误。       上述错误大概是说view输入参数大小是512x7x7的,输出的参数大小确是512x36的,如此造成了输入输出规格不同。但是这在实际的代码中打断点调试根本看不出来,必须深入到tensorrt代码去查。 二、问题排查 打开tensorrt源码中的view.py文件查看并将输入输出的数据进行

贱贱的剑 777

检测头篇 | 手把手教你如何去更换YOLOv8的检测头为ASFF_Detect

自适应空间特征融合(ASFF)的主要原理旨在解决单次检测器中不同尺度特征的不一致性问题。具体来说,ASFF通过动态调整来自不同尺度特征金字塔层的特征贡献,确保每个检测对象的特征表示是一致且最优的。本文所做出的改进是将YOLOv8的检测头更换为ASFF_Detect。🌈

小哥谈 2497

“探索thumbdata4文件的奥秘:编程中的神秘存在“

综上所述,thumbdata4文件在编程中是一个常见的存在,与图库应用程序和图片浏览器密切相关。通过使用适当的库和工具,我们可以读取和处理thumbdata4文件中的缩略图数据,以提供更好的用户体验。我们首先读取8字节的块头,其中包含了下一个缩略图块的大小。你可以根据自己的需求来定义对块数据的处理方式,例如将其保存为图像文件或进行其他的分析操作。thumbdata4文件通常以二进制格式存储,其中包含着设备上浏览过的图片的缩略图。因此,你可能需要根据具体的thumbdata4文件结构进行适当的解析和处理。

JieLun_C的博客 792

pytorch中view函数的常用写法解释

下图是一个简单的神经网络(不是CNN),他是用来拟合一个抛物线的,但是本文的重点是forward函数中的x.view(-1, n)函数,很多时候你会发现许多的网络都是这么写的,2个参数值里有一个-1,另外一个是正数,view函数是不改变数据的情况下任意修改Tensor的形状(你不妨认为你的Tensor是106块麻将结合到一起,你可把它摆放成一个长条的,也可以堆成堆,总之还是那些牌,还是106块)。 -1代表的意思是不确定,主要依据那个非-1的参数,在本例中,就是依靠那个n,就是只要保证列数是n即可,行数随意

qq_43631827的博客 1615

DeepSeek R1-32B医疗大模型的完整微调实战分析(全码版)

【代码】DeepSeek R1-32B医疗大模型的完整微调实战指南(全码版)

AllenLV的博客 5101

python pytorch中 .view()函数讲解

一、普通用法 (手动调整size) view()相当于reshape、resize,重新调整Tensor的形状。 import torch a1 = torch.arange(0,16) print(a1) tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) a2 = a1.view(8, 2) a3 = a1.view(2, 8) a4 = a1.view(4, 4) print(a2) print(

欢迎关注,共同进步! 5万+

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

pytorch中 .view()函数讲解

一、普通用法 (手动调整size) view()相当于reshape、resize,重新调整Tensor的形状。 import torch a1 = torch.arange(0,16) print(a1) # tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) a2 = a1.view(8, 2) a3 = a1.view(2, 8) a4 = a1.view(4, 4) print(a2) #tens

qq_36998053的博客 2693

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

PyTorch中view()与cat()函数讲解浴与实例--(已解决)

最近在学习,记录一下: 1.view()函数   view()函数有些像numpy中的reshape函数,是用来的tensor(张量)形式的数据进行围堵重构的,直接用程序来说明用法。 import torch torch.manual_seed(0) # 用来控制内部的随机机制使每次得到的随机数一样 tt = torch.rand(3,4) # tensor([[0.4963, 0.7682, 0.0885, 0.1320], # [0.3074, 0.6341, 0.4901, 0.8

喵喵love的博客 754

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

PyTorch中的view()函数用法示例及其参数详解

最近使用PyTorch编写程序,经常会遇到tensor_data.contiguous().view(-1),以此记录下其用法。 view()函数用法示例及其参数详解 首先,view( ) 是对 PyTorch 中的 Tensor 操作的,若非 Tensor 类型,可使用 data = torch.tensor(data)来进行转换。 (1) 作用:该函数返回一个有__相同数据__但不同大小的...

vivid 2万+

pytorch中.view()函数的作用

参考以上链接~

m0_47887988的博客 166

PyTorch中的view的用法

在PyTorch中view函数作用为重构张量的维度,相当于numpy中的resize()的功能,但是用法不太一样 import torch tt1=torch.tensor([-0.3623,-0.6115,0.7283,0.4699,2.3261,0.1599]) 则tt1.size()为torch.Size([6]),是一个一行的tensor。现在通过view可以将其重构一下形状。 result=tt1.view(3,2) result tensor([[-0.3623.

hello_program_world的博客 631

Pytorch中tensor.view().permute().contiguous()函数理解

Pytorch中tensor.view().permute().contiguous()函数理解

Vertira的博客 1743

Transformer遇到的pytorch基础函数的使用

讲解的十分好的transformer的链接。

qq_40297851的博客 953

python中view函数,pytorch中torch.max和Tensor.view函数用法详解

torch.max()1.torch.max()简单来说是返回一个tensor中的最大值。例如:>>> si=torch.randn(4,5)>>> print(si)tensor([[ 1.1659, -1.5195, 0.0455, 1.7610, -0.2064],[-0.3443, 2.0483, 0.6303, 0.9475, 0.4364],[-1....

weixin_30438053的博客 515

【Pytorch】2025 Pytorch进阶教程

本文是一份 PyTorch 核心操作实用教程,聚焦张量与模型的关键处理技能。首先详解张量形状操作,涵盖 reshape、transpose、permute 等函数用法,助于适配网络层间数据传递;接着介绍张量均值、求和、平方等常见运算函数;还阐述自动微分模块的梯度计算方法,包括单标量 / 向量梯度求解及梯度清零、控制计算等技巧;最后说明模型保存(参数 / 全模型)与加载方法,强调结构一致性、设备兼容性等注意事项。帮助读者掌握从数据处理到模型管理的核心能力。

Larry的博客 1778

Pytorch

一、动态库链接文件找不到 二、Pytorch的Dataloader报错 三、pytorch bug 四、常用函数功能使用 1.view view(a,b)中第一个参数a代表目标张量的行数,b代表列数,为了简便起见,也可以只指定第一个参数a,b这个参数设置成-1,函数会自动计算对应的列数。 import torch number_1 = torch.rand...

weixin_43466321的博客 1351

pytorch_lesson2 张量的索引+torch.index_select+torch.view+张量的分片函数+张量的合并操作+张量的维度变换

文章目录前言一、张量的符号索引1、一维张量索引2、二维张量索引3、三维张量索引二、张量的函数索引torch.index_select()方法三、tensor.view()方法四、张量的分片函数1、分块:chunk函数2、拆分:split函数四、张量的合并操作1、cat2、stack堆叠六、张量维度变换1、squeeze函数:删除不必要的维度2、unsqueeze函数:手动升维 前言 张量作为有序的序列,也是具备数值索引的功能,并且基本索引方法和Python原生的列表、NumPy中的数组基本一致,当然,所有

weixin_51589123的博客 1667

tensor的存储方式 + view() reshape() resize_() 区别

文章目录1.前言2.tensor 的存储方式2.1.基本知识2.1.1官方文档2.2.tensor 的stride() 和 storage_offset() 属性2.2.1 stride()2.2.2 storage_offset()3.view(),reshape(),resize_()之间的关系3.1.view()3.2.reshape()3.2.1.tensor的连续性3.3.resize_()3.3.1.数据多的时候3.3.2.数据少的时候3.3.3.处理不连续数据4.总结 1.前言 在使用 exp

qq_52852138的博客 3789
上一篇: Pytorch中torch.gather函数
下一篇: CCF CSP 201503-2 数字排序 C++实现
木禾DING
博客等级 码龄8年 191粉丝 121原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值