评价此页

Unfold#

class torch.nn.modules.fold.Unfold(kernel_size, dilation=1, padding=0, stride=1)[源码]#

从批处理的输入 Tensor 中提取滑动局部块。

考虑一个形状为 (N,C,)(N, C, *) 的批量输入张量,其中 NN 是批次维度,CC 是通道维度,* 代表任意空间维度。此操作会将输入张量空间维度中每个 kernel_size 大小的滑动块展平成一个列(即最后一个维度),得到一个形状为 (N,C×(kernel_size),L)(N, C \times \prod(\text{kernel\_size}), L) 的 3-D 输出张量,其中 C×(kernel_size)C \times \prod(\text{kernel\_size}) 是每个块内的值总数(一个块有 (kernel_size)\prod(\text{kernel\_size}) 个空间位置,每个位置包含一个 CC 通道的向量),并且 LL 是这些块的总数。

L=dspatial_size[d]+2×padding[d]dilation[d]×(kernel_size[d]1)1stride[d]+1,L = \prod_d \left\lfloor\frac{\text{spatial\_size}[d] + 2 \times \text{padding}[d] % - \text{dilation}[d] \times (\text{kernel\_size}[d] - 1) - 1}{\text{stride}[d]} + 1\right\rfloor,

其中 spatial_size\text{spatial\_size} 由输入张量的空间维度组成(上面是 *),并且 dd 遍历所有空间维度。

因此,索引输出张量的最后一个维度(列维度)将获得某个块内的所有值。

参数 paddingstridedilation 指定了如何提取滑动块。

  • stride 控制滑动块的步幅。

  • padding 控制在重塑之前,每个维度上的 padding 个点两侧的隐式零填充量。

  • dilation 控制核点之间的间距;也称为空洞卷积算法。这个概念比较难描述,但 这个链接 有一个 dilation 作用的可视化。

参数
  • kernel_size (inttuple) – 滑动块的大小

  • dilation (inttuple, 可选) – 一个控制邻域内元素步幅的参数。默认值:1

  • padding (inttuple, 可选) – 要添加到输入两侧的隐式零填充。默认值:0

  • stride (inttuple, optional) – 输入空间维度中滑动块的步长。默认为:1

  • 如果 kernel_sizedilationpaddingstride 是一个整数或长度为 1 的元组,其值将复制到所有空间维度。

  • 对于具有两个输入空间维度的场景,此操作有时称为 im2col

注意

Fold 通过对所有包含块的值求和来计算结果大张量中的每个组合值。Unfold 通过从大张量中复制来提取局部块中的值。因此,如果块重叠,它们不是彼此的逆操作。

一般来说,折叠和展开操作相关如下。考虑使用相同参数创建的 FoldUnfold 实例。

>>> fold_params = dict(kernel_size=..., dilation=..., padding=..., stride=...)
>>> fold = nn.Fold(output_size=..., **fold_params)
>>> unfold = nn.Unfold(**fold_params)

那么对于任何(受支持的)input 张量,以下等式成立:

fold(unfold(input)) == divisor * input

其中 divisor 是一个仅取决于 input 的形状和 dtype 的张量。

>>> input_ones = torch.ones(input.shape, dtype=input.dtype)
>>> divisor = fold(unfold(input_ones))

divisor 张量不包含零元素时,则 foldunfold 操作是彼此的逆运算( up to constant divisor)。

警告

目前,仅支持 4 维输入张量(批处理的类图像张量)。

形状
  • 输入: (N,C,)(N, C, *)

  • 输出: (N,C×(kernel_size),L)(N, C \times \prod(\text{kernel\_size}), L),如上所述。

示例

>>> unfold = nn.Unfold(kernel_size=(2, 3))
>>> input = torch.randn(2, 5, 3, 4)
>>> output = unfold(input)
>>> # each patch contains 30 values (2x3=6 vectors, each of 5 channels)
>>> # 4 blocks (2x3 kernels) in total in the 3x4 input
>>> output.size()
torch.Size([2, 30, 4])

>>> # Convolution is equivalent with Unfold + Matrix Multiplication + Fold (or view to output shape)
>>> inp = torch.randn(1, 3, 10, 12)
>>> w = torch.randn(2, 3, 4, 5)
>>> inp_unf = torch.nn.functional.unfold(inp, (4, 5))
>>> out_unf = inp_unf.transpose(1, 2).matmul(w.view(w.size(0), -1).t()).transpose(1, 2)
>>> out = torch.nn.functional.fold(out_unf, (7, 8), (1, 1))
>>> # or equivalently (and avoiding a copy),
>>> # out = out_unf.view(1, 2, 7, 8)
>>> (torch.nn.functional.conv2d(inp, w) - out).abs().max()
tensor(1.9073e-06)
extra_repr()[源码]#

返回模块的额外表示。

返回类型

str

forward(input)[源码]#

执行前向传播。

返回类型

张量