Unfold¶
- class torch.nn.Unfold(kernel_size, dilation=1, padding=0, stride=1)[源代码][源代码]¶
从批量输入的张量中提取滑动局部块。
考虑一个批量输入的张量,形状为 ,其中 是批处理维度, 是通道维度, 代表任意空间维度。此操作将
input
张量的空间维度中的每个kernel_size
大小的滑动块展平为一个 3-Doutput
张量的列(即最后一个维度),形状为 ,其中 是每个块内的总值数(一个块有 个空间位置,每个位置包含一个 通道向量),L 是此类块的总数其中 由
input
的空间维度组成(即上面的 ),d 遍历所有空间维度。因此,在
output
张量的最后一个维度(列维度)进行索引会给出特定块内的所有值。padding
、stride
和dilation
参数指定了如何检索滑动块。stride
控制滑动块的步长。padding
控制在重塑之前,在每个维度的padding
个点两端添加的隐式零填充量。dilation
控制核点之间的间距;也称为 à trous 算法。它比较难描述,但此链接有一个很好的可视化说明dilation
的作用。
- 参数
如果
kernel_size
、dilation
、padding
或stride
是一个 int 或长度为 1 的 tuple,它们的值将被复制到所有空间维度。对于两个输入空间维度的情况,此操作有时称为
im2col
。
注意
Fold
通过对所有包含块中的所有值求和来计算结果大张量中的每个组合值。Unfold
通过从大张量复制来提取局部块中的值。因此,如果块重叠,它们就不是彼此的逆操作。一般来说,折叠和展开操作的关系如下。考虑使用相同参数创建的
Fold
和Unfold
实例>>> 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
张量不包含零元素时,fold
和unfold
操作互为逆操作(仅相差一个常数因子)。警告
目前,仅支持 4 维输入张量(批量图像类张量)。
- 形状
输入:
输出: 如上所述
示例
>>> 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)