當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python PyTorch ZeroPad2d用法及代碼示例

本文簡要介紹python語言中 torch.nn.ZeroPad2d 的用法。

用法:

class torch.nn.ZeroPad2d(padding)

參數

padding(int,tuple) -填充的大小。如果是 int ,則在所有邊界中使用相同的填充。如果是 4- tuple ,則使用( )

用零填充輸入張量邊界。

對於 N 維填充,請使用 torch.nn.functional.pad()

形狀:
  • 輸入:

  • 輸出: ,其中

    H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}

    W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}

例子:

>>> m = nn.ZeroPad2d(2)
>>> input = torch.randn(1, 1, 3, 3)
>>> input
tensor([[[[-0.1678, -0.4418,  1.9466],
          [ 0.9604, -0.4219, -0.5241],
          [-0.9162, -0.5436, -0.6446]]]])
>>> m(input)
tensor([[[[ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000],
          [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000],
          [ 0.0000,  0.0000, -0.1678, -0.4418,  1.9466,  0.0000,  0.0000],
          [ 0.0000,  0.0000,  0.9604, -0.4219, -0.5241,  0.0000,  0.0000],
          [ 0.0000,  0.0000, -0.9162, -0.5436, -0.6446,  0.0000,  0.0000],
          [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000],
          [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000]]]])
>>> # using different paddings for different sides
>>> m = nn.ZeroPad2d((1, 1, 2, 0))
>>> m(input)
tensor([[[[ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000],
          [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000],
          [ 0.0000, -0.1678, -0.4418,  1.9466,  0.0000],
          [ 0.0000,  0.9604, -0.4219, -0.5241,  0.0000],
          [ 0.0000, -0.9162, -0.5436, -0.6446,  0.0000]]]])

相關用法


注:本文由純淨天空篩選整理自pytorch.org大神的英文原創作品 torch.nn.ZeroPad2d。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。