nn_functional.md 86.0 KB
Newer Older
W
wizardforcel 已提交
1
# torch.nn.functional
J
janhu 已提交
2 3

> 译者:[hijkzzz](https://github.com/hijkzzz)
W
wizardforcel 已提交
4

J
janhu 已提交
5
## 卷积函数
W
wizardforcel 已提交
6 7 8 9 10 11 12

### conv1d

```py
torch.nn.functional.conv1d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1)  Tensor
```

J
janhu 已提交
13
对由多个输入平面组成的输入信号进行一维卷积. 
W
wizardforcel 已提交
14

J
janhu 已提交
15
有关详细信息和输出形状, 请参见[`Conv1d`](#torch.nn.Conv1d "torch.nn.Conv1d"). 
W
wizardforcel 已提交
16

J
janhu 已提交
17
注意
W
wizardforcel 已提交
18

J
janhu 已提交
19
在某些情况下, 当使用CUDA后端与CuDNN时, 该操作符可能会选择不确定性算法来提高性能. 如果这不是您希望的, 您可以通过设置`torch.backends.cudn .deterministic = True`来尝试使操作具有确定性(可能会以性能为代价). 请参阅关于 [Reproducibility](notes/randomness.html) 了解背景.
W
wizardforcel 已提交
20 21

 
J
janhu 已提交
22
参数:
W
wizardforcel 已提交
23

J
janhu 已提交
24 25 26 27
*   **input** – 输入tensor, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bminibatch%7D%20%5Ctimes%20%5Ctext%7Bin%5C_channels%7D%20%5Ctimes%20iW))
*   **weight** – 卷积核, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bout%5C_channels%7D%20%5Ctimes%20%5Cfrac%7B%5Ctext%7Bin%5C_channels%7D%7D%7B%5Ctext%7Bgroups%7D%7D%20%5Ctimes%20kW))
*   **bias** – 可选的偏置, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bout%5C_channels%7D)). 默认值: `None`
*   **stride** – 卷积核的步幅, 可以是单个数字或一个元素元组`(sW,)`. 默认值: 1
J
janhu 已提交
28 29
*   **padding** – 在输入的两边隐式加零. 可以是单个数字或一个元素元组`(padW, )`. 默认值:  0
*   **dilation** – 核元素之间的空洞. 可以是单个数字或单元素元组`(dW,)`. 默认值:  1
J
janhu 已提交
30
*   **groups** – 将输入分成组, ![](http://latex.codecogs.com/gif.latex?%5Ctext%7Bin%5C_channels%7D) 应该可以被组的数目整除. 默认值:  1
W
wizardforcel 已提交
31 32 33 34

 |
| --- | --- |

J
janhu 已提交
35
例子:
W
wizardforcel 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49

```py
>>> filters = torch.randn(33, 16, 3)
>>> inputs = torch.randn(20, 16, 50)
>>> F.conv1d(inputs, filters)

```

### conv2d

```py
torch.nn.functional.conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1)  Tensor
```

J
janhu 已提交
50
对由多个输入平面组成的输入图像应用二维卷积.
W
wizardforcel 已提交
51

J
janhu 已提交
52
有关详细信息和输出形状, 请参见[`Conv2d`](#torch.nn.Conv2d "torch.nn.Conv2d").
W
wizardforcel 已提交
53

J
janhu 已提交
54
注意
W
wizardforcel 已提交
55

J
janhu 已提交
56
在某些情况下, 当使用CUDA后端与CuDNN时, 该操作符可能会选择不确定性算法来提高性能. 如果这不是您希望的, 您可以通过设置`torch.backends.cudn .deterministic = True`来尝试使操作具有确定性(可能会以性能为代价). 请参阅关于 [Reproducibility](notes/randomness.html) 了解背景.
W
wizardforcel 已提交
57 58

 
J
janhu 已提交
59 60 61 62 63 64 65 66 67
参数:

*   **input** – 输入tensor, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bminibatch%7D%20%5Ctimes%20%5Ctext%7Bin%5C_channels%7D%20%5Ctimes%20iH%20%5Ctimes%20iW))
*   **weight** – 卷积核, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bout%5C_channels%7D%20%5Ctimes%20%5Cfrac%7B%5Ctext%7Bin%5C_channels%7D%7D%7B%5Ctext%7Bgroups%7D%7D%20%5Ctimes%20kH%20%5Ctimes%20kW))
*   **bias** – 可选的偏置, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bout%5C_channels%7D)). 默认值:  `None`
*   **stride** – 卷积核的步幅, 可以是单个数字或一个元素元组 `(sH, sW)`. 默认值:  1
*   **padding** – 在输入的两边隐式加零. 可以是单个数字或一个元素元组 `(padH, padW)`. 默认值:  0
*   **dilation** – 核元素之间的空洞. 可以是单个数字或单元素元组 `(dH, dW)`. 默认值:  1
*   **groups** – 将输入分成组, ![](http://latex.codecogs.com/gif.latex?%5Ctext%7Bin%5C_channels%7D) 应该可以被组的数目整除. 默认值:  1
W
wizardforcel 已提交
68 69 70 71

 |
| --- | --- |

J
janhu 已提交
72
例子:
W
wizardforcel 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

```py
>>> # With square kernels and equal stride
>>> filters = torch.randn(8,4,3,3)
>>> inputs = torch.randn(1,4,5,5)
>>> F.conv2d(inputs, filters, padding=1)

```

### conv3d

```py
torch.nn.functional.conv3d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1)  Tensor
```

J
janhu 已提交
88
对由多个输入平面组成的输入图像应用三维卷积.
W
wizardforcel 已提交
89

J
janhu 已提交
90
有关详细信息和输出形状, 请参见 [`Conv3d`](#torch.nn.Conv3d "torch.nn.Conv3d").
W
wizardforcel 已提交
91

J
janhu 已提交
92
注意
W
wizardforcel 已提交
93

J
janhu 已提交
94
在某些情况下, 当使用CUDA后端与CuDNN时, 该操作符可能会选择不确定性算法来提高性能. 如果这不是您希望的, 您可以通过设置`torch.backends.cudn .deterministic = True`来尝试使操作具有确定性(可能会以性能为代价). 请参阅关于 [Reproducibility](notes/randomness.html) 了解背景.
W
wizardforcel 已提交
95 96

 
J
janhu 已提交
97 98 99 100 101 102 103 104 105
参数:

*   **input** – 输入tensor, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bminibatch%7D%20%5Ctimes%20%5Ctext%7Bin%5C_channels%7D%20%5Ctimes%20iT%20%5Ctimes%20iH%20%5Ctimes%20iW))
*   **weight** – 卷积核, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bout%5C_channels%7D%20%5Ctimes%20%5Cfrac%7B%5Ctext%7Bin%5C_channels%7D%7D%7B%5Ctext%7Bgroups%7D%7D%20%5Ctimes%20kT%20%5Ctimes%20kH%20%5Ctimes%20kW))
*   **bias** – 可选的偏置, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bout%5C_channels%7D)). 默认值:  None
*   **stride** – 卷积核的步幅, 可以是单个数字或一个元素元组 `(sT, sH, sW)`. 默认值:  1
*   **padding** – 在输入的两边隐式加零. 可以是单个数字或一个元素元组 `(padT, padH, padW)`. 默认值:  0
*   **dilation** – 核元素之间的空洞. 可以是单个数字或单元素元组 `(dT, dH, dW)`. 默认值:  1
*   **groups** – 将输入分成组, ![](http://latex.codecogs.com/gif.latex?%5Ctext%7Bin%5C_channels%7D) 应该可以被组的数目整除. 默认值:  1
W
wizardforcel 已提交
106 107 108 109

 |
| --- | --- |

J
janhu 已提交
110
例子:
W
wizardforcel 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124

```py
>>> filters = torch.randn(33, 16, 3, 3, 3)
>>> inputs = torch.randn(20, 16, 50, 10, 20)
>>> F.conv3d(inputs, filters)

```

### conv_transpose1d

```py
torch.nn.functional.conv_transpose1d(input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1)  Tensor
```

J
janhu 已提交
125
对由多个输入平面组成的输入信号应用一维转置卷积算子, 有时也称为反卷积. 
W
wizardforcel 已提交
126

J
janhu 已提交
127
有关详细信息和输出形状, 请参见 [`ConvTranspose1d`](#torch.nn.ConvTranspose1d "torch.nn.ConvTranspose1d") 
W
wizardforcel 已提交
128

J
janhu 已提交
129
注意
W
wizardforcel 已提交
130

J
janhu 已提交
131
在某些情况下, 当使用CUDA后端与CuDNN时, 该操作符可能会选择不确定性算法来提高性能. 如果这不是您希望的, 您可以通过设置`torch.backends.cudn .deterministic = True`来尝试使操作具有确定性(可能会以性能为代价). 请参阅关于 [Reproducibility](notes/randomness.html) 了解背景.
W
wizardforcel 已提交
132 133

 
J
janhu 已提交
134
参数:
W
wizardforcel 已提交
135

J
janhu 已提交
136 137 138 139 140 141 142 143
*   **input** – 输入tensor, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bminibatch%7D%20%5Ctimes%20%5Ctext%7Bin%5C_channels%7D%20%5Ctimes%20iW))
*   **weight** – 卷积核, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bin%5C_channels%7D%20%5Ctimes%20%5Cfrac%7B%5Ctext%7Bout%5C_channels%7D%7D%7B%5Ctext%7Bgroups%7D%7D%20%5Ctimes%20kW))
*   **bias** – 可选的偏置, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bout%5C_channels%7D)). 默认值:  None
*   **stride** – 卷积核的步幅, 可以是单个数字或一个元素元组 `(sW,)`. 默认值:  1
*   **padding** – 输入中的每个维度的两边都将添加零填充`kernel_size - 1 - padding`. 可以是单个数字或元组 `(padW,)`. 默认值:  0
*   **output_padding** – 添加到输出形状中每个维度的一侧的额外大小. 可以是单个数字或元组 `(out_padW)`. 默认值:  0
*   **groups** – 将输入分成组, ![](http://latex.codecogs.com/gif.latex?%5Ctext%7Bin%5C_channels%7D) 应该可以被组的数目整除. 默认值:  1
*   **dilation** – 核元素之间的空洞. 可以是单个数字或单元素元组 `(dW,)`. 默认值:  1
W
wizardforcel 已提交
144 145 146 147

 |
| --- | --- |

J
janhu 已提交
148
例子:
W
wizardforcel 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162

```py
>>> inputs = torch.randn(20, 16, 50)
>>> weights = torch.randn(16, 33, 5)
>>> F.conv_transpose1d(inputs, weights)

```

### conv_transpose2d

```py
torch.nn.functional.conv_transpose2d(input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1)  Tensor
```

J
janhu 已提交
163
对由多个输入平面组成的输入图像应用二维转置卷积算子, 有时也称为反卷积.
W
wizardforcel 已提交
164 165


J
janhu 已提交
166
有关详细信息和输出形状, 请参见 [`ConvTranspose2d`](#torch.nn.ConvTranspose2d "torch.nn.ConvTranspose2d").
W
wizardforcel 已提交
167

J
janhu 已提交
168
注意
W
wizardforcel 已提交
169

J
janhu 已提交
170
在某些情况下, 当使用CUDA后端与CuDNN时, 该操作符可能会选择不确定性算法来提高性能. 如果这不是您希望的, 您可以通过设置`torch.backends.cudn .deterministic = True`来尝试使操作具有确定性(可能会以性能为代价). 请参阅关于 [Reproducibility](notes/randomness.html) 了解背景.
W
wizardforcel 已提交
171

J
janhu 已提交
172 173 174 175 176 177 178 179 180 181 182
 
参数:

*   **input** – 输入tensor, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bminibatch%7D%20%5Ctimes%20%5Ctext%7Bin%5C_channels%7D%20%5Ctimes%20iH%20%5Ctimes%20iW))
*   **weight** – 卷积核, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bin%5C_channels%7D%20%5Ctimes%20%5Cfrac%7B%5Ctext%7Bout%5C_channels%7D%7D%7B%5Ctext%7Bgroups%7D%7D%20%5Ctimes%20kH%20%5Ctimes%20kW))
*   **bias** –可选的偏置, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bout%5C_channels%7D)). 默认值:  None
*   **stride** – 卷积核的步幅, 可以是单个数字或一个元素元组 `(sH, sW)`. 默认值:  1
*   **padding** – 输入中的每个维度的两边都将添加零填充`kernel_size - 1 - padding`. 可以是单个数字或元组 `(padH, padW)`. 默认值:  0
*   **output_padding** – 添加到输出形状中每个维度的一侧的额外大小. 可以是单个数字或元组 `(out_padH, out_padW)`. 默认值:  0
*   **groups** – 将输入分成组, ![](http://latex.codecogs.com/gif.latex?%5Ctext%7Bin%5C_channels%7D) 应该可以被组的数目整除. 默认值:  1
*   **dilation** – 核元素之间的空洞. 可以是单个数字或单元素元组 `(dH, dW)`. 默认值:  1
W
wizardforcel 已提交
183 184 185 186

 |
| --- | --- |

J
janhu 已提交
187
例子:
W
wizardforcel 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

```py
>>> # With square kernels and equal stride
>>> inputs = torch.randn(1, 4, 5, 5)
>>> weights = torch.randn(4, 8, 3, 3)
>>> F.conv_transpose2d(inputs, weights, padding=1)

```

### conv_transpose3d

```py
torch.nn.functional.conv_transpose3d(input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1)  Tensor
```

J
janhu 已提交
203
对由多个输入平面组成的输入图像应用一个三维转置卷积算子,有时也称为反卷积
W
wizardforcel 已提交
204

J
janhu 已提交
205
有关详细信息和输出形状, 请参见 [`ConvTranspose3d`](#torch.nn.ConvTranspose3d "torch.nn.ConvTranspose3d").
W
wizardforcel 已提交
206

J
janhu 已提交
207
注意
W
wizardforcel 已提交
208

J
janhu 已提交
209
在某些情况下, 当使用CUDA后端与CuDNN时, 该操作符可能会选择不确定性算法来提高性能. 如果这不是您希望的, 您可以通过设置`torch.backends.cudn .deterministic = True`来尝试使操作具有确定性(可能会以性能为代价). 请参阅关于 [Reproducibility](notes/randomness.html) 了解背景.
W
wizardforcel 已提交
210 211

 
J
janhu 已提交
212 213 214 215 216 217 218 219 220 221
参数:

*   **input** – 输入tensor, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bminibatch%7D%20%5Ctimes%20%5Ctext%7Bin%5C_channels%7D%20%5Ctimes%20iT%20%5Ctimes%20iH%20%5Ctimes%20iW))
*   **weight** – 卷积核, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bin%5C_channels%7D%20%5Ctimes%20%5Cfrac%7B%5Ctext%7Bout%5C_channels%7D%7D%7B%5Ctext%7Bgroups%7D%7D%20%5Ctimes%20kT%20%5Ctimes%20kH%20%5Ctimes%20kW))
*   **bias** –可选的偏置, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bout%5C_channels%7D)). 默认值:  None
*   **stride** – 卷积核的步幅, 可以是单个数字或一个元素元组 `(sT, sH, sW)`. 默认值:  1
*   **padding** – 输入中的每个维度的两边都将添加零填充`kernel_size - 1 - padding`. 可以是单个数字或元组 `(padT, padH, padW)`. 默认值:  0
*   **output_padding** – 添加到输出形状中每个维度的一侧的额外大小. 可以是单个数字或元组 `(out_padT, out_padH, out_padW)`. 默认值:  0
*   **groups** – 将输入分成组, ![](http://latex.codecogs.com/gif.latex?%5Ctext%7Bin%5C_channels%7D) 应该可以被组的数目整除. 默认值:  1
*   **dilation** – 核元素之间的空洞. 可以是单个数字或单元素元组 `(dT, dH, dW)`. 默认值:  1
W
wizardforcel 已提交
222 223 224 225

 |
| --- | --- |

J
janhu 已提交
226
例子:
W
wizardforcel 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

```py
>>> inputs = torch.randn(20, 16, 50, 10, 20)
>>> weights = torch.randn(16, 33, 3, 3, 3)
>>> F.conv_transpose3d(inputs, weights)

```

### unfold

```py
torch.nn.functional.unfold(input, kernel_size, dilation=1, padding=0, stride=1)
```

Extracts sliding local blocks from an batched input tensor.

J
janhu 已提交
243
警告
W
wizardforcel 已提交
244 245 246

Currently, only 4-D input tensors (batched image-like tensors) are supported.

J
janhu 已提交
247
[`torch.nn.Unfold`](#torch.nn.Unfold "torch.nn.Unfold") for details
W
wizardforcel 已提交
248 249 250 251 252 253 254 255 256

### fold

```py
torch.nn.functional.fold(input, output_size, kernel_size, dilation=1, padding=0, stride=1)
```

Combines an array of sliding local blocks into a large containing tensor.

J
janhu 已提交
257
警告
W
wizardforcel 已提交
258 259 260

Currently, only 4-D output tensors (batched image-like tensors) are supported.

J
janhu 已提交
261
[`torch.nn.Fold`](#torch.nn.Fold "torch.nn.Fold") for details
W
wizardforcel 已提交
262 263 264 265 266 267 268 269 270 271 272

## Pooling functions

### avg_pool1d

```py
torch.nn.functional.avg_pool1d(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True)  Tensor
```

Applies a 1D average pooling over an input signal composed of several input planes.

J
janhu 已提交
273
[`AvgPool1d`](#torch.nn.AvgPool1d "torch.nn.AvgPool1d") for details and output shape.
W
wizardforcel 已提交
274 275

 
J
janhu 已提交
276
参数:
W
wizardforcel 已提交
277

J
janhu 已提交
278
*   **input** – 输入tensor, 形状为 ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bminibatch%7D%20%5Ctimes%20%5Ctext%7Bin%5C_channels%7D%20%5Ctimes%20iW))
W
wizardforcel 已提交
279
*   **kernel_size** – the size of the window. Can be a single number or a tuple ![](http://latex.codecogs.com/gif.latex?(kW%2C))
J
janhu 已提交
280
*   **stride** – the stride of the window. Can be a single number or a tuple `(sW,)`. 默认值:  `kernel_size`
J
janhu 已提交
281
*   **padding** – 在输入的两边隐式加零. 可以是单个数字或一个元素元组 `(padW,)`. 默认值:  0
J
janhu 已提交
282 283
*   **ceil_mode** – when True, will use `ceil` instead of `floor` to compute the output shape. 默认值:  `False`
*   **count_include_pad** – when True, will include the zero-padding in the averaging calculation. 默认值:  `True`
W
wizardforcel 已提交
284 285 286 287 288

 |
| --- | --- |

```py
J
janhu 已提交
289
例子::
W
wizardforcel 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
```

```py
>>> # pool of square window of size=3, stride=2
>>> input = torch.tensor([[[1,2,3,4,5,6,7]]])
>>> F.avg_pool1d(input, kernel_size=3, stride=2)
tensor([[[ 2.,  4.,  6.]]])

```

### avg_pool2d

```py
torch.nn.functional.avg_pool2d(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True)  Tensor
```

Applies 2D average-pooling operation in ![](http://latex.codecogs.com/gif.latex?kH%20%5Ctimes%20kW) regions by step size ![](http://latex.codecogs.com/gif.latex?sH%20%5Ctimes%20sW) steps. The number of output features is equal to the number of input planes.

J
janhu 已提交
308
[`AvgPool2d`](#torch.nn.AvgPool2d "torch.nn.AvgPool2d") for details and output shape.
W
wizardforcel 已提交
309 310

 
J
janhu 已提交
311
参数:
W
wizardforcel 已提交
312 313 314

*   **input** – input tensor ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bminibatch%7D%20%5Ctimes%20%5Ctext%7Bin%5C_channels%7D%20%5Ctimes%20iH%20%5Ctimes%20iW))
*   **kernel_size** – size of the pooling region. Can be a single number or a tuple ![](http://latex.codecogs.com/gif.latex?(kH%20%5Ctimes%20kW))
J
janhu 已提交
315
*   **stride** – stride of the pooling operation. Can be a single number or a tuple `(sH, sW)`. 默认值:  `kernel_size`
J
janhu 已提交
316
*   **padding** – 在输入的两边隐式加零. 可以是单个数字或一个元素元组 `(padH, padW)`. 默认值:  0
J
janhu 已提交
317 318
*   **ceil_mode** – when True, will use `ceil` instead of `floor` in the formula to compute the output shape. 默认值:  `False`
*   **count_include_pad** – when True, will include the zero-padding in the averaging calculation. 默认值:  `True`
W
wizardforcel 已提交
319 320 321 322 323 324 325 326 327 328 329 330

 |
| --- | --- |

### avg_pool3d

```py
torch.nn.functional.avg_pool3d(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True)  Tensor
```

Applies 3D average-pooling operation in ![](http://latex.codecogs.com/gif.latex?kT%20%5Ctimes%20kH%20%5Ctimes%20kW) regions by step size ![](http://latex.codecogs.com/gif.latex?sT%20%5Ctimes%20sH%20%5Ctimes%20sW) steps. The number of output features is equal to ![](http://latex.codecogs.com/gif.latex?%5Clfloor%5Cfrac%7B%5Ctext%7Binput%20planes%7D%7D%7BsT%7D%5Crfloor).

J
janhu 已提交
331
[`AvgPool3d`](#torch.nn.AvgPool3d "torch.nn.AvgPool3d") for details and output shape.
W
wizardforcel 已提交
332 333

 
J
janhu 已提交
334
参数:
W
wizardforcel 已提交
335 336 337

*   **input** – input tensor ![](http://latex.codecogs.com/gif.latex?(%5Ctext%7Bminibatch%7D%20%5Ctimes%20%5Ctext%7Bin%5C_channels%7D%20%5Ctimes%20iT%20%5Ctimes%20iH%20%5Ctimes%20iW))
*   **kernel_size** – size of the pooling region. Can be a single number or a tuple ![](http://latex.codecogs.com/gif.latex?(kT%20%5Ctimes%20kH%20%5Ctimes%20kW))
J
janhu 已提交
338
*   **stride** – stride of the pooling operation. Can be a single number or a tuple `(sT, sH, sW)`. 默认值:  `kernel_size`
J
janhu 已提交
339
*   **padding** – 在输入的两边隐式加零. 可以是单个数字或一个元素元组 `(padT, padH, padW)`, 默认值:  0
W
wizardforcel 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353
*   **ceil_mode** – when True, will use `ceil` instead of `floor` in the formula to compute the output shape
*   **count_include_pad** – when True, will include the zero-padding in the averaging calculation

 |
| --- | --- |

### max_pool1d

```py
torch.nn.functional.max_pool1d(*args, **kwargs)
```

Applies a 1D max pooling over an input signal composed of several input planes.

J
janhu 已提交
354
[`MaxPool1d`](#torch.nn.MaxPool1d "torch.nn.MaxPool1d") for details.
W
wizardforcel 已提交
355 356 357 358 359 360 361 362 363

### max_pool2d

```py
torch.nn.functional.max_pool2d(*args, **kwargs)
```

Applies a 2D max pooling over an input signal composed of several input planes.

J
janhu 已提交
364
[`MaxPool2d`](#torch.nn.MaxPool2d "torch.nn.MaxPool2d") for details.
W
wizardforcel 已提交
365 366 367 368 369 370 371 372 373

### max_pool3d

```py
torch.nn.functional.max_pool3d(*args, **kwargs)
```

Applies a 3D max pooling over an input signal composed of several input planes.

J
janhu 已提交
374
[`MaxPool3d`](#torch.nn.MaxPool3d "torch.nn.MaxPool3d") for details.
W
wizardforcel 已提交
375 376 377 378 379 380 381 382 383

### max_unpool1d

```py
torch.nn.functional.max_unpool1d(input, indices, kernel_size, stride=None, padding=0, output_size=None)
```

Computes a partial inverse of `MaxPool1d`.

J
janhu 已提交
384
[`MaxUnpool1d`](#torch.nn.MaxUnpool1d "torch.nn.MaxUnpool1d") for details.
W
wizardforcel 已提交
385 386 387 388 389 390 391 392 393

### max_unpool2d

```py
torch.nn.functional.max_unpool2d(input, indices, kernel_size, stride=None, padding=0, output_size=None)
```

Computes a partial inverse of `MaxPool2d`.

J
janhu 已提交
394
[`MaxUnpool2d`](#torch.nn.MaxUnpool2d "torch.nn.MaxUnpool2d") for details.
W
wizardforcel 已提交
395 396 397 398 399 400 401 402 403

### max_unpool3d

```py
torch.nn.functional.max_unpool3d(input, indices, kernel_size, stride=None, padding=0, output_size=None)
```

Computes a partial inverse of `MaxPool3d`.

J
janhu 已提交
404
[`MaxUnpool3d`](#torch.nn.MaxUnpool3d "torch.nn.MaxUnpool3d") for details.
W
wizardforcel 已提交
405 406 407 408 409 410 411 412 413

### lp_pool1d

```py
torch.nn.functional.lp_pool1d(input, norm_type, kernel_size, stride=None, ceil_mode=False)
```

Applies a 1D power-average pooling over an input signal composed of several input planes. If the sum of all inputs to the power of `p` is zero, the gradient is set to zero as well.

J
janhu 已提交
414
[`LPPool1d`](#torch.nn.LPPool1d "torch.nn.LPPool1d") for details.
W
wizardforcel 已提交
415 416 417 418 419 420 421 422 423

### lp_pool2d

```py
torch.nn.functional.lp_pool2d(input, norm_type, kernel_size, stride=None, ceil_mode=False)
```

Applies a 2D power-average pooling over an input signal composed of several input planes. If the sum of all inputs to the power of `p` is zero, the gradient is set to zero as well.

J
janhu 已提交
424
[`LPPool2d`](#torch.nn.LPPool2d "torch.nn.LPPool2d") for details.
W
wizardforcel 已提交
425 426 427 428 429 430 431 432 433

### adaptive_max_pool1d

```py
torch.nn.functional.adaptive_max_pool1d(*args, **kwargs)
```

Applies a 1D adaptive max pooling over an input signal composed of several input planes.

J
janhu 已提交
434
[`AdaptiveMaxPool1d`](#torch.nn.AdaptiveMaxPool1d "torch.nn.AdaptiveMaxPool1d") for details and output shape.
W
wizardforcel 已提交
435 436

 
J
janhu 已提交
437
参数:
W
wizardforcel 已提交
438 439

*   **output_size** – the target output size (single integer)
J
janhu 已提交
440
*   **return_indices** – whether to return pooling indices. 默认值:  `False`
W
wizardforcel 已提交
441 442 443 444 445 446 447 448 449 450 451 452

 |
| --- | --- |

### adaptive_max_pool2d

```py
torch.nn.functional.adaptive_max_pool2d(*args, **kwargs)
```

Applies a 2D adaptive max pooling over an input signal composed of several input planes.

J
janhu 已提交
453
[`AdaptiveMaxPool2d`](#torch.nn.AdaptiveMaxPool2d "torch.nn.AdaptiveMaxPool2d") for details and output shape.
W
wizardforcel 已提交
454 455

 
J
janhu 已提交
456
参数:
W
wizardforcel 已提交
457 458

*   **output_size** – the target output size (single integer or double-integer tuple)
J
janhu 已提交
459
*   **return_indices** – whether to return pooling indices. 默认值:  `False`
W
wizardforcel 已提交
460 461 462 463 464 465 466 467 468 469 470 471

 |
| --- | --- |

### adaptive_max_pool3d

```py
torch.nn.functional.adaptive_max_pool3d(*args, **kwargs)
```

Applies a 3D adaptive max pooling over an input signal composed of several input planes.

J
janhu 已提交
472
[`AdaptiveMaxPool3d`](#torch.nn.AdaptiveMaxPool3d "torch.nn.AdaptiveMaxPool3d") for details and output shape.
W
wizardforcel 已提交
473 474

 
J
janhu 已提交
475
参数:
W
wizardforcel 已提交
476 477

*   **output_size** – the target output size (single integer or triple-integer tuple)
J
janhu 已提交
478
*   **return_indices** – whether to return pooling indices. 默认值:  `False`
W
wizardforcel 已提交
479 480 481 482 483 484 485 486 487 488 489 490

 |
| --- | --- |

### adaptive_avg_pool1d

```py
torch.nn.functional.adaptive_avg_pool1d(input, output_size)  Tensor
```

Applies a 1D adaptive average pooling over an input signal composed of several input planes.

J
janhu 已提交
491
[`AdaptiveAvgPool1d`](#torch.nn.AdaptiveAvgPool1d "torch.nn.AdaptiveAvgPool1d") for details and output shape.
W
wizardforcel 已提交
492 493

 
J
janhu 已提交
494
| 参数:| **output_size** – the target output size (single integer) |
W
wizardforcel 已提交
495 496 497 498 499 500 501 502 503 504
| --- | --- |

### adaptive_avg_pool2d

```py
torch.nn.functional.adaptive_avg_pool2d(input, output_size)
```

Applies a 2D adaptive average pooling over an input signal composed of several input planes.

J
janhu 已提交
505
[`AdaptiveAvgPool2d`](#torch.nn.AdaptiveAvgPool2d "torch.nn.AdaptiveAvgPool2d") for details and output shape.
W
wizardforcel 已提交
506 507

 
J
janhu 已提交
508
| 参数:| **output_size** – the target output size (single integer or double-integer tuple) |
W
wizardforcel 已提交
509 510 511 512 513 514 515 516 517 518
| --- | --- |

### adaptive_avg_pool3d

```py
torch.nn.functional.adaptive_avg_pool3d(input, output_size)
```

Applies a 3D adaptive average pooling over an input signal composed of several input planes.

J
janhu 已提交
519
[`AdaptiveAvgPool3d`](#torch.nn.AdaptiveAvgPool3d "torch.nn.AdaptiveAvgPool3d") for details and output shape.
W
wizardforcel 已提交
520 521

 
J
janhu 已提交
522
| 参数:| **output_size** – the target output size (single integer or triple-integer tuple) |
W
wizardforcel 已提交
523 524 525 526 527 528 529 530 531 532 533 534
| --- | --- |

## Non-linear activation functions

### threshold

```py
torch.nn.functional.threshold(input, threshold, value, inplace=False)
```

Thresholds each element of the input Tensor.

J
janhu 已提交
535
[`Threshold`](#torch.nn.Threshold "torch.nn.Threshold") for more details.
W
wizardforcel 已提交
536 537 538 539 540 541 542 543 544 545 546 547 548

```py
torch.nn.functional.threshold_(input, threshold, value)  Tensor
```

In-place version of [`threshold()`](#torch.nn.functional.threshold "torch.nn.functional.threshold").

### relu

```py
torch.nn.functional.relu(input, inplace=False)  Tensor
```

J
janhu 已提交
549
Applies the rectified linear unit function element-wise. 见 [`ReLU`](#torch.nn.ReLU "torch.nn.ReLU") for more details.
W
wizardforcel 已提交
550 551 552 553 554 555 556 557 558 559 560 561 562

```py
torch.nn.functional.relu_(input)  Tensor
```

In-place version of [`relu()`](#torch.nn.functional.relu "torch.nn.functional.relu").

### hardtanh

```py
torch.nn.functional.hardtanh(input, min_val=-1., max_val=1., inplace=False)  Tensor
```

J
janhu 已提交
563
Applies the HardTanh function element-wise. 见 [`Hardtanh`](#torch.nn.Hardtanh "torch.nn.Hardtanh") for more details.
W
wizardforcel 已提交
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578

```py
torch.nn.functional.hardtanh_(input, min_val=-1., max_val=1.)  Tensor
```

In-place version of [`hardtanh()`](#torch.nn.functional.hardtanh "torch.nn.functional.hardtanh").

### relu6

```py
torch.nn.functional.relu6(input, inplace=False)  Tensor
```

Applies the element-wise function ![](http://latex.codecogs.com/gif.latex?%5Ctext%7BReLU6%7D(x)%20%3D%20%5Cmin(%5Cmax(0%2Cx)%2C%206)).

J
janhu 已提交
579
[`ReLU6`](#torch.nn.ReLU6 "torch.nn.ReLU6") for more details.
W
wizardforcel 已提交
580 581 582 583 584 585 586 587 588

### elu

```py
torch.nn.functional.elu(input, alpha=1.0, inplace=False)
```

Applies element-wise, ![](http://latex.codecogs.com/gif.latex?%5Ctext%7BELU%7D(x)%20%3D%20%5Cmax(0%2Cx)%20%2B%20%5Cmin(0%2C%20%5Calpha%20*%20(%5Cexp(x)%20-%201))).

J
janhu 已提交
589
[`ELU`](#torch.nn.ELU "torch.nn.ELU") for more details.
W
wizardforcel 已提交
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604

```py
torch.nn.functional.elu_(input, alpha=1.)  Tensor
```

In-place version of [`elu()`](#torch.nn.functional.elu "torch.nn.functional.elu").

### selu

```py
torch.nn.functional.selu(input, inplace=False)  Tensor
```

Applies element-wise, ![](http://latex.codecogs.com/gif.latex?%5Ctext%7BSELU%7D(x)%20%3D%20scale%20*%20(%5Cmax(0%2Cx)%20%2B%20%5Cmin(0%2C%20%5Calpha%20*%20(%5Cexp(x)%20-%201)))), with ![](http://latex.codecogs.com/gif.latex?%5Calpha%3D1.6732632423543772848170429916717) and ![](http://latex.codecogs.com/gif.latex?scale%3D1.0507009873554804934193349852946).

J
janhu 已提交
605
[`SELU`](#torch.nn.SELU "torch.nn.SELU") for more details.
W
wizardforcel 已提交
606 607 608 609 610 611 612 613 614

### celu

```py
torch.nn.functional.celu(input, alpha=1., inplace=False)  Tensor
```

Applies element-wise, ![](http://latex.codecogs.com/gif.latex?%5Ctext%7BCELU%7D(x)%20%3D%20%5Cmax(0%2Cx)%20%2B%20%5Cmin(0%2C%20%5Calpha%20*%20(%5Cexp(x%2F%5Calpha)%20-%201))).

J
janhu 已提交
615
[`CELU`](#torch.nn.CELU "torch.nn.CELU") for more details.
W
wizardforcel 已提交
616 617 618 619 620 621 622 623 624

### leaky_relu

```py
torch.nn.functional.leaky_relu(input, negative_slope=0.01, inplace=False)  Tensor
```

Applies element-wise, ![](http://latex.codecogs.com/gif.latex?%5Ctext%7BLeakyReLU%7D(x)%20%3D%20%5Cmax(0%2C%20x)%20%2B%20%5Ctext%7Bnegative%5C_slope%7D%20*%20%5Cmin(0%2C%20x))

J
janhu 已提交
625
[`LeakyReLU`](#torch.nn.LeakyReLU "torch.nn.LeakyReLU") for more details.
W
wizardforcel 已提交
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640

```py
torch.nn.functional.leaky_relu_(input, negative_slope=0.01)  Tensor
```

In-place version of [`leaky_relu()`](#torch.nn.functional.leaky_relu "torch.nn.functional.leaky_relu").

### prelu

```py
torch.nn.functional.prelu(input, weight)  Tensor
```

Applies element-wise the function ![](http://latex.codecogs.com/gif.latex?%5Ctext%7BPReLU%7D(x)%20%3D%20%5Cmax(0%2Cx)%20%2B%20%5Ctext%7Bweight%7D%20*%20%5Cmin(0%2Cx)) where weight is a learnable parameter.

J
janhu 已提交
641
[`PReLU`](#torch.nn.PReLU "torch.nn.PReLU") for more details.
W
wizardforcel 已提交
642 643 644 645 646 647 648 649 650

### rrelu

```py
torch.nn.functional.rrelu(input, lower=1./8, upper=1./3, training=False, inplace=False)  Tensor
```

Randomized leaky ReLU.

J
janhu 已提交
651
[`RReLU`](#torch.nn.RReLU "torch.nn.RReLU") for more details.
W
wizardforcel 已提交
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673

```py
torch.nn.functional.rrelu_(input, lower=1./8, upper=1./3, training=False)  Tensor
```

In-place version of [`rrelu()`](#torch.nn.functional.rrelu "torch.nn.functional.rrelu").

### glu

```py
torch.nn.functional.glu(input, dim=-1)  Tensor
```

The gated linear unit. Computes:

![](http://latex.codecogs.com/gif.latex?%0D%0AH%20%3D%20A%20%5Ctimes%20%5Csigma(B))

where `input` is split in half along `dim` to form `A` and `B`.

See [Language Modeling with Gated Convolutional Networks](https://arxiv.org/abs/1612.08083).

 
J
janhu 已提交
674
参数:
W
wizardforcel 已提交
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689

*   **input** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – input tensor
*   **dim** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – dimension on which to split the input

 |
| --- | --- |

### logsigmoid

```py
torch.nn.functional.logsigmoid(input)  Tensor
```

Applies element-wise ![](http://latex.codecogs.com/gif.latex?%5Ctext%7BLogSigmoid%7D(x)%20%3D%20%5Clog%20%5Cleft(%5Cfrac%7B1%7D%7B1%20%2B%20%5Cexp(-x_i)%7D%5Cright))

J
janhu 已提交
690
[`LogSigmoid`](#torch.nn.LogSigmoid "torch.nn.LogSigmoid") for more details.
W
wizardforcel 已提交
691 692 693 694 695 696 697 698 699

### hardshrink

```py
torch.nn.functional.hardshrink(input, lambd=0.5)  Tensor
```

Applies the hard shrinkage function element-wise

J
janhu 已提交
700
[`Hardshrink`](#torch.nn.Hardshrink "torch.nn.Hardshrink") for more details.
W
wizardforcel 已提交
701 702 703 704 705 706 707 708 709

### tanhshrink

```py
torch.nn.functional.tanhshrink(input)  Tensor
```

Applies element-wise, ![](http://latex.codecogs.com/gif.latex?%5Ctext%7BTanhshrink%7D(x)%20%3D%20x%20-%20%5Ctext%7BTanh%7D(x))

J
janhu 已提交
710
[`Tanhshrink`](#torch.nn.Tanhshrink "torch.nn.Tanhshrink") for more details.
W
wizardforcel 已提交
711 712 713 714 715 716 717 718 719

### softsign

```py
torch.nn.functional.softsign(input)  Tensor
```

Applies element-wise, the function ![](http://latex.codecogs.com/gif.latex?%5Ctext%7BSoftSign%7D(x)%20%3D%20%5Cfrac%7Bx%7D%7B1%20%2B%20%7Cx%7C%7D)

J
janhu 已提交
720
[`Softsign`](#torch.nn.Softsign "torch.nn.Softsign") for more details.
W
wizardforcel 已提交
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737

### softplus

```py
torch.nn.functional.softplus(input, beta=1, threshold=20)  Tensor
```

### softmin

```py
torch.nn.functional.softmin(input, dim=None, _stacklevel=3, dtype=None)
```

Applies a softmin function.

Note that ![](http://latex.codecogs.com/gif.latex?%5Ctext%7BSoftmin%7D(x)%20%3D%20%5Ctext%7BSoftmax%7D(-x)). See softmax definition for mathematical formula.

J
janhu 已提交
738
[`Softmin`](#torch.nn.Softmin "torch.nn.Softmin") for more details.
W
wizardforcel 已提交
739 740

 
J
janhu 已提交
741
参数:
W
wizardforcel 已提交
742 743 744 745 746 747 748 749

*   **input** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – input
*   **dim** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – A dimension along which softmin will be computed (so every slice along dim will sum to 1).
*   **dtype** (`torch.dtype`, optional) – the desired data type of returned tensor.

 |
| --- | --- |

J
janhu 已提交
750
:param If specified, the input tensor is casted to `dtype` before the operation: :param is performed. This is useful for preventing data type overflows. 默认值:  None.
W
wizardforcel 已提交
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765

### softmax

```py
torch.nn.functional.softmax(input, dim=None, _stacklevel=3, dtype=None)
```

Applies a softmax function.

Softmax is defined as:

![](http://latex.codecogs.com/gif.latex?%5Ctext%7BSoftmax%7D(x_%7Bi%7D)%20%3D%20%5Cfrac%7Bexp(x_i)%7D%7B%5Csum_j%20exp(x_j)%7D)

It is applied to all slices along dim, and will re-scale them so that the elements lie in the range `(0, 1)` and sum to 1.

J
janhu 已提交
766
[`Softmax`](#torch.nn.Softmax "torch.nn.Softmax") for more details.
W
wizardforcel 已提交
767 768

 
J
janhu 已提交
769
参数:
W
wizardforcel 已提交
770 771 772 773 774 775 776 777

*   **input** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – input
*   **dim** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – A dimension along which softmax will be computed.
*   **dtype** (`torch.dtype`, optional) – the desired data type of returned tensor.

 |
| --- | --- |

J
janhu 已提交
778
:param If specified, the input tensor is casted to `dtype` before the operation: :param is performed. This is useful for preventing data type overflows. 默认值:  None.
W
wizardforcel 已提交
779

J
janhu 已提交
780
注意
W
wizardforcel 已提交
781 782 783 784 785 786 787 788 789 790 791

This function doesn’t work directly with NLLLoss, which expects the Log to be computed between the Softmax and itself. Use log_softmax instead (it’s faster and has better numerical properties).

### softshrink

```py
torch.nn.functional.softshrink(input, lambd=0.5)  Tensor
```

Applies the soft shrinkage function elementwise

J
janhu 已提交
792
[`Softshrink`](#torch.nn.Softshrink "torch.nn.Softshrink") for more details.
W
wizardforcel 已提交
793 794 795 796 797 798 799 800 801 802

### gumbel_softmax

```py
torch.nn.functional.gumbel_softmax(logits, tau=1.0, hard=False, eps=1e-10)
```

Sample from the Gumbel-Softmax distribution and optionally discretize.

 
J
janhu 已提交
803
参数:
W
wizardforcel 已提交
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829

*   **logits**`[batch_size, num_features]` unnormalized log probabilities
*   **tau** – non-negative scalar temperature
*   **hard** – if `True`, the returned samples will be discretized as one-hot vectors, but will be differentiated as if it is the soft sample in autograd

 |
| --- | --- |
| Returns: | Sampled tensor of shape `batch_size x num_features` from the Gumbel-Softmax distribution. If `hard=True`, the returned samples will be one-hot, otherwise they will be probability distributions that sum to 1 across features |
| --- | --- |

Constraints:

*   Currently only work on 2D input `logits` tensor of shape `batch_size x num_features`

Based on [https://github.com/ericjang/gumbel-softmax/blob/3c8584924603869e90ca74ac20a6a03d99a91ef9/Categorical%20VAE.ipynb](https://github.com/ericjang/gumbel-softmax/blob/3c8584924603869e90ca74ac20a6a03d99a91ef9/Categorical%20VAE.ipynb) , (MIT license)

### log_softmax

```py
torch.nn.functional.log_softmax(input, dim=None, _stacklevel=3, dtype=None)
```

Applies a softmax followed by a logarithm.

While mathematically equivalent to log(softmax(x)), doing these two operations separately is slower, and numerically unstable. This function uses an alternative formulation to compute the output and gradient correctly.

J
janhu 已提交
830
[`LogSoftmax`](#torch.nn.LogSoftmax "torch.nn.LogSoftmax") for more details.
W
wizardforcel 已提交
831 832

 
J
janhu 已提交
833
参数:
W
wizardforcel 已提交
834 835 836 837 838 839 840 841

*   **input** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – input
*   **dim** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – A dimension along which log_softmax will be computed.
*   **dtype** (`torch.dtype`, optional) – the desired data type of returned tensor.

 |
| --- | --- |

J
janhu 已提交
842
:param If specified, the input tensor is casted to `dtype` before the operation: :param is performed. This is useful for preventing data type overflows. 默认值:  None.
W
wizardforcel 已提交
843 844 845 846 847 848 849 850 851

### tanh

```py
torch.nn.functional.tanh(input)  Tensor
```

Applies element-wise, ![](http://latex.codecogs.com/gif.latex?%5Ctext%7BTanh%7D(x)%20%3D%20%5Ctanh(x)%20%3D%20%5Cfrac%7B%5Cexp(x)%20-%20%5Cexp(-x)%7D%7B%5Cexp(x)%20%2B%20%5Cexp(-x)%7D)

J
janhu 已提交
852
[`Tanh`](#torch.nn.Tanh "torch.nn.Tanh") for more details.
W
wizardforcel 已提交
853 854 855 856 857 858 859 860 861

### sigmoid

```py
torch.nn.functional.sigmoid(input)  Tensor
```

Applies the element-wise function ![](http://latex.codecogs.com/gif.latex?%5Ctext%7BSigmoid%7D(x)%20%3D%20%5Cfrac%7B1%7D%7B1%20%2B%20%5Cexp(-x)%7D)

J
janhu 已提交
862
[`Sigmoid`](#torch.nn.Sigmoid "torch.nn.Sigmoid") for more details.
W
wizardforcel 已提交
863 864 865 866 867 868 869 870 871 872 873

## Normalization functions

### batch_norm

```py
torch.nn.functional.batch_norm(input, running_mean, running_var, weight=None, bias=None, training=False, momentum=0.1, eps=1e-05)
```

Applies Batch Normalization for each channel across a batch of data.

J
janhu 已提交
874
[`BatchNorm1d`](#torch.nn.BatchNorm1d "torch.nn.BatchNorm1d"), [`BatchNorm2d`](#torch.nn.BatchNorm2d "torch.nn.BatchNorm2d"), [`BatchNorm3d`](#torch.nn.BatchNorm3d "torch.nn.BatchNorm3d") for details.
W
wizardforcel 已提交
875 876 877 878 879 880 881 882 883

### instance_norm

```py
torch.nn.functional.instance_norm(input, running_mean=None, running_var=None, weight=None, bias=None, use_input_stats=True, momentum=0.1, eps=1e-05)
```

Applies Instance Normalization for each channel in each data sample in a batch.

J
janhu 已提交
884
[`InstanceNorm1d`](#torch.nn.InstanceNorm1d "torch.nn.InstanceNorm1d"), [`InstanceNorm2d`](#torch.nn.InstanceNorm2d "torch.nn.InstanceNorm2d"), [`InstanceNorm3d`](#torch.nn.InstanceNorm3d "torch.nn.InstanceNorm3d") for details.
W
wizardforcel 已提交
885 886 887 888 889 890 891 892 893

### layer_norm

```py
torch.nn.functional.layer_norm(input, normalized_shape, weight=None, bias=None, eps=1e-05)
```

Applies Layer Normalization for last certain number of dimensions.

J
janhu 已提交
894
[`LayerNorm`](#torch.nn.LayerNorm "torch.nn.LayerNorm") for details.
W
wizardforcel 已提交
895 896 897 898 899 900 901 902 903

### local_response_norm

```py
torch.nn.functional.local_response_norm(input, size, alpha=0.0001, beta=0.75, k=1.0)
```

Applies local response normalization over an input signal composed of several input planes, where channels occupy the second dimension. Applies normalization across channels.

J
janhu 已提交
904
[`LocalResponseNorm`](#torch.nn.LocalResponseNorm "torch.nn.LocalResponseNorm") for details.
W
wizardforcel 已提交
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920

### normalize

```py
torch.nn.functional.normalize(input, p=2, dim=1, eps=1e-12, out=None)
```

Performs ![](http://latex.codecogs.com/gif.latex?L_p) normalization of inputs over specified dimension.

For a tensor `input` of sizes ![](http://latex.codecogs.com/gif.latex?(n_0%2C%20...%2C%20n_%7Bdim%7D%2C%20...%2C%20n_k)), each ![](http://latex.codecogs.com/gif.latex?n_%7Bdim%7D) -element vector ![](http://latex.codecogs.com/gif.latex?v) along dimension `dim` is transformed as

![](http://latex.codecogs.com/gif.latex?%0D%0Av%20%3D%20%5Cfrac%7Bv%7D%7B%5Cmax(%5ClVert%20v%20%5CrVert_p%2C%20%5Cepsilon)%7D.%0D%0A%0D%0A)

With the default arguments it uses the Euclidean norm over vectors along dimension ![](http://latex.codecogs.com/gif.latex?1) for normalization.

 
J
janhu 已提交
921
参数:
W
wizardforcel 已提交
922 923

*   **input** – input tensor of any shape
J
janhu 已提交
924 925 926
*   **p** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")) – the exponent value in the norm formulation. 默认值:  2
*   **dim** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – the dimension to reduce. 默认值:  1
*   **eps** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")) – small value to avoid division by zero. 默认值:  1e-12
W
wizardforcel 已提交
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
*   **out** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_,_ _optional_) – the output tensor. If `out` is used, this operation won’t be differentiable.

 |
| --- | --- |

## Linear functions

### linear

```py
torch.nn.functional.linear(input, weight, bias=None)
```

Applies a linear transformation to the incoming data: ![](http://latex.codecogs.com/gif.latex?y%20%3D%20xA%5ET%20%2B%20b).

Shape:

> *   Input: ![](http://latex.codecogs.com/gif.latex?(N%2C%20*%2C%20in%5C_features)) where `*` means any number of additional dimensions
> *   Weight: ![](http://latex.codecogs.com/gif.latex?(out%5C_features%2C%20in%5C_features))
> *   Bias: ![](http://latex.codecogs.com/gif.latex?(out%5C_features))
> *   Output: ![](http://latex.codecogs.com/gif.latex?(N%2C%20*%2C%20out%5C_features))

### bilinear

```py
torch.nn.functional.bilinear(input1, input2, weight, bias=None)
```

## Dropout functions

### dropout

```py
torch.nn.functional.dropout(input, p=0.5, training=True, inplace=False)
```

During training, randomly zeroes some of the elements of the input tensor with probability `p` using samples from a Bernoulli distribution.

J
janhu 已提交
965
[`Dropout`](#torch.nn.Dropout "torch.nn.Dropout") for details.
W
wizardforcel 已提交
966 967

 
J
janhu 已提交
968
参数:
W
wizardforcel 已提交
969

J
janhu 已提交
970
*   **p** – probability of an element to be zeroed. 默认值:  0.5
W
wizardforcel 已提交
971
*   **training** – apply dropout if is `True`. Defualt: `True`
J
janhu 已提交
972
*   **inplace** – If set to `True`, will do this operation in-place. 默认值:  `False`
W
wizardforcel 已提交
973 974 975 976 977 978 979 980 981 982 983 984

 |
| --- | --- |

### alpha_dropout

```py
torch.nn.functional.alpha_dropout(input, p=0.5, training=False, inplace=False)
```

Applies alpha dropout to the input.

J
janhu 已提交
985
[`AlphaDropout`](#torch.nn.AlphaDropout "torch.nn.AlphaDropout") for details.
W
wizardforcel 已提交
986 987 988 989 990 991 992 993 994

### dropout2d

```py
torch.nn.functional.dropout2d(input, p=0.5, training=True, inplace=False)
```

Randomly zero out entire channels (a channel is a 2D feature map, e.g., the ![](http://latex.codecogs.com/gif.latex?j)-th channel of the ![](http://latex.codecogs.com/gif.latex?i)-th sample in the batched input is a 2D tensor ![](http://latex.codecogs.com/gif.latex?%5Ctext%7Binput%7D%5Bi%2C%20j%5D)) of the input tensor). Each channel will be zeroed out independently on every forward call. with probability `p` using samples from a Bernoulli distribution.

J
janhu 已提交
995
[`Dropout2d`](#torch.nn.Dropout2d "torch.nn.Dropout2d") for details.
W
wizardforcel 已提交
996 997

 
J
janhu 已提交
998
参数:
W
wizardforcel 已提交
999

J
janhu 已提交
1000
*   **p** – probability of a channel to be zeroed. 默认值:  0.5
W
wizardforcel 已提交
1001
*   **training** – apply dropout if is `True`. Defualt: `True`
J
janhu 已提交
1002
*   **inplace** – If set to `True`, will do this operation in-place. 默认值:  `False`
W
wizardforcel 已提交
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014

 |
| --- | --- |

### dropout3d

```py
torch.nn.functional.dropout3d(input, p=0.5, training=True, inplace=False)
```

Randomly zero out entire channels (a channel is a 3D feature map, e.g., the ![](http://latex.codecogs.com/gif.latex?j)-th channel of the ![](http://latex.codecogs.com/gif.latex?i)-th sample in the batched input is a 3D tensor ![](http://latex.codecogs.com/gif.latex?%5Ctext%7Binput%7D%5Bi%2C%20j%5D)) of the input tensor). Each channel will be zeroed out independently on every forward call. with probability `p` using samples from a Bernoulli distribution.

J
janhu 已提交
1015
[`Dropout3d`](#torch.nn.Dropout3d "torch.nn.Dropout3d") for details.
W
wizardforcel 已提交
1016 1017

 
J
janhu 已提交
1018
参数:
W
wizardforcel 已提交
1019

J
janhu 已提交
1020
*   **p** – probability of a channel to be zeroed. 默认值:  0.5
W
wizardforcel 已提交
1021
*   **training** – apply dropout if is `True`. Defualt: `True`
J
janhu 已提交
1022
*   **inplace** – If set to `True`, will do this operation in-place. 默认值:  `False`
W
wizardforcel 已提交
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038

 |
| --- | --- |

## Sparse functions

### embedding

```py
torch.nn.functional.embedding(input, weight, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False)
```

A simple lookup table that looks up embeddings in a fixed dictionary and size.

This module is often used to retrieve word embeddings using indices. The input to the module is a list of indices, and the embedding matrix, and the output is the corresponding word embeddings.

J
janhu 已提交
1039
[`torch.nn.Embedding`](#torch.nn.Embedding "torch.nn.Embedding") for more details.
W
wizardforcel 已提交
1040 1041

 
J
janhu 已提交
1042
参数:
W
wizardforcel 已提交
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066

*   **input** (_LongTensor_) – Tensor containing indices into the embedding matrix
*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – The embedding matrix with number of rows equal to the maximum possible index + 1, and number of columns equal to the embedding size
*   **padding_idx** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – If given, pads the output with the embedding vector at `padding_idx` (initialized to zeros) whenever it encounters the index.
*   **max_norm** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – If given, each embedding vector with norm larger than `max_norm` is renormalized to have norm `max_norm`. Note: this will modify `weight` in-place.
*   **norm_type** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – The p of the p-norm to compute for the `max_norm` option. Default `2`.
*   **scale_grad_by_freq** (_boolean__,_ _optional_) – If given, this will scale gradients by the inverse of frequency of the words in the mini-batch. Default `False`.
*   **sparse** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – If `True`, gradient w.r.t. `weight` will be a sparse tensor. See Notes under [`torch.nn.Embedding`](#torch.nn.Embedding "torch.nn.Embedding") for more details regarding sparse gradients.

 |
| --- | --- |

```py
Shape:
```

*   Input: LongTensor of arbitrary shape containing the indices to extract
*   ```py
    Weight: Embedding matrix of floating point type with shape (V, embedding_dim),
    ```

    where V = maximum index + 1 and embedding_dim = the embedding size
*   Output: `(*, embedding_dim)`, where `*` is the input shape

J
janhu 已提交
1067
例子:
W
wizardforcel 已提交
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105

```py
>>> # a batch of 2 samples of 4 indices each
>>> input = torch.tensor([[1,2,4,5],[4,3,2,9]])
>>> # an embedding matrix containing 10 tensors of size 3
>>> embedding_matrix = torch.rand(10, 3)
>>> F.embedding(input, embedding_matrix)
tensor([[[ 0.8490,  0.9625,  0.6753],
 [ 0.9666,  0.7761,  0.6108],
 [ 0.6246,  0.9751,  0.3618],
 [ 0.4161,  0.2419,  0.7383]],

 [[ 0.6246,  0.9751,  0.3618],
 [ 0.0237,  0.7794,  0.0528],
 [ 0.9666,  0.7761,  0.6108],
 [ 0.3385,  0.8612,  0.1867]]])

>>> # example with padding_idx
>>> weights = torch.rand(10, 3)
>>> weights[0, :].zero_()
>>> embedding_matrix = weights
>>> input = torch.tensor([[0,2,0,5]])
>>> F.embedding(input, embedding_matrix, padding_idx=0)
tensor([[[ 0.0000,  0.0000,  0.0000],
 [ 0.5609,  0.5384,  0.8720],
 [ 0.0000,  0.0000,  0.0000],
 [ 0.6262,  0.2438,  0.7471]]])

```

### embedding_bag

```py
torch.nn.functional.embedding_bag(input, weight, offsets=None, max_norm=None, norm_type=2, scale_grad_by_freq=False, mode='mean', sparse=False)
```

Computes sums, means or maxes of ‘bags’ of embeddings, without instantiating the intermediate embeddings.

J
janhu 已提交
1106
[`torch.nn.EmbeddingBag`](#torch.nn.EmbeddingBag "torch.nn.EmbeddingBag") for more details. .. include:: cuda_deterministic_backward.rst
W
wizardforcel 已提交
1107 1108

 
J
janhu 已提交
1109
参数:
W
wizardforcel 已提交
1110 1111 1112 1113 1114 1115 1116

*   **input** (_LongTensor_) – Tensor containing bags of indices into the embedding matrix
*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – The embedding matrix with number of rows equal to the maximum possible index + 1, and number of columns equal to the embedding size
*   **offsets** (_LongTensor__,_ _optional_) – Only used when `input` is 1D. `offsets` determines the starting index position of each bag (sequence) in `input`.
*   **max_norm** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – If given, each embedding vector with norm larger than `max_norm` is renormalized to have norm `max_norm`. Note: this will modify `weight` in-place.
*   **norm_type** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – The `p` in the `p`-norm to compute for the `max_norm` option. Default `2`.
*   **scale_grad_by_freq** (_boolean__,_ _optional_) – if given, this will scale gradients by the inverse of frequency of the words in the mini-batch. Default `False`. Note: this option is not supported when `mode="max"`.
J
janhu 已提交
1117
*   **mode** (_string__,_ _optional_) – `"sum"`, `"mean"` or `"max"`. Specifies the way to reduce the bag. 默认值:  `"mean"`
W
wizardforcel 已提交
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
*   **sparse** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – if `True`, gradient w.r.t. `weight` will be a sparse tensor. See Notes under [`torch.nn.Embedding`](#torch.nn.Embedding "torch.nn.Embedding") for more details regarding sparse gradients. Note: this option is not supported when `mode="max"`.

 |
| --- | --- |

Shape:

> *   `input` (LongTensor) and `offsets` (LongTensor, optional)
>     
>     
>     *   If `input` is 2D of shape `B x N`,
>         
>         
>         
>         it will be treated as `B` bags (sequences) each of fixed length `N`, and this will return `B` values aggregated in a way depending on the `mode`. `offsets` is ignored and required to be `None` in this case.
>         
>         
>     *   If `input` is 1D of shape `N`,
>         
>         
>         
>         it will be treated as a concatenation of multiple bags (sequences). `offsets` is required to be a 1D tensor containing the starting index positions of each bag in `input`. Therefore, for `offsets` of shape `B`, `input` will be viewed as having `B` bags. Empty bags (i.e., having 0-length) will have returned vectors filled by zeros.
>         
>         
> *   `weight` (Tensor): the learnable weights of the module of shape `(num_embeddings x embedding_dim)`
>     
>     
> *   `output`: aggregated embedding values of shape `B x embedding_dim`

J
janhu 已提交
1147
例子:
W
wizardforcel 已提交
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168

```py
>>> # an Embedding module containing 10 tensors of size 3
>>> embedding_matrix = torch.rand(10, 3)
>>> # a batch of 2 samples of 4 indices each
>>> input = torch.tensor([1,2,4,5,4,3,2,9])
>>> offsets = torch.tensor([0,4])
>>> F.embedding_bag(embedding_matrix, input, offsets)
tensor([[ 0.3397,  0.3552,  0.5545],
 [ 0.5893,  0.4386,  0.5882]])

```

## Distance functions

### pairwise_distance

```py
torch.nn.functional.pairwise_distance(x1, x2, p=2.0, eps=1e-06, keepdim=False)
```

J
janhu 已提交
1169
[`torch.nn.PairwiseDistance`](#torch.nn.PairwiseDistance "torch.nn.PairwiseDistance") for details
W
wizardforcel 已提交
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181

### cosine_similarity

```py
torch.nn.functional.cosine_similarity(x1, x2, dim=1, eps=1e-8)  Tensor
```

Returns cosine similarity between x1 and x2, computed along dim.

![](http://latex.codecogs.com/gif.latex?%0D%0A%5Ctext%7Bsimilarity%7D%20%3D%20%5Cdfrac%7Bx_1%20%5Ccdot%20x_2%7D%7B%5Cmax(%5CVert%20x_1%20%5CVert%20_2%20%5Ccdot%20%5CVert%20x_2%20%5CVert%20_2%2C%20%5Cepsilon)%7D%0D%0A%0D%0A)

 
J
janhu 已提交
1182
参数:
W
wizardforcel 已提交
1183 1184 1185

*   **x1** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – First input.
*   **x2** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – Second input (of size matching x1).
J
janhu 已提交
1186 1187
*   **dim** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – Dimension of vectors. 默认值:  1
*   **eps** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – Small value to avoid division by zero. 默认值:  1e-8
W
wizardforcel 已提交
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221

 |
| --- | --- |

```py
Shape:
```

*   Input: ![](http://latex.codecogs.com/gif.latex?(%5Cast_1%2C%20D%2C%20%5Cast_2)) where D is at position `dim`.
*   Output: ![](http://latex.codecogs.com/gif.latex?(%5Cast_1%2C%20%5Cast_2)) where 1 is at position `dim`.

Example:

```py
>>> input1 = torch.randn(100, 128)
>>> input2 = torch.randn(100, 128)
>>> output = F.cosine_similarity(input1, input2)
>>> print(output)

```

### pdist

```py
torch.nn.functional.pdist(input, p=2)  Tensor
```

Computes the p-norm distance between every pair of row vectors in the input. This is identical to the upper triangular portion, excluding the diagonal, of `torch.norm(input[:, None] - input, dim=2, p=p)`. This function will be faster if the rows are contiguous.

If input has shape ![](http://latex.codecogs.com/gif.latex?N%20%5Ctimes%20M) then the output will have shape ![](http://latex.codecogs.com/gif.latex?%5Cfrac%7B1%7D%7B2%7D%20N%20(N%20-%201)).

This function is equivalent to `scipy.spatial.distance.pdist(input, ‘minkowski’, p=p)` if ![](http://latex.codecogs.com/gif.latex?p%20%5Cin%20(0%2C%20%5Cinfty)). When ![](http://latex.codecogs.com/gif.latex?p%20%3D%200) it is equivalent to `scipy.spatial.distance.pdist(input, ‘hamming’) * M`. When ![](http://latex.codecogs.com/gif.latex?p%20%3D%20%5Cinfty), the closest scipy function is `scipy.spatial.distance.pdist(xn, lambda x, y: np.abs(x - y).max())`.

 
J
janhu 已提交
1222
参数:
W
wizardforcel 已提交
1223

J
janhu 已提交
1224
*   **input** – 输入tensor, 形状为 ![](http://latex.codecogs.com/gif.latex?N%20%5Ctimes%20M).
W
wizardforcel 已提交
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
*   **p** – p value for the p-norm distance to calculate between each vector pair ![](http://latex.codecogs.com/gif.latex?%5Cin%20%5B0%2C%20%5Cinfty%5D).

 |
| --- | --- |

## Loss functions

### binary_cross_entropy

```py
torch.nn.functional.binary_cross_entropy(input, target, weight=None, size_average=None, reduce=None, reduction='mean')
```

Function that measures the Binary Cross Entropy between the target and the output.

J
janhu 已提交
1240
[`BCELoss`](#torch.nn.BCELoss "torch.nn.BCELoss") for details.
W
wizardforcel 已提交
1241 1242

 
J
janhu 已提交
1243
参数:
W
wizardforcel 已提交
1244 1245 1246 1247

*   **input** – Tensor of arbitrary shape
*   **target** – Tensor of the same shape as input
*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_,_ _optional_) – a manual rescaling weight if provided it’s repeated to match input tensor shape
J
janhu 已提交
1248 1249 1250
*   **size_average** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – Deprecated (see `reduction`). By default, the losses are averaged over each loss element in the batch. Note that for some losses, there multiple elements per sample. If the field `size_average` is set to `False`, the losses are instead summed for each minibatch. Ignored when reduce is `False`. 默认值:  `True`
*   **reduce** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – Deprecated (see `reduction`). By default, the losses are averaged or summed over observations for each minibatch depending on `size_average`. When `reduce` is `False`, returns a loss per batch element instead and ignores `size_average`. 默认值:  `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ | ‘mean’ | ‘sum’. ‘none’: no reduction will be applied, ‘mean’: the sum of the output will be divided by the number of elements in the output, ‘sum’: the output will be summed. Note: `size_average` and `reduce` are in the process of being deprecated, and in the meantime, specifying either of those two args will override `reduction`. 默认值:  ‘mean’
W
wizardforcel 已提交
1251 1252 1253 1254

 |
| --- | --- |

J
janhu 已提交
1255
例子:
W
wizardforcel 已提交
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272

```py
>>> input = torch.randn((3, 2), requires_grad=True)
>>> target = torch.rand((3, 2), requires_grad=False)
>>> loss = F.binary_cross_entropy(F.sigmoid(input), target)
>>> loss.backward()

```

### binary_cross_entropy_with_logits

```py
torch.nn.functional.binary_cross_entropy_with_logits(input, target, weight=None, size_average=None, reduce=None, reduction='mean', pos_weight=None)
```

Function that measures Binary Cross Entropy between target and output logits.

J
janhu 已提交
1273
[`BCEWithLogitsLoss`](#torch.nn.BCEWithLogitsLoss "torch.nn.BCEWithLogitsLoss") for details.
W
wizardforcel 已提交
1274 1275

 
J
janhu 已提交
1276
参数:
W
wizardforcel 已提交
1277 1278 1279 1280

*   **input** – Tensor of arbitrary shape
*   **target** – Tensor of the same shape as input
*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_,_ _optional_) – a manual rescaling weight if provided it’s repeated to match input tensor shape
J
janhu 已提交
1281 1282 1283
*   **size_average** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – Deprecated (see `reduction`). By default, the losses are averaged over each loss element in the batch. Note that for some losses, there multiple elements per sample. If the field `size_average` is set to `False`, the losses are instead summed for each minibatch. Ignored when reduce is `False`. 默认值:  `True`
*   **reduce** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – Deprecated (see `reduction`). By default, the losses are averaged or summed over observations for each minibatch depending on `size_average`. When `reduce` is `False`, returns a loss per batch element instead and ignores `size_average`. 默认值:  `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ | ‘mean’ | ‘sum’. ‘none’: no reduction will be applied, ‘mean’: the sum of the output will be divided by the number of elements in the output, ‘sum’: the output will be summed. Note: `size_average` and `reduce` are in the process of being deprecated, and in the meantime, specifying either of those two args will override `reduction`. 默认值:  ‘mean’
W
wizardforcel 已提交
1284 1285 1286 1287 1288
*   **pos_weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_,_ _optional_) – a weight of positive examples. Must be a vector with length equal to the number of classes.

 |
| --- | --- |

J
janhu 已提交
1289
例子:
W
wizardforcel 已提交
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306

```py
>>> input = torch.randn(3, requires_grad=True)
>>> target = torch.empty(3).random_(2)
>>> loss = F.binary_cross_entropy_with_logits(input, target)
>>> loss.backward()

```

### poisson_nll_loss

```py
torch.nn.functional.poisson_nll_loss(input, target, log_input=True, full=False, size_average=None, eps=1e-08, reduce=None, reduction='mean')
```

Poisson negative log likelihood loss.

J
janhu 已提交
1307
[`PoissonNLLLoss`](#torch.nn.PoissonNLLLoss "torch.nn.PoissonNLLLoss") for details.
W
wizardforcel 已提交
1308 1309

 
J
janhu 已提交
1310
参数:
W
wizardforcel 已提交
1311 1312 1313

*   **input** – expectation of underlying Poisson distribution.
*   **target** – random sample ![](http://latex.codecogs.com/gif.latex?target%20%5Csim%20%5Ctext%7BPoisson%7D(input)).
J
janhu 已提交
1314 1315 1316 1317 1318 1319
*   **log_input** – if `True` the loss is computed as ![](http://latex.codecogs.com/gif.latex?%5Cexp(%5Ctext%7Binput%7D)%20-%20%5Ctext%7Btarget%7D%20*%20%5Ctext%7Binput%7D), if `False` then loss is ![](http://latex.codecogs.com/gif.latex?%5Ctext%7Binput%7D%20-%20%5Ctext%7Btarget%7D%20*%20%5Clog(%5Ctext%7Binput%7D%2B%5Ctext%7Beps%7D)). 默认值:  `True`
*   **full** – whether to compute full loss, i. e. to add the Stirling approximation term. 默认值:  `False` ![](http://latex.codecogs.com/gif.latex?%5Ctext%7Btarget%7D%20*%20%5Clog(%5Ctext%7Btarget%7D)%20-%20%5Ctext%7Btarget%7D%20%2B%200.5%20*%20%5Clog(2%20*%20%5Cpi%20*%20%5Ctext%7Btarget%7D)).
*   **size_average** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – Deprecated (see `reduction`). By default, the losses are averaged over each loss element in the batch. Note that for some losses, there multiple elements per sample. If the field `size_average` is set to `False`, the losses are instead summed for each minibatch. Ignored when reduce is `False`. 默认值:  `True`
*   **eps** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – Small value to avoid evaluation of ![](http://latex.codecogs.com/gif.latex?%5Clog(0)) when `log_input`=``False``. 默认值:  1e-8
*   **reduce** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – Deprecated (see `reduction`). By default, the losses are averaged or summed over observations for each minibatch depending on `size_average`. When `reduce` is `False`, returns a loss per batch element instead and ignores `size_average`. 默认值:  `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ | ‘mean’ | ‘sum’. ‘none’: no reduction will be applied, ‘mean’: the sum of the output will be divided by the number of elements in the output, ‘sum’: the output will be summed. Note: `size_average` and `reduce` are in the process of being deprecated, and in the meantime, specifying either of those two args will override `reduction`. 默认值:  ‘mean’
W
wizardforcel 已提交
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329

 |
| --- | --- |

### cosine_embedding_loss

```py
torch.nn.functional.cosine_embedding_loss(input1, input2, target, margin=0, size_average=None, reduce=None, reduction='mean')  Tensor
```

J
janhu 已提交
1330
[`CosineEmbeddingLoss`](#torch.nn.CosineEmbeddingLoss "torch.nn.CosineEmbeddingLoss") for details.
W
wizardforcel 已提交
1331 1332 1333 1334 1335 1336 1337 1338 1339

### cross_entropy

```py
torch.nn.functional.cross_entropy(input, target, weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean')
```

This criterion combines `log_softmax` and `nll_loss` in a single function.

J
janhu 已提交
1340
[`CrossEntropyLoss`](#torch.nn.CrossEntropyLoss "torch.nn.CrossEntropyLoss") for details.
W
wizardforcel 已提交
1341 1342

 
J
janhu 已提交
1343
参数:
W
wizardforcel 已提交
1344 1345 1346 1347

*   **input** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – ![](http://latex.codecogs.com/gif.latex?(N%2C%20C)) where `C = number of classes` or ![](http://latex.codecogs.com/gif.latex?(N%2C%20C%2C%20H%2C%20W)) in case of 2D Loss, or ![](http://latex.codecogs.com/gif.latex?(N%2C%20C%2C%20d_1%2C%20d_2%2C%20...%2C%20d_K)) where ![](http://latex.codecogs.com/gif.latex?K%20%3E%201) in the case of K-dimensional loss.
*   **target** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – ![](http://latex.codecogs.com/gif.latex?(N)) where each value is ![](http://latex.codecogs.com/gif.latex?0%20%5Cleq%20%5Ctext%7Btargets%7D%5Bi%5D%20%5Cleq%20C-1), or ![](http://latex.codecogs.com/gif.latex?(N%2C%20d_1%2C%20d_2%2C%20...%2C%20d_K)) where ![](http://latex.codecogs.com/gif.latex?K%20%5Cgeq%201) for K-dimensional loss.
*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_,_ _optional_) – a manual rescaling weight given to each class. If given, has to be a Tensor of size `C`
J
janhu 已提交
1348 1349 1350 1351
*   **size_average** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – Deprecated (see `reduction`). By default, the losses are averaged over each loss element in the batch. Note that for some losses, there multiple elements per sample. If the field `size_average` is set to `False`, the losses are instead summed for each minibatch. Ignored when reduce is `False`. 默认值:  `True`
*   **ignore_index** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – Specifies a target value that is ignored and does not contribute to the input gradient. When `size_average` is `True`, the loss is averaged over non-ignored targets. 默认值:  -100
*   **reduce** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – Deprecated (see `reduction`). By default, the losses are averaged or summed over observations for each minibatch depending on `size_average`. When `reduce` is `False`, returns a loss per batch element instead and ignores `size_average`. 默认值:  `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ | ‘mean’ | ‘sum’. ‘none’: no reduction will be applied, ‘mean’: the sum of the output will be divided by the number of elements in the output, ‘sum’: the output will be summed. Note: `size_average` and `reduce` are in the process of being deprecated, and in the meantime, specifying either of those two args will override `reduction`. 默认值:  ‘mean’
W
wizardforcel 已提交
1352 1353 1354 1355

 |
| --- | --- |

J
janhu 已提交
1356
例子:
W
wizardforcel 已提交
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373

```py
>>> input = torch.randn(3, 5, requires_grad=True)
>>> target = torch.randint(5, (3,), dtype=torch.int64)
>>> loss = F.cross_entropy(input, target)
>>> loss.backward()

```

### ctc_loss

```py
torch.nn.functional.ctc_loss(log_probs, targets, input_lengths, target_lengths, blank=0, reduction='mean')
```

The Connectionist Temporal Classification loss.

J
janhu 已提交
1374
[`CTCLoss`](#torch.nn.CTCLoss "torch.nn.CTCLoss") for details.
W
wizardforcel 已提交
1375

J
janhu 已提交
1376
注意
W
wizardforcel 已提交
1377

J
janhu 已提交
1378
在某些情况下, 当使用CUDA后端与CuDNN时, 该操作符可能会选择不确定性算法来提高性能. 如果这不是您希望的, 您可以通过设置`torch.backends.cudn .deterministic = True`来尝试使操作具有确定性(可能会以性能为代价). 请参阅关于 [Reproducibility](notes/randomness.html) 了解背景.
W
wizardforcel 已提交
1379

J
janhu 已提交
1380
注意
W
wizardforcel 已提交
1381 1382 1383 1384

When using the CUDA backend, this operation may induce nondeterministic behaviour in be backward that is not easily switched off. Please see the notes on [Reproducibility](notes/randomness.html) for background.

 
J
janhu 已提交
1385
参数:
W
wizardforcel 已提交
1386 1387 1388 1389 1390 1391

*   **log_probs** – ![](http://latex.codecogs.com/gif.latex?(T%2C%20N%2C%20C)) where `C = number of characters in alphabet including blank`, `T = input length`, and `N = batch size`. The logarithmized probabilities of the outputs (e.g. obtained with [`torch.nn.functional.log_softmax()`](#torch.nn.functional.log_softmax "torch.nn.functional.log_softmax")).
*   **targets** – ![](http://latex.codecogs.com/gif.latex?(N%2C%20S)) or `(sum(target_lengths))`. Targets (cannot be blank). In the second form, the targets are assumed to be concatenated.
*   **input_lengths** – ![](http://latex.codecogs.com/gif.latex?(N)). Lengths of the inputs (must each be ![](http://latex.codecogs.com/gif.latex?%5Cleq%20T))
*   **target_lengths** – ![](http://latex.codecogs.com/gif.latex?(N)). Lengths of the targets
*   **blank** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – Blank label. Default ![](http://latex.codecogs.com/gif.latex?0).
J
janhu 已提交
1392
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ | ‘mean’ | ‘sum’. ‘none’: no reduction will be applied, ‘mean’: the output losses will be divided by the target lengths and then the mean over the batch is taken. 默认值:  ‘mean’
W
wizardforcel 已提交
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414

 |
| --- | --- |

Example:

```py
>>> log_probs = torch.randn(50, 16, 20).log_softmax(2).detach().requires_grad_()
>>> targets = torch.randint(1, 20, (16, 30), dtype=torch.long)
>>> input_lengths = torch.full((16,), 50, dtype=torch.long)
>>> target_lengths = torch.randint(10,30,(16,), dtype=torch.long)
>>> loss = F.ctc_loss(log_probs, targets, input_lengths, target_lengths)
>>> loss.backward()

```

### hinge_embedding_loss

```py
torch.nn.functional.hinge_embedding_loss(input, target, margin=1.0, size_average=None, reduce=None, reduction='mean')  Tensor
```

J
janhu 已提交
1415
[`HingeEmbeddingLoss`](#torch.nn.HingeEmbeddingLoss "torch.nn.HingeEmbeddingLoss") for details.
W
wizardforcel 已提交
1416 1417 1418 1419 1420 1421 1422 1423 1424

### kl_div

```py
torch.nn.functional.kl_div(input, target, size_average=None, reduce=None, reduction='mean')
```

The [Kullback-Leibler divergence](https://en.wikipedia.org/wiki/Kullback-Leibler_divergence) Loss.

J
janhu 已提交
1425
[`KLDivLoss`](#torch.nn.KLDivLoss "torch.nn.KLDivLoss") for details.
W
wizardforcel 已提交
1426 1427

 
J
janhu 已提交
1428
参数:
W
wizardforcel 已提交
1429 1430 1431

*   **input** – Tensor of arbitrary shape
*   **target** – Tensor of the same shape as input
J
janhu 已提交
1432 1433 1434
*   **size_average** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – Deprecated (see `reduction`). By default, the losses are averaged over each loss element in the batch. Note that for some losses, there multiple elements per sample. If the field `size_average` is set to `False`, the losses are instead summed for each minibatch. Ignored when reduce is `False`. 默认值:  `True`
*   **reduce** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – Deprecated (see `reduction`). By default, the losses are averaged or summed over observations for each minibatch depending on `size_average`. When `reduce` is `False`, returns a loss per batch element instead and ignores `size_average`. 默认值:  `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ | ‘batchmean’ | ‘sum’ | ‘mean’. ‘none’: no reduction will be applied ‘batchmean’: the sum of the output will be divided by the batchsize ‘sum’: the output will be summed ‘mean’: the output will be divided by the number of elements in the output 默认值:  ‘mean’
W
wizardforcel 已提交
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450

 |
| --- | --- |

:param .. note:: `size_average` and `reduce` are in the process of being deprecated,: and in the meantime, specifying either of those two args will override `reduction`. :param .. note:: `reduction=’mean’` doesn’t return the true kl divergence value, please use: `reduction=’batchmean’` which aligns with KL math definition.

> In the next major release, ‘mean’ will be changed to be the same as ‘batchmean’.

### l1_loss

```py
torch.nn.functional.l1_loss(input, target, size_average=None, reduce=None, reduction='mean')  Tensor
```

Function that takes the mean element-wise absolute value difference.

J
janhu 已提交
1451
[`L1Loss`](#torch.nn.L1Loss "torch.nn.L1Loss") for details.
W
wizardforcel 已提交
1452 1453 1454 1455 1456 1457 1458 1459 1460

### mse_loss

```py
torch.nn.functional.mse_loss(input, target, size_average=None, reduce=None, reduction='mean')  Tensor
```

Measures the element-wise mean squared error.

J
janhu 已提交
1461
[`MSELoss`](#torch.nn.MSELoss "torch.nn.MSELoss") for details.
W
wizardforcel 已提交
1462 1463 1464 1465 1466 1467 1468

### margin_ranking_loss

```py
torch.nn.functional.margin_ranking_loss(input1, input2, target, margin=0, size_average=None, reduce=None, reduction='mean')  Tensor
```

J
janhu 已提交
1469
[`MarginRankingLoss`](#torch.nn.MarginRankingLoss "torch.nn.MarginRankingLoss") for details.
W
wizardforcel 已提交
1470 1471 1472 1473 1474 1475 1476

### multilabel_margin_loss

```py
torch.nn.functional.multilabel_margin_loss(input, target, size_average=None, reduce=None, reduction='mean')  Tensor
```

J
janhu 已提交
1477
[`MultiLabelMarginLoss`](#torch.nn.MultiLabelMarginLoss "torch.nn.MultiLabelMarginLoss") for details.
W
wizardforcel 已提交
1478 1479 1480 1481 1482 1483 1484

### multilabel_soft_margin_loss

```py
torch.nn.functional.multilabel_soft_margin_loss(input, target, weight=None, size_average=None)  Tensor
```

J
janhu 已提交
1485
[`MultiLabelSoftMarginLoss`](#torch.nn.MultiLabelSoftMarginLoss "torch.nn.MultiLabelSoftMarginLoss") for details.
W
wizardforcel 已提交
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498

### multi_margin_loss

```py
torch.nn.functional.multi_margin_loss(input, target, p=1, margin=1.0, weight=None, size_average=None, reduce=None, reduction='mean')
```

```py
multi_margin_loss(input, target, p=1, margin=1, weight=None, size_average=None,
```

reduce=None, reduction=’mean’) -> Tensor

J
janhu 已提交
1499
[`MultiMarginLoss`](#torch.nn.MultiMarginLoss "torch.nn.MultiMarginLoss") for details.
W
wizardforcel 已提交
1500 1501 1502 1503 1504 1505 1506 1507 1508

### nll_loss

```py
torch.nn.functional.nll_loss(input, target, weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean')
```

The negative log likelihood loss.

J
janhu 已提交
1509
[`NLLLoss`](#torch.nn.NLLLoss "torch.nn.NLLLoss") for details.
W
wizardforcel 已提交
1510 1511

 
J
janhu 已提交
1512
参数:
W
wizardforcel 已提交
1513 1514 1515 1516

*   **input** – ![](http://latex.codecogs.com/gif.latex?(N%2C%20C)) where `C = number of classes` or ![](http://latex.codecogs.com/gif.latex?(N%2C%20C%2C%20H%2C%20W)) in case of 2D Loss, or ![](http://latex.codecogs.com/gif.latex?(N%2C%20C%2C%20d_1%2C%20d_2%2C%20...%2C%20d_K)) where ![](http://latex.codecogs.com/gif.latex?K%20%3E%201) in the case of K-dimensional loss.
*   **target** – ![](http://latex.codecogs.com/gif.latex?(N)) where each value is ![](http://latex.codecogs.com/gif.latex?0%20%5Cleq%20%5Ctext%7Btargets%7D%5Bi%5D%20%5Cleq%20C-1), or ![](http://latex.codecogs.com/gif.latex?(N%2C%20d_1%2C%20d_2%2C%20...%2C%20d_K)) where ![](http://latex.codecogs.com/gif.latex?K%20%5Cgeq%201) for K-dimensional loss.
*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_,_ _optional_) – a manual rescaling weight given to each class. If given, has to be a Tensor of size `C`
J
janhu 已提交
1517 1518 1519 1520
*   **size_average** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – Deprecated (see `reduction`). By default, the losses are averaged over each loss element in the batch. Note that for some losses, there multiple elements per sample. If the field `size_average` is set to `False`, the losses are instead summed for each minibatch. Ignored when reduce is `False`. 默认值:  `True`
*   **ignore_index** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – Specifies a target value that is ignored and does not contribute to the input gradient. When `size_average` is `True`, the loss is averaged over non-ignored targets. 默认值:  -100
*   **reduce** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – Deprecated (see `reduction`). By default, the losses are averaged or summed over observations for each minibatch depending on `size_average`. When `reduce` is `False`, returns a loss per batch element instead and ignores `size_average`. 默认值:  `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ | ‘mean’ | ‘sum’. ‘none’: no reduction will be applied, ‘mean’: the sum of the output will be divided by the number of elements in the output, ‘sum’: the output will be summed. Note: `size_average` and `reduce` are in the process of being deprecated, and in the meantime, specifying either of those two args will override `reduction`. 默认值:  ‘mean’
W
wizardforcel 已提交
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544

 |
| --- | --- |

Example:

```py
>>> # input is of size N x C = 3 x 5
>>> input = torch.randn(3, 5, requires_grad=True)
>>> # each element in target has to have 0 <= value < C
>>> target = torch.tensor([1, 0, 4])
>>> output = F.nll_loss(F.log_softmax(input), target)
>>> output.backward()

```

### smooth_l1_loss

```py
torch.nn.functional.smooth_l1_loss(input, target, size_average=None, reduce=None, reduction='mean')
```

Function that uses a squared term if the absolute element-wise error falls below 1 and an L1 term otherwise.

J
janhu 已提交
1545
[`SmoothL1Loss`](#torch.nn.SmoothL1Loss "torch.nn.SmoothL1Loss") for details.
W
wizardforcel 已提交
1546 1547 1548 1549 1550 1551 1552

### soft_margin_loss

```py
torch.nn.functional.soft_margin_loss(input, target, size_average=None, reduce=None, reduction='mean')  Tensor
```

J
janhu 已提交
1553
[`SoftMarginLoss`](#torch.nn.SoftMarginLoss "torch.nn.SoftMarginLoss") for details.
W
wizardforcel 已提交
1554 1555 1556 1557 1558 1559 1560

### triplet_margin_loss

```py
torch.nn.functional.triplet_margin_loss(anchor, positive, negative, margin=1.0, p=2, eps=1e-06, swap=False, size_average=None, reduce=None, reduction='mean')
```

J
janhu 已提交
1561
[`TripletMarginLoss`](#torch.nn.TripletMarginLoss "torch.nn.TripletMarginLoss") for details
W
wizardforcel 已提交
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572

## Vision functions

### pixel_shuffle

```py
torch.nn.functional.pixel_shuffle()
```

Rearranges elements in a tensor of shape ![](http://latex.codecogs.com/gif.latex?(*%2C%20C%20%5Ctimes%20r%5E2%2C%20H%2C%20W)) to a tensor of shape ![](http://latex.codecogs.com/gif.latex?(C%2C%20H%20%5Ctimes%20r%2C%20W%20%5Ctimes%20r)).

J
janhu 已提交
1573
[`PixelShuffle`](#torch.nn.PixelShuffle "torch.nn.PixelShuffle") for details.
W
wizardforcel 已提交
1574 1575

 
J
janhu 已提交
1576
参数:
W
wizardforcel 已提交
1577 1578 1579 1580 1581 1582 1583

*   **input** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – the input tensor
*   **upscale_factor** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – factor to increase spatial resolution by

 |
| --- | --- |

J
janhu 已提交
1584
例子:
W
wizardforcel 已提交
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611

```py
>>> input = torch.randn(1, 9, 4, 4)
>>> output = torch.nn.functional.pixel_shuffle(input, 3)
>>> print(output.size())
torch.Size([1, 1, 12, 12])

```

### pad

```py
torch.nn.functional.pad(input, pad, mode='constant', value=0)
```

Pads tensor.

```py
Pading size:
```

The number of dimensions to pad is ![](http://latex.codecogs.com/gif.latex?%5Cleft%5Clfloor%5Cfrac%7B%5Ctext%7Blen(pad)%7D%7D%7B2%7D%5Cright%5Crfloor) and the dimensions that get padded begins with the last dimension and moves forward. For example, to pad the last dimension of the input tensor, then <cite>pad</cite> has form <cite>(padLeft, padRight)</cite>; to pad the last 2 dimensions of the input tensor, then use <cite>(padLeft, padRight, padTop, padBottom)</cite>; to pad the last 3 dimensions, use <cite>(padLeft, padRight, padTop, padBottom, padFront, padBack)</cite>.

```py
Padding mode:
```

J
janhu 已提交
1612
[`torch.nn.ConstantPad2d`](#torch.nn.ConstantPad2d "torch.nn.ConstantPad2d"), [`torch.nn.ReflectionPad2d`](#torch.nn.ReflectionPad2d "torch.nn.ReflectionPad2d"), and [`torch.nn.ReplicationPad2d`](#torch.nn.ReplicationPad2d "torch.nn.ReplicationPad2d") for concrete examples on how each of the padding modes works. Constant padding is implemented for arbitrary dimensions. Replicate padding is implemented for padding the last 3 dimensions of 5D input tensor, or the last 2 dimensions of 4D input tensor, or the last dimension of 3D input tensor. Reflect padding is only implemented for padding the last 2 dimensions of 4D input tensor, or the last dimension of 3D input tensor.
W
wizardforcel 已提交
1613

J
janhu 已提交
1614
注意
W
wizardforcel 已提交
1615 1616 1617 1618

When using the CUDA backend, this operation may induce nondeterministic behaviour in be backward that is not easily switched off. Please see the notes on [Reproducibility](notes/randomness.html) for background.

 
J
janhu 已提交
1619
参数:
W
wizardforcel 已提交
1620 1621 1622

*   **input** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – `Nd` tensor
*   **pad** ([_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – m-elem tuple, where ![](http://latex.codecogs.com/gif.latex?%5Cfrac%7Bm%7D%7B2%7D%20%5Cleq) input dimensions and ![](http://latex.codecogs.com/gif.latex?m) is even.
J
janhu 已提交
1623 1624
*   **mode** – ‘constant’, ‘reflect’ or ‘replicate’. 默认值:  ‘constant’
*   **value** – fill value for ‘constant’ padding. 默认值:  0
W
wizardforcel 已提交
1625 1626 1627 1628

 |
| --- | --- |

J
janhu 已提交
1629
例子:
W
wizardforcel 已提交
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665

```py
>>> t4d = torch.empty(3, 3, 4, 2)
>>> p1d = (1, 1) # pad last dim by 1 on each side
>>> out = F.pad(t4d, p1d, "constant", 0)  # effectively zero padding
>>> print(out.data.size())
torch.Size([3, 3, 4, 4])
>>> p2d = (1, 1, 2, 2) # pad last dim by (1, 1) and 2nd to last by (2, 2)
>>> out = F.pad(t4d, p2d, "constant", 0)
>>> print(out.data.size())
torch.Size([3, 3, 8, 4])
>>> t4d = torch.empty(3, 3, 4, 2)
>>> p3d = (0, 1, 2, 1, 3, 3) # pad by (0, 1), (2, 1), and (3, 3)
>>> out = F.pad(t4d, p3d, "constant", 0)
>>> print(out.data.size())
torch.Size([3, 9, 7, 3])

```

### interpolate

```py
torch.nn.functional.interpolate(input, size=None, scale_factor=None, mode='nearest', align_corners=None)
```

Down/up samples the input to either the given `size` or the given `scale_factor`

The algorithm used for interpolation is determined by `mode`.

Currently temporal, spatial and volumetric sampling are supported, i.e. expected inputs are 3-D, 4-D or 5-D in shape.

The input dimensions are interpreted in the form: `mini-batch x channels x [optional depth] x [optional height] x width`.

The modes available for resizing are: `nearest`, `linear` (3D-only), `bilinear` (4D-only), `trilinear` (5D-only), `area`

 
J
janhu 已提交
1666
参数:
W
wizardforcel 已提交
1667 1668 1669 1670

*   **input** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – the input tensor
*   **size** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ _Tuple__[_[_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_] or_ _Tuple__[_[_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_] or_ _Tuple__[_[_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_]_) – output spatial size.
*   **scale_factor** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)") _or_ _Tuple__[_[_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_]_) – multiplier for spatial size. Has to match input size if it is a tuple.
J
janhu 已提交
1671 1672
*   **mode** (_string_) – algorithm used for upsampling: ‘nearest’ &#124; ‘linear’ &#124; ‘bilinear’ &#124; ‘trilinear’ &#124; ‘area’. 默认值:  ‘nearest’
*   **align_corners** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – if True, the corner pixels of the input and output tensors are aligned, and thus preserving the values at those pixels. This only has effect when `mode` is `linear`, `bilinear`, or `trilinear`. 默认值:  False
W
wizardforcel 已提交
1673 1674 1675 1676

 |
| --- | --- |

J
janhu 已提交
1677
警告
W
wizardforcel 已提交
1678

J
janhu 已提交
1679
With `align_corners = True`, the linearly interpolating modes (`linear`, `bilinear`, and `trilinear`) don’t proportionally align the output and input pixels, and thus the output values can depend on the input size. This was the default behavior for these modes up to version 0.3.1\. Since then, the default behavior is `align_corners = False`. 见 [`Upsample`](#torch.nn.Upsample "torch.nn.Upsample") for concrete examples on how this affects the outputs.
W
wizardforcel 已提交
1680

J
janhu 已提交
1681
注意
W
wizardforcel 已提交
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692

When using the CUDA backend, this operation may induce nondeterministic behaviour in be backward that is not easily switched off. Please see the notes on [Reproducibility](notes/randomness.html) for background.

### upsample

```py
torch.nn.functional.upsample(input, size=None, scale_factor=None, mode='nearest', align_corners=None)
```

Upsamples the input to either the given `size` or the given `scale_factor`

J
janhu 已提交
1693
警告
W
wizardforcel 已提交
1694 1695 1696

This function is deprecated in favor of [`torch.nn.functional.interpolate()`](#torch.nn.functional.interpolate "torch.nn.functional.interpolate"). This is equivalent with `nn.functional.interpolate(...)`.

J
janhu 已提交
1697
注意
W
wizardforcel 已提交
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709

When using the CUDA backend, this operation may induce nondeterministic behaviour in be backward that is not easily switched off. Please see the notes on [Reproducibility](notes/randomness.html) for background.

The algorithm used for upsampling is determined by `mode`.

Currently temporal, spatial and volumetric upsampling are supported, i.e. expected inputs are 3-D, 4-D or 5-D in shape.

The input dimensions are interpreted in the form: `mini-batch x channels x [optional depth] x [optional height] x width`.

The modes available for upsampling are: `nearest`, `linear` (3D-only), `bilinear` (4D-only), `trilinear` (5D-only)

 
J
janhu 已提交
1710
参数:
W
wizardforcel 已提交
1711 1712 1713 1714

*   **input** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – the input tensor
*   **size** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ _Tuple__[_[_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_] or_ _Tuple__[_[_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_] or_ _Tuple__[_[_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_]_) – output spatial size.
*   **scale_factor** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – multiplier for spatial size. Has to be an integer.
J
janhu 已提交
1715 1716
*   **mode** (_string_) – algorithm used for upsampling: ‘nearest’ &#124; ‘linear’ &#124; ‘bilinear’ &#124; ‘trilinear’. 默认值:  ‘nearest’
*   **align_corners** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – if True, the corner pixels of the input and output tensors are aligned, and thus preserving the values at those pixels. This only has effect when `mode` is `linear`, `bilinear`, or `trilinear`. 默认值:  False
W
wizardforcel 已提交
1717 1718 1719 1720

 |
| --- | --- |

J
janhu 已提交
1721
警告
W
wizardforcel 已提交
1722

J
janhu 已提交
1723
With `align_corners = True`, the linearly interpolating modes (`linear`, `bilinear`, and `trilinear`) don’t proportionally align the output and input pixels, and thus the output values can depend on the input size. This was the default behavior for these modes up to version 0.3.1\. Since then, the default behavior is `align_corners = False`. 见 [`Upsample`](#torch.nn.Upsample "torch.nn.Upsample") for concrete examples on how this affects the outputs.
W
wizardforcel 已提交
1724 1725 1726 1727 1728 1729 1730 1731 1732

### upsample_nearest

```py
torch.nn.functional.upsample_nearest(input, size=None, scale_factor=None)
```

Upsamples the input, using nearest neighbours’ pixel values.

J
janhu 已提交
1733
警告
W
wizardforcel 已提交
1734 1735 1736 1737 1738 1739

This function is deprecated in favor of [`torch.nn.functional.interpolate()`](#torch.nn.functional.interpolate "torch.nn.functional.interpolate"). This is equivalent with `nn.functional.interpolate(..., mode='nearest')`.

Currently spatial and volumetric upsampling are supported (i.e. expected inputs are 4 or 5 dimensional).

 
J
janhu 已提交
1740
参数:
W
wizardforcel 已提交
1741 1742 1743 1744 1745 1746 1747 1748

*   **input** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – input
*   **size** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ _Tuple__[_[_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_] or_ _Tuple__[_[_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_]_) – output spatia size.
*   **scale_factor** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – multiplier for spatial size. Has to be an integer.

 |
| --- | --- |

J
janhu 已提交
1749
注意
W
wizardforcel 已提交
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760

When using the CUDA backend, this operation may induce nondeterministic behaviour in be backward that is not easily switched off. Please see the notes on [Reproducibility](notes/randomness.html) for background.

### upsample_bilinear

```py
torch.nn.functional.upsample_bilinear(input, size=None, scale_factor=None)
```

Upsamples the input, using bilinear upsampling.

J
janhu 已提交
1761
警告
W
wizardforcel 已提交
1762 1763 1764 1765 1766 1767

This function is deprecated in favor of [`torch.nn.functional.interpolate()`](#torch.nn.functional.interpolate "torch.nn.functional.interpolate"). This is equivalent with `nn.functional.interpolate(..., mode='bilinear', align_corners=True)`.

Expected inputs are spatial (4 dimensional). Use `upsample_trilinear` fo volumetric (5 dimensional) inputs.

 
J
janhu 已提交
1768
参数:
W
wizardforcel 已提交
1769 1770 1771 1772 1773 1774 1775 1776

*   **input** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – input
*   **size** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ _Tuple__[_[_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_]_) – output spatial size.
*   **scale_factor** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ _Tuple__[_[_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_]_) – multiplier for spatial size

 |
| --- | --- |

J
janhu 已提交
1777
注意
W
wizardforcel 已提交
1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802

When using the CUDA backend, this operation may induce nondeterministic behaviour in be backward that is not easily switched off. Please see the notes on [Reproducibility](notes/randomness.html) for background.

### grid_sample

```py
torch.nn.functional.grid_sample(input, grid, mode='bilinear', padding_mode='zeros')
```

Given an `input` and a flow-field `grid`, computes the `output` using `input` values and pixel locations from `grid`.

Currently, only spatial (4-D) and volumetric (5-D) `input` are supported.

In the spatial (4-D) case, for `input` with shape ![](http://latex.codecogs.com/gif.latex?(N%2C%20C%2C%20H_%5Ctext%7Bin%7D%2C%20W_%5Ctext%7Bin%7D)) and `grid` with shape ![](http://latex.codecogs.com/gif.latex?(N%2C%20H_%5Ctext%7Bout%7D%2C%20W_%5Ctext%7Bout%7D%2C%202)), the output will have shape ![](http://latex.codecogs.com/gif.latex?(N%2C%20C%2C%20H_%5Ctext%7Bout%7D%2C%20W_%5Ctext%7Bout%7D)).

For each output location `output[n, :, h, w]`, the size-2 vector `grid[n, h, w]` specifies `input` pixel locations `x` and `y`, which are used to interpolate the output value `output[n, :, h, w]`. In the case of 5D inputs, `grid[n, d, h, w]` specifies the `x`, `y`, `z` pixel locations for interpolating `output[n, :, d, h, w]`. `mode` argument specifies `nearest` or `bilinear` interpolation method to sample the input pixels.

`grid` should have most values in the range of `[-1, 1]`. This is because the pixel locations are normalized by the `input` spatial dimensions. For example, values `x = -1, y = -1` is the left-top pixel of `input`, and values `x = 1, y = 1` is the right-bottom pixel of `input`.

If `grid` has values outside the range of `[-1, 1]`, those locations are handled as defined by `padding_mode`. Options are

> *   `padding_mode="zeros"`: use `0` for out-of-bound values,
> *   `padding_mode="border"`: use border values for out-of-bound values,
> *   `padding_mode="reflection"`: use values at locations reflected by the border for out-of-bound values. For location far away from the border, it will keep being reflected until becoming in bound, e.g., (normalized) pixel location `x = -3.5` reflects by `-1` and becomes `x' = 2.5`, then reflects by border `1` and becomes `x'' = -0.5`.

J
janhu 已提交
1803
注意
W
wizardforcel 已提交
1804 1805 1806

This function is often used in building Spatial Transformer Networks.

J
janhu 已提交
1807
注意
W
wizardforcel 已提交
1808 1809 1810 1811

When using the CUDA backend, this operation may induce nondeterministic behaviour in be backward that is not easily switched off. Please see the notes on [Reproducibility](notes/randomness.html) for background.

 
J
janhu 已提交
1812
参数:
W
wizardforcel 已提交
1813 1814 1815

*   **input** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – input of shape ![](http://latex.codecogs.com/gif.latex?(N%2C%20C%2C%20H_%5Ctext%7Bin%7D%2C%20W_%5Ctext%7Bin%7D)) (4-D case) or ![](http://latex.codecogs.com/gif.latex?(N%2C%20C%2C%20D_%5Ctext%7Bin%7D%2C%20H_%5Ctext%7Bin%7D%2C%20W_%5Ctext%7Bin%7D)) (5-D case)
*   **grid** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – flow-field of shape ![](http://latex.codecogs.com/gif.latex?(N%2C%20H_%5Ctext%7Bout%7D%2C%20W_%5Ctext%7Bout%7D%2C%202)) (4-D case) or ![](http://latex.codecogs.com/gif.latex?(N%2C%20D_%5Ctext%7Bout%7D%2C%20H_%5Ctext%7Bout%7D%2C%20W_%5Ctext%7Bout%7D%2C%203)) (5-D case)
J
janhu 已提交
1816 1817
*   **mode** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – interpolation mode to calculate output values ‘bilinear’ &#124; ‘nearest’. 默认值:  ‘bilinear’
*   **padding_mode** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – padding mode for outside grid values ‘zeros’ &#124; ‘border’ &#124; ‘reflection’. 默认值:  ‘zeros’
W
wizardforcel 已提交
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834

 |
| --- | --- |
| Returns: | output Tensor |
| --- | --- |
| Return type: | output ([Tensor](tensors.html#torch.Tensor "torch.Tensor")) |
| --- | --- |

### affine_grid

```py
torch.nn.functional.affine_grid(theta, size)
```

Generates a 2d flow field, given a batch of affine matrices `theta` Generally used in conjunction with [`grid_sample()`](#torch.nn.functional.grid_sample "torch.nn.functional.grid_sample") to implement Spatial Transformer Networks.

 
J
janhu 已提交
1835
参数:
W
wizardforcel 已提交
1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859

*   **theta** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – input batch of affine matrices (![](http://latex.codecogs.com/gif.latex?N%20%5Ctimes%202%20%5Ctimes%203))
*   **size** (_torch.Size_) – the target output image size (![](http://latex.codecogs.com/gif.latex?N%20%5Ctimes%20C%20%5Ctimes%20H%20%5Ctimes%20W)) Example: torch.Size((32, 3, 24, 24))

 |
| --- | --- |
| Returns: | output Tensor of size (![](http://latex.codecogs.com/gif.latex?N%20%5Ctimes%20H%20%5Ctimes%20W%20%5Ctimes%202)) |
| --- | --- |
| Return type: | output ([Tensor](tensors.html#torch.Tensor "torch.Tensor")) |
| --- | --- |

## DataParallel functions (multi-GPU, distributed)

### data_parallel

```py
torch.nn.parallel.data_parallel(module, inputs, device_ids=None, output_device=None, dim=0, module_kwargs=None)
```

Evaluates module(input) in parallel across the GPUs given in device_ids.

This is the functional version of the DataParallel module.

 
J
janhu 已提交
1860
参数:
W
wizardforcel 已提交
1861 1862 1863 1864

*   **module** ([_Module_](#torch.nn.Module "torch.nn.Module")) – the module to evaluate in parallel
*   **inputs** (_tensor_) – inputs to the module
*   **device_ids** (_list of python:int_ _or_ [_torch.device_](tensor_attributes.html#torch.torch.device "torch.torch.device")) – GPU ids on which to replicate module
J
janhu 已提交
1865
*   **output_device** (_list of python:int_ _or_ [_torch.device_](tensor_attributes.html#torch.torch.device "torch.torch.device")) – GPU location of the output Use -1 to indicate the CPU. (默认值:  device_ids[0])
W
wizardforcel 已提交
1866 1867 1868 1869 1870

 |
| --- | --- |
| Returns: | a Tensor containing the result of module(input) located on output_device |
| --- | --- |