評價此頁

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)[原始碼]#

執行前向傳播。

返回型別

張量