torch.nn gather用法

浅谈Pytorch中的torch.gather函数的含义 pytorch中的gather函数 pytorch比tensorflow更加编程友好,所以准备用pytorch试着做最近要做的一些实验。 立个flag开始学习pytorch,新开一个分类整理学习pytorch中的一些踩到的泥坑。 今天刚开始接触,读了一下documentation,写一个一开始每太搞懂的函数gather b = torch.Tensor([[1,2,3],[4,5,6]]) print b index_1 = torch.LongTensor([[0,1],[2,0]]) index_2 = torch.LongTensor([[0,1,1],[0,0,0]]) print 立即下载

官方解释
torch.gather(input, dim, index, *, sparse_grad=False, out=None) → Tensor
Gathers values along an axis specified by dim.

For a 3-D tensor the output is specified by:

out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0
out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1
out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2

Parameters
input (Tensor) – the source tensor

dim (int) – the axis along which to index

index (LongTensor) – the indices of elements to gather

sparse_grad (bool,optional) – If True, gradient w.r.t. input will be a sparse tensor.

out (Tensor, optional) – the destination tensor

Example:

t = torch.tensor([[1,2],[3,4]])
torch.gather(t, 1, torch.tensor([[0,0],[1,0]]))
output:
tensor([[ 1, 1],
[ 4, 3]])

理解为在dim的方向,取index指定的input对应的值出来,
如example中,dim=1,所以沿列的方向,分别取t第一行的[0, 0]位置,即t对应的第一行[1,1],
取第二行的[1,0]位置,对应t的[4,3]

可用在分类问题中,计算每个类别softmax概率后,直接用groudtruth类别取出对应类别计算的概率。

Pytorch中torch.gather函数 在学习 CS231n中的NetworkVisualization-PyTorch任务,讲解了使用torch.gather函数,gather函数是用来根据你输入的位置索引 index,来对张量位置的数据进行合并,然后再输出。 其中 gather有两种使用方式,一种为 torch.gather 另一种为 对象.gather。 首先介绍 对象.gather import torch torch.manual_seed(2) #为CPU设置种子用于生成随机数,以使得结果是确定的 def gather_example(): N, C = 4, 5 s = torch.randn(N, 立即下载

相关推荐

如果用Selenium进行自动化测试

使用 Selenium 进行前端测试是一种非常有效的自动化测试方法。Selenium 是一个用于 Web 应用程序自动化测试的工具,它支持多种编程语言(如 Python、Java、C# 等),并可以在多种浏览器上运行测试。下面,我将通过一个具体的例子来向大家展示如何使用 Selenium 进行前端测试。在这个示例中,我们将使用 Python 语言,并以一个简单的登录功能为例,来介绍 Selenium 的基本使用方法。

fengyun4623的博客 1732

torch.gather()详解

的,可乱序的。

oceancoco的博客 4297

pwscf与wannier90 Hands-On实战训练(一)——费米面计算为例

系列文章目录 Quantum Espresso Hands-On实战训练(三)——DOS计算 文章目录系列文章目录计算过程pwscf直接得到等能面pwscf和wannier90得到等能面pwscf直接得到等能面1. scf2. nscf3. 后处理pwscf和wannier90得到等能面1. Kpoints2. scf3. nscf4. pw2wan及wannier90.x5. XCrySDen可视化 计算过程 pwscf直接得到等能面 pwscf和wannier90得到等能面 pwscf直接得到等能面

weixin_45973682的博客 5083

【Pytorch小知识】torch.gather()函数的用法及在Focal Loss中的应用(详细易懂)

文章目录官方文档中torch.gather的用法torch.gather应用总结 官方文档中torch.gather的用法 torch.gather(input, dim, index, out=None) → Tensor Gathers values along an axis specified by dim. For a 3-D tensor the output is specified by: out[i][j][k] = input[index[i][j][k]

主要更新底层视觉(去噪、超分等)相关的科研内容,形式为【论文精读】+【论文复现】 19万+

QCC308x/3095收发一体:TX/RX双模一拖二与多编码广播实战解析

本文深度解析高通QCC308x/3095蓝牙音频芯片的TX/RX双模功能与广播应用。芯片支持发射和接收模式下的“一拖二”连接,并能实现LE Audio多设备广播,显著提升多设备音频切换体验与商业广播能力,适用于健身、导览等丰富场景。

g9h0i1的博客 1016

python文件转为可执行文件(.exe)的详细步骤

本文详细介绍了如何从零开始把python文件打包成为可执行文件(.exe)。

m0_67093160的博客 3万+

torch.gather()用法详解

官方示例 链接:https://pytorch.org/docs/stable/generated/torch.gather.html torch.gather(input, dim, index, *, sparse_grad=False, out=None) → Tensor # 沿由 dim 指定的轴收集input的值,其输出形状与index相同。 input (Tensor) – the source tensor dim (int) – the axis along which to inde

Huang_Fj的博客 3553

水与光的奇妙“切割之舞”:水导激光切割技术探秘

水导激光切割技术的诞生,是材料加工领域不断追求高精度、高质量加工的成果。传统激光切割技术在加工过程中,材料会因瞬间高温而产生热变形、热影响区大以及切割面粗糙等问题,这些弊端在对一些高精度、热敏性材料的加工中尤为突出 ,迫切需要一种新的技术来克服这些难题。水导激光切割技术的起源可以追溯到 20 世纪 80 年代。1986 年,德国公司 Aesculap-Werke AG 首次提出了将水流引入激光切割过程的创新想法,并制造出首代水导激光设备。不过,当时的技术尚处于雏形阶段,仅仅是在光纤出口添加了一小柱水流,激光

远程部署调试 运行安装 项目调试 二次开发 项目技术新 持续迭代 部分源码免费分享 1684

pytorch padding_【开源计划】图像配准中常用损失函数的pytorch实现

前言按照开源计划的预告,我们首先从基于深度学习的图像配准任务中常用的损失函数的代码实现开始。从我最开始的那一篇博客,即基于深度学习的医学图像配准综述,可以看出,目前基于无监督学习的图像非刚性配准模型成为了一个比较流行的研究方向。这是因为基于监督学习的方法过分依赖传统方法或者模拟变形的方法来提供监督信息,这样既吃力又不讨好。以我的探索经验来讲,以传统配准方法产生的变形场作为监督信息,对网络进行训练,...

weixin_39979516的博客 473

Python爬虫实战:链家/贝壳租房数据抓取与可视化分析平台

本文详细介绍了如何使用Python爬虫技术抓取链家/贝壳网站的租房信息,并构建一个完整的数据可视化分析平台。文章涵盖了从数据抓取、数据清洗、数据存储到数据可视化的全流程,使用最新的Python技术栈,包括AsyncIOPandasMongoDB和Pyecharts等库。本系统可作为毕业设计项目,提供了完整的代码实现和架构设计。关键词:Python爬虫、数据抓取、数据可视化、链家、贝壳、租房信息、毕业设计。

2201_76125261的博客 1216

上午题目复习ing

无线局域网,11b是常用的,2.4ghz,后来改进5ghz,有些字段可以工作在5g的字段802.11/11a/1h/11n,,,,,11b和11g还在2.4ghz工作。数据链路层 传输服务,数据链路维护,差错控制,arp ip到mac,rarp反过来,token ring,x.25,atm,ethernet,蓝牙10m,简化因特网,分散式网,快调频,短包,点对点,点多多点,2.4ghz,最高速率1mb/s。gsm:是时分多址,900m-1800m,微蜂窝是市区,微微风是室内,伞是盲点,

weixin_47120900的博客 899

【pytorch】深度学习单卡训练升级到多卡训练(nn.DataParallel原理),以手写数据集分类为例

然后,nn.DataParallel会将输入数据划分为多个小批次,每个小批次分配到不同的GPU上,并使用torch.nn.parallel.scatter函数将输入数据复制到各个GPU上。接下来,nn.DataParallel会在每个GPU上分别计算模型的输出,并使用torch.nn.parallel.gather函数将各个GPU上的输出合并起来,得到最终的输出。最后,nn.DataParallel会将每个GPU上的输出合并起来,得到最终的输出,并计算损失函数和梯度。

种一棵树最好的时间是十年前,其次是现在 2185

2023华为od机试C卷【最富裕的小家庭】C++ 实现

在一颗树中,每个节点代表一个家庭成员,节点的数字表示其个人的财富值,一个节点及其直接相连的子节点被定义为个小家庭。现给你一颗树,请计算出最富裕的小家庭的财富和。

MISAYAONE的博客 1254

搭建深度学习网络时常用的一些pytorch函数:view(),softmax(),FloatTensor(),zero_(),scatter_(),gather(),sum(),clamp(),log

目录 torch.view() torch.nn.functional.softmax() torch.FloatTensor() torch.Tensor.zero_() torch.Tensor.scatter_() torch.gather() torch.sum() torch.clamp() torch.log() 参考pytorch说明文档:torch文档 torch.view() 返回一个数据相同但大小不同的tensor。 返回的tensor必须有与原te...

大烤翅的博客 1320

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

transformer代码理解

nn.ModuleList:https://blog.csdn.net/u014090429/article/details/112618607+代码写的挺好的。nn.conv1 https://blog.csdn.net/xu624735206/article/details/124961990 二三。Tensor.expand(): 具体的还需要进一步研究,没研究透彻。

hhhhhh356557的博客 160

深度学习工具包 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基础(一)

pytorch基础

weixin_46569877的博客 2022

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

【深度学习】多卡训练__单机多GPU方法详解(torch.nn.DataParallel、torch.distributed)

【深度学习】多卡训练__单机多GPU方法详解(torch.nn.DataParallel、torch.distributed)

Danger的博客 1万+

[已解决]安装apex报错AttributeError: module ‘torch.distributed‘ has no attribute ‘_all_gather_base‘

如果之前有安装apex,记得删除。然后按照后面指令操作即可。

计算机视觉 5224

torch.distributed.all_gather

torch.distributed.all_gather

weixin_37958272的博客 4913

PyTorch之torch.gather

torch.gather gather(input, dim, index) # 根据index,在dim维度上选取数据,输出的 size 和 index 一样 沿给定轴dim,将输入索引张量index指定位置的值进行聚合。 举例 import torch b = torch.Tensor([[1, 2, 3], [4, 5, 6]]) print(b) index_1 = torch.Lo...

WeiXy的博客 469

gather torch_torch.nn.DataParallel中数据Gather的问题:维度不匹配

Pytorch中的多GPU非常好用,一句话就能搞定:self.model = torch.nn.DataParallel(self.model)。然而这两天我做零样本学习中遇到了一个问题始终无法解决,就是说单GPU可以跑,一旦使用多GPU,就会出现:RuntimeError: Gather got an input of invalid size: got [24, 10, 448,448], b...

weixin_39970064的博客 866

pytorch之torch基础学习

然后,它将输出按顺序“链接”到每个后续模块的输入,最后返回最后一个模块的输出。或者,也可以创建一个OrderedDict来作为模块的方法接受输入Sequential,forward()将其转发给它包含的第一个模块。然后,它将输出按顺序“链接”到每个后续模块的输入,最后返回最后一个模块的输出。赋值张量没有这样的效果。这意味着model.base的参数将使用默认的学习率1e-2, model.classifier的参数将使用1e-3学习率,所有参数将使用动量0.9。模块的输入是索引列表,输出是相应的词嵌入。

qq_41627642的博客 2133

pytorch gather_torch.nn.DataParallel中数据Gather的问题:维度不匹配

Pytorch中的多GPU非常好用,一句话就能搞定:self.model = torch.nn.DataParallel(self.model)。然而这两天我做零样本学习中遇到了一个问题始终无法解决,就是说单GPU可以跑,一旦使用多GPU,就会出现:RuntimeError: Gather got an input of invalid size: got [24, 10, 448,448], b...

weixin_39557583的博客 781

PyTorch gather() 与 index_select() 对比:5 个场景下的性能与用法选择

本文深入对比了PyTorch中gather()与index_select()函数在5个典型场景下的性能与用法差异。通过核心概念解析、性能测试和实战案例,揭示两者在索引维度支持、内存访问模式和梯度传播等方面的本质区别,帮助开发者在不同场景下做出最优选择。文章特别关注GPU加速下的效率对比,为深度学习模型开发提供实用指南。

weixin_34059951的博客 449

torch的一些函数

0. 长期更新,看到奇怪的弄懂了就写 ref: https://www.bilibili.com/video/BV1wQ4y1q7Bm/?spm_id_from=333.788 https://blog.csdn.net/m0_46384757/article/details/120509481 1.torch.gather https://www.jianshu.com/p/b7d8d3c26f2d 上面的文章告诉我举例子的时候不要用1m或m1 也不要用n*n这种,不然歧义很多 这里是按我的理解写一遍,为

m0_46861439的博客 924

torch常用函数备忘录(持续更新...)

torch常用函数备忘录

xmyzqs1212的博客 349
上一篇: log_softmax与softmax的区别
下一篇: Focal loss简易版理解与实现
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

打赏作者

蓝羽飞鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值
⌂ 换网址