torch.scatter函数详解

#torch.scatter函数官方解释

scatter(output, dim, index, src) → Tensor

Writes all values from the tensor src into self at the indices specified in the index tensor. For each value in src, its output index is specified by its index in src for dimension != dim and by the corresponding value in index for dimension = dim.

For a 3-D tensor, self is updated as:

  • output[index[i][j][k]][j][k] = src[i][j][k]  # if dim == 0
  • output[i][index[i][j][k]][k] = src[i][j][k]  # if dim == 1
  • output[i][j][index[i][j][k]] = src[i][j][k]  # if dim == 2

This is the reverse operation of the manner described in gather().

self, index and src (if it is a Tensor) should have same number of dimensions. It is also required that index.size(d) <= src.size(d) for all dimensions d, and that index.size(d) <= self.size(d) for all dimensions d != dim.

Moreover, as for gather(), the values of index must be between 0 and self.size(dim) - 1 inclusive, and all values in a row along the specified dimension dim must be unique.

Parameters

  • dim (int) – the axis along which to index
  • index (LongTensor) – the indices of elements to scatter, can be either empty or the same size of src. When empty, the operation returns identity
  • src (Tensor) – the source element(s) to scatter, incase value is not specified
  • value (float) – the source element(s) to scatter, incase src is not specified

总结:scatter函数就是把src数组中的数据重新分配到output数组当中,index数组中表示了要把src数组中的数据分配到output数组中的位置,若未指定,则填充0.

#通过例子理解函数

import torch
 
input = torch.randn(2, 4)
print(input)
output = torch.zeros(2, 5)
index = torch.tensor([[3, 1, 2, 0], [1, 2, 0, 3]])
output = output.scatter(1, index, input)
print(output)

#得到输出
tensor([[-0.2558, -1.8930, -0.7831,  0.6100],
        [ 0.3246,  2.1289,  0.5887,  1.5588]])

tensor([[ 0.6100, -1.8930, -0.7831, -0.2558,  0.0000],
        [ 0.5887,  0.3246,  2.1289,  1.5588,  0.0000]])

建议从input数组出发,结合官方给出的位置替换进行理解。

数据位置发生的变化都是在第1维上,第0维不变。若dim=0,则同理变换input第一维的下标。

  • input[0][0] = output[0][index[0][0]] = output[0][3]
  • input[0][1] = output[0][index[0][1]] = output[0][1]
  • input[0][2] = output[0][index[0][2]] = output[0][2]
  • input[0][3] = output[0][index[0][3]] = output[0][0]
  • Input[1][0] = output[1][index[1][0]] = output[1][1]
  • input[1][1] = output[1][index[1][1]] = output[1][2]
  • input[1][2] = output[1][index[1][2]] = output[1][0]
  • input[1][3] = output[1][index[1][3]] = output[1][3]

一般scatter用于生成onehot向量,如下所示:

index = torch.tensor([[1], [2], [0], [3]])
onehot = torch.zeros(4, 4)
onehot.scatter_(1, index, 1)
print(onehot)

#输出
tensor([[0., 1., 0., 0.],
        [0., 0., 1., 0.],
        [1., 0., 0., 0.],
        [0., 0., 0., 1.]])

#如果input是一个数字的话,代表这用于分配到output的数字是多少。

  • 28
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: torch.onnx.export函数PyTorch中用于将模型导出为ONNX格式的函数。ONNX是一种开放式的深度学习框架,可以用于在不同的平台和框架之间共享模型。torch.onnx.export函数接受以下参数: 1. model:要导出的PyTorch模型。 2. args:模型的输入参数,可以是一个张量或一个元组。 3. f:导出的ONNX文件的名称。 4. export_params:如果为True,则导出模型的参数。 5. opset_version:导出的ONNX版本。 6. do_constant_folding:如果为True,则将模型中的常量折叠。 7. input_names:模型的输入名称。 8. output_names:模型的输出名称。 9. dynamic_axes:动态轴的字典,用于指定输入和输出的变化轴。 使用torch.onnx.export函数可以将PyTorch模型导出为ONNX格式,以便在其他平台和框架中使用。 ### 回答2: torch.onnx.export是PyTorch中的一个API,用于将定义好的模型导出为ONNX格式,从而可以在其他平台或框架中使用。 在使用torch.onnx.export时,需要提供以下参数: - model:待导出的模型 - args:模型输入的张量 - f:导出的ONNX文件的路径或文件句柄 - input_names:输入张量的名称列表 - output_names:输出张量的名称列表 - dynamic_axes:为输入和输出张量指定动态轴的名称和长度。例如:{‘input’: {0: ‘batch_size’}, ‘output’: {0: ‘batch_size’}}表示对于输入和输出的第0维设置为变化的动态轴,而它们的名称为“batch_size”。 - opset_version:ONNX模型所使用的运算符版本,例如opset_version=11表示使用ONNX版本11的运算符。 下面是一个简单的示例,展示了如何使用torch.onnx.export将模型导出为ONNX格式。 ``` import torch import torchvision dummy_input = torch.randn(10, 3, 224, 224) model = torchvision.models.alexnet(pretrained=True) torch.onnx.export(model, dummy_input, "alexnet.onnx", verbose=True) ``` 在上述示例中,我们首先载入预训练的AlexNet模型,并随机生成一个形状为[10,3,224,224]的张量作为输入数据。然后,我们使用torch.onnx.export将AlexNet模型导出为ONNX模型,并将其保存为"alexnet.onnx"文件。 这个API实际上还挺好用的,特别是在多次部署部署时可以避免重复工作。笔者在使用过程中也遇到了一些坑,比如导出的onnx模型放到tensorflow里跑的时候需要默认转置,如果涉及到模型的输入形状动态改变的话还需要设置对于维度名称的设置和onnx模型opset_version设置。阅读文档是件严肃的事情,用好了一定可以起到事半功倍的效果。 ### 回答3: PyTorch是一种非常流行的深度学习框架,其提供了ONNX(开放式神经网络交换)作为模型导出的标准。通过使用ONNX,PyTorch可以将训练好的模型导出为不同的平台所需的不同格式。这就使得模型可以在不同平台和环境中进行部署和运行。在PyTorch中,我们可以使用torch.onnx.export函数PyTorch模型导出一个ONNX模型。 torch.onnx.export函数可以将PyTorch模型保存为ONNX模型,其原型如下: torch.onnx.export(model, args, f, export_params=True, verbose=False, input_names=None, output_names=None, operator_export_type=None, opset_version=None, input_shapes=None, dynamic_axes=None, do_constant_folding=True, example_outputs=None, strip_doc_string=True, keep_initializers_as_inputs=None) 其中,参数model是我们要导出为ONNX模型的PyTorch模型,args是PyTorch模型输入的张量,f是导出ONNX模型的文件名。 export_params确定是否将训练参数导出到ONNX模型中,verbose指定是否输出详细信息。input_names和output_names是模型输入和输出张量的名称。operator_export_type指定导出模型时要使用的运算符类型,opset_version指定使用的ONNX版本。 input_shapes和dynamic_axes在导出多个批次数据时非常有用。input_shapes可以指定张量的完整形状,dynamic_axes可以指定哪个维度应该是变量维度(批次维度)。 do_constant_folding可以控制是否执行常量折叠优化,例如可以删除不再需要的常量。example_outputs是生成器,提供模型的输出示例。strip_doc_string确定是否删除ONNX模型中的注释字符串。keep_initializers_as_inputs决定是否在导出的ONNX模型的输入中保留初始化器。 使用torch.onnx.export函数时,要注意输入和输出张量的数量和顺序。如果我们的PyTorch模型有多个输入或输出,我们需要在input_names和output_names中提供所有输入和输出名称,并在args中按顺序提供所有输入张量。 除了torch.onnx.export函数之外,我们还可以使用PyTorch提供的其他API来进行模型导出。例如,我们可以使用torch.jit.trace函数来动态跟踪模型操作,并生成Torch脚本模型。我们还可以使用torch.jit.script函数将整个PyTorch模型转换为Torch脚本模型。但是,对于某些平台或工具,ONNX格式是最好的选择。 在总体上,通过使用torch.onnx.export函数,我们可以轻松地将训练好的PyTorch模型导出为ONNX模型,以便在不同的平台和环境中进行部署和运行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值