PyTorch学习(14):张量(Tensor)填充(Padding)(torch.nn.functional.pad)

PyTorch学习(6):导出ONNX模型_pytorch导出onnx-CSDN博客

PyTorch学习(7):常用损失函数(CrossEntropyLoss, BCELoss, BCEWithLogitsLoss, L1Loss, MSELoss)_pytorch bce-CSDN博客

PyTorch学习(8):PyTorch中Tensor的合并于拆分(torch.cat, torch.stack, torch.trunk, torch.split)-CSDN博客

PyTorch学习(9):torch.topk-CSDN博客

PyTorch学习(11):PyTorch的形状变换(view, reshape)与维度变换(transpose, permute)_pytorch的三维view变换-CSDN博客
PyTorch学习(12):PyTorch取极值(max, argmax, min, argmin)_torch.argmin-CSDN博客
 

PyTorch学习(13):PyTorch的张量相乘(torch.matmul)_torch.matmul pytorch-CSDN博客

目录

1. 概述

2. PyTorch的Padding接口

3. 示例


1. 概述

我们在做卷积的时候,不可避免的会遇到对Tensor进行填充的情况。

以卷积操作为例,在操作中,padding指的是在输入特征图的边缘填充额外的值(通常为0),以增加输入特征图的大小,从而影响卷积层的输出尺寸。通过调整padding的大小,可以精确控制输出特征图的维度,一方面保持边缘信息,另一方面也能够使其满足网络设计的需求。

2. PyTorch的Padding接口

PyTorch的卷积操作本身包含padding功能,同时也提供了torch.nn.functional.pad功能接口。

torch.nn.functional.pad原型如下:

torch.nn.functional.pad(input, pad, mode='constant', value=None)

其中,

input (Tensor): 要进行填充的输入张量。

pad (int, tuple): (左填充,右填充,上填充,下填充,前填充,后填充),其数值代表填充次数。

mode (str, 可选): 填充的类型,可以是 'constant', 'reflect', 'replicate' 或 'circular'。默认为 'constant'。

value (float, 可选): 当mode='constant'时,用于填充的值。默认为0。

值得注意的是,pad参数的数量一般为2的倍数,其对应的维度从右往左计。如pad参数为(2, 2),则是对最后一维进行。如果当前的Tensor为NCHW,则是在W维度上前后各填充2个数(默认为0)。

3. 示例

如下为一个示例程序,首先创建一个随机Tensor,然后再最后一维前后各填充两个0.

import torch

ts = torch.randint(0, 10, (2,3))

new_ts = torch.nn.functional.pad(ts, (2, 2))

print(f"ts: {ts}")

print(f"new_ts: {new_ts}")

原Tensor和填充后的Tensor如下:

ts: tensor([[8, 9, 0],

        [4, 8, 6]])

new_ts: tensor([[0, 0, 8, 9, 0, 0, 0],

        [0, 0, 4, 8, 6, 0, 0]])

如果将程序做如下修改,增加将要填充的维度。

import torch

ts = torch.randint(0, 10, (2,3))

new_ts = torch.nn.functional.pad(ts, (2, 2, 2, 2))

print(f"ts: {ts}")

print(f"new_ts: {new_ts}")

新的原Tensor和填充后的Tensor如下:

ts: tensor([[1, 8, 8],

        [1, 0, 7]])

new_ts: tensor([[0, 0, 0, 0, 0, 0, 0],

        [0, 0, 0, 0, 0, 0, 0],

        [0, 0, 1, 8, 8, 0, 0],

        [0, 0, 1, 0, 7, 0, 0],

        [0, 0, 0, 0, 0, 0, 0],

        [0, 0, 0, 0, 0, 0, 0]])

  • 22
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值