nn.md 300.7 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4


# torch.nn

C
chen 已提交
5
## Parameters(参数)
W
wizardforcel 已提交
6 7

```py
W
wizardforcel 已提交
8
class torch.nn.Parameter
W
wizardforcel 已提交
9 10
```

C
chen 已提交
11 12

Parameters对象是一种会被视为模块参数(module parameter)的Tensor张量。
W
wizardforcel 已提交
13

C
chen 已提交
14
Parameters类是[`Tensor`](tensors.html#torch.Tensor "torch.Tensor") 的子类, 不过相对于它的父类,Parameters类有一个很重要的特性就是当其在 [`Module`](#torch.nn.Module "torch.nn.Module")类中被使用并被当做这个[`Module`](#torch.nn.Module "torch.nn.Module")类的模块属性的时候,那么这个Parameters对象会被自动地添加到这个[`Module`](#torch.nn.Module "torch.nn.Module")类的参数列表(list of parameters)之中,同时也就会被添加入此[`Module`](#torch.nn.Module "torch.nn.Module")类的 [`parameters()`](#torch.nn.Module.parameters "torch.nn.Module.parameters")方法所返回的参数迭代器中。而Parameters类的父类Tensor类也可以被用为构建模块的属性,但不会被加入参数列表。这样主要是因为,有时可能需要在模型中存储一些非模型参数的临时状态,比如RNN中的最后一个隐状态。而通过使用非[`Parameter`](#torch.nn.Parameter "torch.nn.Parameter")的Tensor类,可以将这些临时变量注册(register)为模型的属性的同时使其不被加入参数列表。
W
wizardforcel 已提交
15

W
wizardforcel 已提交
16
Parameters: 
W
wizardforcel 已提交
17

C
chen 已提交
18 19
*   **data** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – 参数张量(parameter tensor).
*   **requires_grad** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – 参数是否需要梯度, 默认为 `True`。更多细节请看 [如何将子图踢出反向传播过程](notes/autograd.html#excluding-subgraphs)
W
wizardforcel 已提交
20

W
wizardforcel 已提交
21

W
wizardforcel 已提交
22

C
chen 已提交
23
## Containers(容器)
W
wizardforcel 已提交
24

C
chen 已提交
25
### Module(模块)
W
wizardforcel 已提交
26 27

```py
W
wizardforcel 已提交
28
class torch.nn.Module
W
wizardforcel 已提交
29 30
```

C
chen 已提交
31
模块(Module)是所有神经网络模型的基类。
W
wizardforcel 已提交
32

C
chen 已提交
33
你创建模型的时候也应该继承这个类哦。
W
wizardforcel 已提交
34

C
chen 已提交
35
模块(Module)中还可以包含其他的模块,你可以将一个模块赋值成为另一个模块的属性,从而成为这个模块的一个子模块。而通过不断的赋值,你可以将不同的模块组织成一个树结构:
W
wizardforcel 已提交
36 37 38 39 40 41 42 43

```py
import torch.nn as nn
import torch.nn.functional as F

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
C
chen 已提交
44
        self.conv1 = nn.Conv2d(1, 20, 5) # 当前的nn.Conv2d模块就被赋值成为Model模块的一个子模块,成为“树结构”的叶子
W
wizardforcel 已提交
45 46 47 48 49 50 51 52
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
       x = F.relu(self.conv1(x))
       return F.relu(self.conv2(x))

```

C
chen 已提交
53
通过赋值这种方式添加的子模块将会被模型注册(register),而后当调用模块的一些参数转换函数([`to()`](#torch.nn.Module.to "torch.nn.Module.to"))的时候,子模块的参数也会一并转换。
W
wizardforcel 已提交
54 55

```py
W
wizardforcel 已提交
56
add_module(name, module)
W
wizardforcel 已提交
57
```
C
chen 已提交
58 59
向当前模块添加一个子模块。
此子模块可以作为当前模块的属性被访问到,而属性名就是add_module()函数中的name参数。
W
wizardforcel 已提交
60

C
chen 已提交
61
add_module()函数参数: 
W
wizardforcel 已提交
62

C
chen 已提交
63 64
*   **name** (_string_) – 子模块的名字. 函数调用完成后,可以通过访问当前模块的此字段来访问该子模块。
*   **parameter** ([_Module_](#torch.nn.Module "torch.nn.Module")) – 要添加到当前模块的子模块。
W
wizardforcel 已提交
65

W
wizardforcel 已提交
66

W
wizardforcel 已提交
67 68

```py
W
wizardforcel 已提交
69
apply(fn)
W
wizardforcel 已提交
70 71 72
```


C
chen 已提交
73 74 75
apply()函数的主要作用是将 `fn` 递归地应用于模块的所有子模块(`.children()`函数的返回值)以及模块自身。此函数的一个经典应用就是初始化模型的所有参数这一过程(同样参见于 torch-nn-init)。

| Parameters: | **fn** ([`Module`](#torch.nn.Module "torch.nn.Module") -> None) – 要应用于所有子模型的函数 |
W
wizardforcel 已提交
76 77 78 79 80 81
| --- | --- |
| Returns: | self |
| --- | --- |
| Return type: | [Module](#torch.nn.Module "torch.nn.Module") |
| --- | --- |

C
chen 已提交
82
例子:
W
wizardforcel 已提交
83 84 85 86 87 88 89 90 91

```py
>>> def init_weights(m):
 print(m)
 if type(m) == nn.Linear:
 m.weight.data.fill_(1.0)
 print(m.weight)

>>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
C
chen 已提交
92
>>> net.apply(init_weights) # 将init_weights()函数应用于模块的所有子模块
W
wizardforcel 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[ 1.,  1.],
 [ 1.,  1.]])
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[ 1.,  1.],
 [ 1.,  1.]])
Sequential(
 (0): Linear(in_features=2, out_features=2, bias=True)
 (1): Linear(in_features=2, out_features=2, bias=True)
)
Sequential(
 (0): Linear(in_features=2, out_features=2, bias=True)
 (1): Linear(in_features=2, out_features=2, bias=True)
)

```

```py
W
wizardforcel 已提交
113
buffers(recurse=True)
W
wizardforcel 已提交
114
```
C
chen 已提交
115
返回模块的缓冲区的迭代器
W
wizardforcel 已提交
116

C
chen 已提交
117
| Parameters: | **recurse** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")) – 如果设置为True,产生的缓冲区迭代器会遍历模块自己与所有子模块,否则只会遍历模块的直连的成员。 |
W
wizardforcel 已提交
118
| --- | --- |
C
chen 已提交
119
| Yields: | _torch.Tensor_ – 模型缓冲区 |
W
wizardforcel 已提交
120 121
| --- | --- |

C
chen 已提交
122
举例:
W
wizardforcel 已提交
123 124 125 126 127 128 129 130 131 132

```py
>>> for buf in model.buffers():
>>>     print(type(buf.data), buf.size())
<class 'torch.FloatTensor'> (20L,)
<class 'torch.FloatTensor'> (20L, 1L, 5L, 5L)

```

```py
W
wizardforcel 已提交
133
children()
W
wizardforcel 已提交
134 135
```

C
chen 已提交
136
返回一个当前所有子模块的迭代器
W
wizardforcel 已提交
137 138
Returns an iterator over immediate children modules.

C
chen 已提交
139
| Yields: | _Module_ – 子模块 |
W
wizardforcel 已提交
140 141 142
| --- | --- |

```py
W
wizardforcel 已提交
143
cpu()
W
wizardforcel 已提交
144 145
```

C
chen 已提交
146
将模型的所有参数(parameter)和缓冲区(buffer)都转移到CPU内存中。
W
wizardforcel 已提交
147 148 149 150 151 152 153

| Returns: | self |
| --- | --- |
| Return type: | [Module](#torch.nn.Module "torch.nn.Module") |
| --- | --- |

```py
W
wizardforcel 已提交
154
cuda(device=None)
W
wizardforcel 已提交
155 156
```

C
chen 已提交
157
将模型的所有参数和缓冲区都转移到CUDA设备内存中。
W
wizardforcel 已提交
158

C
chen 已提交
159
因为cuda()函数同时会将处理模块中的所有参数并缓存这些参数的对象。所以如果想让模块在GPU上进行优化操作,一定要在构建优化器之前调用模块的cuda()函数。
W
wizardforcel 已提交
160

C
chen 已提交
161
| Parameters: | **device** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – 如果设备编号被指定,所有的参数都会被拷贝到编号指定设备上 |
W
wizardforcel 已提交
162 163 164 165 166 167 168
| --- | --- |
| Returns: | self |
| --- | --- |
| Return type: | [Module](#torch.nn.Module "torch.nn.Module") |
| --- | --- |

```py
W
wizardforcel 已提交
169
double()
W
wizardforcel 已提交
170 171
```

C
chen 已提交
172
将所有的浮点数类型的参数(parameters)和缓冲区(buffers)转换为`double`数据类型。
W
wizardforcel 已提交
173 174 175 176 177 178 179

| Returns: | self |
| --- | --- |
| Return type: | [Module](#torch.nn.Module "torch.nn.Module") |
| --- | --- |

```py
W
wizardforcel 已提交
180
dump_patches = False
W
wizardforcel 已提交
181 182
```

C
chen 已提交
183
这个字段可以为[`load_state_dict()`](#torch.nn.Module.load_state_dict "torch.nn.Module.load_state_dict")提供 BC 支持(BC support实在不懂是什么意思-.-)。 在 [`state_dict()`](#torch.nn.Module.state_dict "torch.nn.Module.state_dict")函数返回的状态字典(state dict)中, 有一个名为`_metadata`的属性中存储了这个state_dict的版本号。`_metadata`是一个遵从了状态字典(state dict)的命名规范的关键字字典, 要想了解这个`_metadata`在加载状态(loading state dict)的时候是怎么用的,可以看一下 `_load_from_state_dict`部分的文档。
W
wizardforcel 已提交
184

C
chen 已提交
185

C
chen 已提交
186
如果新的参数/缓冲区被添加于/移除自这个模块之中时,这个版本号数字会随之发生变化。同时模块的`_load_from_state_dict`方法会比较版本号的信息并依据此状态词典(state dict)的变化做出一些适当的调整。
W
wizardforcel 已提交
187 188

```py
W
wizardforcel 已提交
189
eval()
W
wizardforcel 已提交
190 191
```

C
chen 已提交
192
将模块转换为测试模式。
W
wizardforcel 已提交
193

C
chen 已提交
194
这个函数只对特定的模块类型有效,如 [`Dropout`](#torch.nn.Dropout "torch.nn.Dropout")`BatchNorm`等等。如果想了解这些特定模块在训练/测试模式下各自的运作细节,可以看一下这些特殊模块的文档部分。
W
wizardforcel 已提交
195 196

```py
W
wizardforcel 已提交
197
extra_repr()
W
wizardforcel 已提交
198 199
```

C
chen 已提交
200 201 202
为模块设置额外的展示信息(extra representation)。

如果想要打印展示(print)你的模块的一些定制的额外信息,那你应该在你的模块中复现这个函数。单行和多行的字符串都可以被接受。
W
wizardforcel 已提交
203 204 205


```py
W
wizardforcel 已提交
206
float()
W
wizardforcel 已提交
207 208
```

C
chen 已提交
209
将所有浮点数类型的参数(parameters)和缓冲区(buffers)转换为`float`数据类型。
W
wizardforcel 已提交
210 211 212 213 214 215 216

| Returns: | self |
| --- | --- |
| Return type: | [Module](#torch.nn.Module "torch.nn.Module") |
| --- | --- |

```py
W
wizardforcel 已提交
217
forward(*input)
W
wizardforcel 已提交
218 219
```

C
chen 已提交
220
定义了每次模块被调用之后所进行的计算过程。
W
wizardforcel 已提交
221

C
chen 已提交
222
应该被Module类的所有子类重写。
W
wizardforcel 已提交
223 224 225

Note

C
chen 已提交
226
尽管模块的前向操作都被定义在这个函数里面,但是当你要进行模块的前向操作的时候,还是要直接调用模块[`Module`](#torch.nn.Module "torch.nn.Module") 的实例函数,而不是直接调用这个forward()函数。这主要是因为前者会照顾到注册在此模块之上的钩子函数(the registered hooks)的运行,而后者则不会。
W
wizardforcel 已提交
227 228

```py
W
wizardforcel 已提交
229
half()
W
wizardforcel 已提交
230 231
```

C
chen 已提交
232
将所有的浮点数类型的参数(parameters)和缓冲区(buffers)转换为`half`数据类型。
W
wizardforcel 已提交
233 234 235 236 237 238 239

| Returns: | self |
| --- | --- |
| Return type: | [Module](#torch.nn.Module "torch.nn.Module") |
| --- | --- |

```py
W
wizardforcel 已提交
240
load_state_dict(state_dict, strict=True)
W
wizardforcel 已提交
241 242
```

C
chen 已提交
243
[`state_dict`](#torch.nn.Module.state_dict "torch.nn.Module.state_dict")中的参数(parameters)和缓冲区(buffers)拷贝到模块和其子模块之中。如果`strict`被设置为`True`,那么[`state_dict`](#torch.nn.Module.state_dict "torch.nn.Module.state_dict")中的键值(keys)必须与模型的[`state_dict()`]函数所返回的键值(keys)信息保持完全的一致。
W
wizardforcel 已提交
244

C
chen 已提交
245
load_state_dict()函数参数: 
W
wizardforcel 已提交
246

C
chen 已提交
247 248
*   **state_dict** ([_dict_](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)")) – 一个包含了参数和持久缓冲区的字典。
*   **strict** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – 是否严格要求 [`state_dict`](#torch.nn.Module.state_dict "torch.nn.Module.state_dict") 中的键值(keys)与模型 [`state_dict()`](#torch.nn.Module.state_dict "torch.nn.Module.state_dict") 函数返回的键值(keys)信息保持完全一致。 默认: `True`
W
wizardforcel 已提交
249

W
wizardforcel 已提交
250

W
wizardforcel 已提交
251 252

```py
W
wizardforcel 已提交
253
modules()
W
wizardforcel 已提交
254 255
```

C
chen 已提交
256
返回一个当前模块内所有模块(包括自身)的迭代器。
W
wizardforcel 已提交
257 258 259 260 261 262

| Yields: | _Module_ – a module in the network |
| --- | --- |

Note

C
chen 已提交
263
注意重复的模块只会被返回一次。比在下面这个例子中,`l`就只会被返回一次。
W
wizardforcel 已提交
264

C
chen 已提交
265
例子:
W
wizardforcel 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

```py
>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.modules()):
 print(idx, '->', m)

0 -> Sequential (
 (0): Linear (2 -> 2)
 (1): Linear (2 -> 2)
)
1 -> Linear (2 -> 2)

```

```py
W
wizardforcel 已提交
282
named_buffers(prefix='', recurse=True)
W
wizardforcel 已提交
283 284
```

C
chen 已提交
285
返回一个模块缓冲区的迭代器,每次返回的元素是由缓冲区的名字和缓冲区自身组成的元组。
W
wizardforcel 已提交
286

C
chen 已提交
287
named_buffers()函数的参数: 
W
wizardforcel 已提交
288

C
chen 已提交
289 290
*   **prefix** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – 要添加在所有缓冲区名字之前的前缀。
*   **recurse** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")) – 如果设置为True,那样迭代器中不光会返回这个模块自身直连成员的缓冲区,同时也会递归返回其子模块的缓冲区。否则,只返回这个模块直连成员的缓冲区。
W
wizardforcel 已提交
291

W
wizardforcel 已提交
292

C
chen 已提交
293
| Yields: | _(string, torch.Tensor)_ – 包含了缓冲区的名字和缓冲区自身的元组 |
W
wizardforcel 已提交
294 295
| --- | --- |

C
chen 已提交
296
例子:
W
wizardforcel 已提交
297 298 299 300 301 302 303 304 305

```py
>>> for name, buf in self.named_buffers():
>>>    if name in ['running_var']:
>>>        print(buf.size())

```

```py
W
wizardforcel 已提交
306
named_children()
W
wizardforcel 已提交
307 308
```

C
chen 已提交
309 310
返回一个当前模型直连的子模块的迭代器,每次返回的元素是由子模块的名字和子模块自身组成的元组。

W
wizardforcel 已提交
311

C
chen 已提交
312
| Yields: | _(string, Module)_ – 包含了子模块的名字和子模块自身的元组 |
W
wizardforcel 已提交
313 314
| --- | --- |

C
chen 已提交
315
例子:
W
wizardforcel 已提交
316 317 318 319 320 321 322 323 324

```py
>>> for name, module in model.named_children():
>>>     if name in ['conv4', 'conv5']:
>>>         print(module)

```

```py
W
wizardforcel 已提交
325
named_modules(memo=None, prefix='')
W
wizardforcel 已提交
326 327
```

C
chen 已提交
328
返回一个当前模块内所有模块(包括自身)的迭代器,每次返回的元素是由模块的名字和模块自身组成的元组。
W
wizardforcel 已提交
329

C
chen 已提交
330 331

| Yields: | _(string, Module)_ – 模块名字和模块自身组成的元组 |
W
wizardforcel 已提交
332 333 334 335
| --- | --- |

Note

C
chen 已提交
336
重复的模块只会被返回一次。在下面的例子中,`l`只被返回了一次。
W
wizardforcel 已提交
337

C
chen 已提交
338
例子:
W
wizardforcel 已提交
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354

```py
>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.named_modules()):
 print(idx, '->', m)

0 -> ('', Sequential (
 (0): Linear (2 -> 2)
 (1): Linear (2 -> 2)
))
1 -> ('0', Linear (2 -> 2))

```

```py
W
wizardforcel 已提交
355
named_parameters(prefix='', recurse=True)
W
wizardforcel 已提交
356 357
```

C
chen 已提交
358
返回一个当前模块内所有参数的迭代器,每次返回的元素是由参数的名字和参数自身组成的元组。
W
wizardforcel 已提交
359

C
chen 已提交
360
named_parameters()函数参数:
W
wizardforcel 已提交
361

C
chen 已提交
362 363
*   **prefix** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")) – 要在所有参数名字前面添加的前缀。
*   **recurse** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")) – 如果设置为True,那样迭代器中不光会返回这个模块自身直连成员的参数,同时也会返回其子模块的参数。否则,只返回这个模块直连成员的参数。
W
wizardforcel 已提交
364

W
wizardforcel 已提交
365

C
chen 已提交
366
| Yields: | _(string, Parameter)_ – 参数名字和参数自身组成的元组 |
W
wizardforcel 已提交
367 368
| --- | --- |

C
chen 已提交
369
例子:
W
wizardforcel 已提交
370 371 372 373 374 375 376 377 378

```py
>>> for name, param in self.named_parameters():
>>>    if name in ['bias']:
>>>        print(param.size())

```

```py
W
wizardforcel 已提交
379
parameters(recurse=True)
W
wizardforcel 已提交
380 381
```

C
chen 已提交
382 383
返回一个遍历模块所有参数的迭代器。
parameters()函数一个经典的应用就是实践中经常将此函数的返回值传入优化器。
W
wizardforcel 已提交
384

C
chen 已提交
385
| Parameters: | **recurse** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")) –  如果设置为True,那样迭代器中不光会返回这个模块自身直连成员的参数,同时也会递归返回其子模块的参数。否则,只返回这个模块直连成员的参数。 |
W
wizardforcel 已提交
386
| --- | --- |
C
chen 已提交
387
| Yields: | _Parameter_ – 模块参数 |
W
wizardforcel 已提交
388 389
| --- | --- |

C
chen 已提交
390
例子:
W
wizardforcel 已提交
391 392 393 394 395 396 397 398 399 400

```py
>>> for param in model.parameters():
>>>     print(type(param.data), param.size())
<class 'torch.FloatTensor'> (20L,)
<class 'torch.FloatTensor'> (20L, 1L, 5L, 5L)

```

```py
W
wizardforcel 已提交
401
register_backward_hook(hook)
W
wizardforcel 已提交
402 403
```

C
chen 已提交
404
在模块上注册一个挂载在反向操作之后的钩子函数。(挂载在backward之后这个点上的钩子函数)
C
chen 已提交
405

C
chen 已提交
406
对于每次输入,当模块关于此次输入的反向梯度的计算过程完成,该钩子函数都会被调用一次。此钩子函数需要遵从以下函数签名:
W
wizardforcel 已提交
407 408 409 410 411 412 413


```py
hook(module, grad_input, grad_output) -> Tensor or None

```

C
chen 已提交
414
如果模块的输入或输出是多重的(multiple inputs or outputs),那 `grad_input``grad_output` 应当是元组数据。 钩子函数不能对输入的参数`grad_input``grad_output`进行任何更改,但是可以选择性地根据输入的参数返回一个新的梯度回去,而这个新的梯度在后续的计算中会替换掉`grad_input`
W
wizardforcel 已提交
415

C
chen 已提交
416
| Returns: | 一个句柄(handle),这个handle的特点就是通过调用`handle.remove()`函数就可以将这个添加于模块之上的钩子移除掉。|
W
wizardforcel 已提交
417 418 419 420 421 422
| --- | --- |
| Return type: | `torch.utils.hooks.RemovableHandle` |
| --- | --- |

Warning

C
chen 已提交
423
对于一些具有很多复杂操作的[`Module`](#torch.nn.Module "torch.nn.Module"),当前的hook实现版本还不能达到完全理想的效果。举个例子,有些错误的情况下,函数的输入参数`grad_input``grad_output`中可能只是真正的输入和输出变量的一个子集。对于此类的[`Module`](#torch.nn.Module "torch.nn.Module"),你应该使用[`torch.Tensor.register_hook()`]直接将钩子挂载到某个特定的输入输出的变量上,而不是当前的模块。
W
wizardforcel 已提交
424 425

```py
W
wizardforcel 已提交
426
register_buffer(name, tensor)
W
wizardforcel 已提交
427 428
```

C
chen 已提交
429
往模块上添加一个持久缓冲区。
W
wizardforcel 已提交
430

C
chen 已提交
431
这个函数的经常会被用于向模块添加不会被认为是模块参数(model parameter)的缓冲区。举个栗子,BatchNorm的`running_mean`就不是一个参数,但却属于持久状态。
W
wizardforcel 已提交
432

C
chen 已提交
433
所添加的缓冲区可以通过给定的名字(name参数)以访问模块的属性的方式进行访问。
W
wizardforcel 已提交
434

C
chen 已提交
435
register_buffer()函数的参数: 
W
wizardforcel 已提交
436

C
chen 已提交
437 438
*   **name** (_string_) – 要添加的缓冲区的名字。所添加的缓冲区可以通过此名字以访问模块的属性的方式进行访问。
*   **tensor** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – 需要注册到模块上的缓冲区。
W
wizardforcel 已提交
439

W
wizardforcel 已提交
440

W
wizardforcel 已提交
441

C
chen 已提交
442
例子:
W
wizardforcel 已提交
443 444 445 446 447 448 449

```py
>>> self.register_buffer('running_mean', torch.zeros(num_features))

```

```py
W
wizardforcel 已提交
450
register_forward_hook(hook)
W
wizardforcel 已提交
451 452
```

C
chen 已提交
453
在模块上注册一个挂载在前向操作之后的钩子函数。(挂载在forward操作结束之后这个点)
W
wizardforcel 已提交
454

C
chen 已提交
455
此钩子函数在每次模块的 [`forward()`](#torch.nn.Module.forward "torch.nn.Module.forward")函数运行结束产生output之后就会被触发。此钩子函数需要遵从以下函数签名:
W
wizardforcel 已提交
456 457 458 459 460 461

```py
hook(module, input, output) -> None

```

C
chen 已提交
462
此钩子函数不能进行会修改 input 和 output 这两个参数的操作。
W
wizardforcel 已提交
463

C
chen 已提交
464
| Returns: | 一个句柄(handle),这个handle的特点就是通过调用`handle.remove()`函数就可以将这个添加于模块之上的钩子移除掉。 |
W
wizardforcel 已提交
465 466 467 468 469
| --- | --- |
| Return type: | `torch.utils.hooks.RemovableHandle` |
| --- | --- |

```py
W
wizardforcel 已提交
470
register_forward_pre_hook(hook)
W
wizardforcel 已提交
471 472
```

C
chen 已提交
473
在模块上注册一个挂载在前向操作之前的钩子函数。(挂载在forward操作开始之前这个点)
W
wizardforcel 已提交
474

C
chen 已提交
475 476

此钩子函数在每次模块的 [`forward()`](#torch.nn.Module.forward "torch.nn.Module.forward")函数运行开始之前会被触发。此钩子函数需要遵从以下函数签名:
W
wizardforcel 已提交
477 478 479 480 481 482 483
The hook will be called every time before [`forward()`](#torch.nn.Module.forward "torch.nn.Module.forward") is invoked. It should have the following signature:

```py
hook(module, input) -> None

```

C
chen 已提交
484
此钩子函数不能进行会修改 input 这个参数的操作。
W
wizardforcel 已提交
485

C
chen 已提交
486
| Returns: | 一个句柄(handle),这个handle的特点就是通过调用`handle.remove()`函数就可以将这个添加于模块之上的钩子移除掉。 |
W
wizardforcel 已提交
487 488 489 490 491
| --- | --- |
| Return type: | `torch.utils.hooks.RemovableHandle` |
| --- | --- |

```py
W
wizardforcel 已提交
492
register_parameter(name, param)
W
wizardforcel 已提交
493 494
```

C
chen 已提交
495
向模块添加一个参数(parameter)。
W
wizardforcel 已提交
496

C
chen 已提交
497
所添加的参数(parameter)可以通过给定的名字(name参数)以访问模块的属性的方式进行访问。
W
wizardforcel 已提交
498

C
chen 已提交
499
register_parameter()函数的参数: 
W
wizardforcel 已提交
500

C
chen 已提交
501 502
*   **name** (_string_) – 所添加的参数的名字. 所添加的参数(parameter)可以通过此名字以访问模块的属性的方式进行访问
*   **parameter** ([_Parameter_](#torch.nn.Parameter "torch.nn.Parameter")) – 要添加到模块之上的参数。
W
wizardforcel 已提交
503

W
wizardforcel 已提交
504

W
wizardforcel 已提交
505 506

```py
W
wizardforcel 已提交
507
state_dict(destination=None, prefix='', keep_vars=False)
W
wizardforcel 已提交
508 509
```

C
chen 已提交
510
返回一个包含了模块当前所有状态(state)的字典(dictionary)。
W
wizardforcel 已提交
511

C
chen 已提交
512
所有的参数和持久缓冲区都被囊括在其中。字典的键值就是响应的参数和缓冲区的名字(name)。
W
wizardforcel 已提交
513

C
chen 已提交
514 515

| Returns: | 一个包含了模块当前所有状态的字典 |
W
wizardforcel 已提交
516 517 518 519
| --- | --- |
| Return type: | [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.7)") |
| --- | --- |

C
chen 已提交
520
例子:
W
wizardforcel 已提交
521 522 523 524 525 526 527 528

```py
>>> module.state_dict().keys()
['bias', 'weight']

```

```py
W
wizardforcel 已提交
529
to(*args, **kwargs)
W
wizardforcel 已提交
530 531
```

C
chen 已提交
532
移动 并且/或者(and/or)转换所有的参数和缓冲区。
W
wizardforcel 已提交
533

C
chen 已提交
534
这个函数可以这样调用:
W
wizardforcel 已提交
535 536 537 538 539 540 541 542 543 544 545 546 547

```py
to(device=None, dtype=None, non_blocking=False)
```

```py
to(dtype, non_blocking=False)
```

```py
to(tensor, non_blocking=False)
```

C
chen 已提交
548
此函数的函数签名跟[`torch.Tensor.to()`](tensors.html#torch.Tensor.to "torch.Tensor.to")函数的函数签名很相似,只不过这个函数`dtype`参数只接受浮点数类型的dtype,如float, double, half( floating point desired `dtype` s)。同时,这个方法只会将浮点数类型的参数和缓冲区(the floating point parameters and buffers)转化为`dtype`(如果输入参数中给定的话)的数据类型。而对于整数类型的参数和缓冲区(the integral parameters and buffers),即便输入参数中给定了`dtype`,也不会进行转换操作,而如果给定了 `device`参数,移动操作则会正常进行。当`non_blocking`参数被设置为True之后,此函数会尽可能地相对于 host 进行异步的 转换/移动 操作,比如,将存储在固定内存(pinned memory)上的CPU Tensors移动到CUDA设备上这一过程既是如此。
W
wizardforcel 已提交
549

C
chen 已提交
550
例子在下面。
W
wizardforcel 已提交
551 552 553

Note

C
chen 已提交
554
这个方法对模块的修改都是in-place操作。
W
wizardforcel 已提交
555

C
chen 已提交
556
to()函数的参数: 
W
wizardforcel 已提交
557

C
chen 已提交
558 559 560
*   **device** (`torch.device`) – 想要将这个模块中的参数和缓冲区转移到的设备。
*   **dtype** (`torch.dtype`) – 想要将这个模块中浮点数的参数和缓冲区转化为的浮点数数据类型。
*   **tensor** ([_torch.Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – 一个Tensor,如果被指定,其dtype和device信息,将分别起到上面两个参数的作用,也就是说,这个模块的浮点数的参数和缓冲区的数据类型将会被转化为这个Tensor的dtype类型,同时被转移到此Tensor所处的设备device上去。
W
wizardforcel 已提交
561

W
wizardforcel 已提交
562

W
wizardforcel 已提交
563 564 565 566 567
| Returns: | self |
| --- | --- |
| Return type: | [Module](#torch.nn.Module "torch.nn.Module") |
| --- | --- |

C
chen 已提交
568
例子:
W
wizardforcel 已提交
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599

```py
>>> linear = nn.Linear(2, 2)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
 [-0.5113, -0.2325]])
>>> linear.to(torch.double)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
 [-0.5113, -0.2325]], dtype=torch.float64)
>>> gpu1 = torch.device("cuda:1")
>>> linear.to(gpu1, dtype=torch.half, non_blocking=True)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
 [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')
>>> cpu = torch.device("cpu")
>>> linear.to(cpu)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
 [-0.5112, -0.2324]], dtype=torch.float16)

```

```py
W
wizardforcel 已提交
600
train(mode=True)
W
wizardforcel 已提交
601 602
```

C
chen 已提交
603
将模块转换成训练模式。
W
wizardforcel 已提交
604

C
chen 已提交
605
这个函数只对特定的模块类型有效,如 [`Dropout`](#torch.nn.Dropout "torch.nn.Dropout")`BatchNorm`等等。如果想了解这些特定模块在训练/测试模式下各自的运作细节,可以看一下这些特殊模块的文档部分。
W
wizardforcel 已提交
606 607 608 609 610 611 612

| Returns: | self |
| --- | --- |
| Return type: | [Module](#torch.nn.Module "torch.nn.Module") |
| --- | --- |

```py
W
wizardforcel 已提交
613
type(dst_type)
W
wizardforcel 已提交
614 615
```

C
chen 已提交
616
将所有的参数和缓冲区转化为 `dst_type`的数据类型。
W
wizardforcel 已提交
617

C
chen 已提交
618
| Parameters: | **dst_type** ([_type_](https://docs.python.org/3/library/functions.html#type "(in Python v3.7)") _or_ _string_) – 要转化的数据类型 |
W
wizardforcel 已提交
619 620 621 622 623 624 625
| --- | --- |
| Returns: | self |
| --- | --- |
| Return type: | [Module](#torch.nn.Module "torch.nn.Module") |
| --- | --- |

```py
W
wizardforcel 已提交
626
zero_grad()
W
wizardforcel 已提交
627 628
```

C
chen 已提交
629
讲模块所有参数的梯度设置为0。
W
wizardforcel 已提交
630 631 632 633

### Sequential

```py
W
wizardforcel 已提交
634
class torch.nn.Sequential(*args)
W
wizardforcel 已提交
635 636
```

C
chen 已提交
637
一种顺序容器。传入Sequential构造器中的模块会被按照他们传入的顺序依次添加到Sequential之上。相应的,一个由模块组成的顺序词典也可以被传入到Sequential的构造器中。
W
wizardforcel 已提交
638

C
chen 已提交
639
为了方便大家理解,举个简单的例子:
W
wizardforcel 已提交
640 641

```py
C
chen 已提交
642
# 构建Sequential的例子
W
wizardforcel 已提交
643 644 645 646 647 648 649
model = nn.Sequential(
          nn.Conv2d(1,20,5),
          nn.ReLU(),
          nn.Conv2d(20,64,5),
          nn.ReLU()
        )

C
chen 已提交
650
# 利用OrderedDict构建Sequential的例子
W
wizardforcel 已提交
651 652 653 654 655 656 657 658 659
model = nn.Sequential(OrderedDict([
          ('conv1', nn.Conv2d(1,20,5)),
          ('relu1', nn.ReLU()),
          ('conv2', nn.Conv2d(20,64,5)),
          ('relu2', nn.ReLU())
        ]))

```

C
chen 已提交
660
### ModuleList (模块列表)
W
wizardforcel 已提交
661 662

```py
W
wizardforcel 已提交
663
class torch.nn.ModuleList(modules=None)
W
wizardforcel 已提交
664 665
```

C
chen 已提交
666
ModuleList的作用是将一堆模块(module)存储在一个列表之中。
W
wizardforcel 已提交
667

C
chen 已提交
668
ModuleList 可以按一般的python列表的索引方式进行索引,但ModuleList中的模块都已被正确注册,并且对所有的Module method可见。
W
wizardforcel 已提交
669

C
chen 已提交
670
| Parameters: | **modules** (_iterable__,_ _optional_) – 一个要添加到ModuleList中的由模块组成的可迭代结构(an iterable of modules)|
W
wizardforcel 已提交
671 672
| --- | --- |

C
chen 已提交
673
例子:
W
wizardforcel 已提交
674 675 676 677 678 679 680 681

```py
class MyModule(nn.Module):
    def __init__(self):
        super(MyModule, self).__init__()
        self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(10)])

    def forward(self, x):
C
chen 已提交
682
        # ModuleList可以被当作一个迭代器,同时也可以使用index索引
W
wizardforcel 已提交
683 684 685 686 687 688 689
        for i, l in enumerate(self.linears):
            x = self.linears[i // 2](x) + l(x)
        return x

```

```py
W
wizardforcel 已提交
690
append(module)
W
wizardforcel 已提交
691 692
```

C
chen 已提交
693
将一个模块添加到ModuleList的末尾,与python list的append()一致。
W
wizardforcel 已提交
694

C
chen 已提交
695
| Parameters: | **module** ([_nn.Module_](#torch.nn.Module "torch.nn.Module")) – 要添加的模块 |
W
wizardforcel 已提交
696 697 698
| --- | --- |

```py
W
wizardforcel 已提交
699
extend(modules)
W
wizardforcel 已提交
700 701
```

C
chen 已提交
702
将一个由模块组成的可迭代结构添加到ModuleList的末尾,与python list的extend()一致。
W
wizardforcel 已提交
703

C
chen 已提交
704
| Parameters: | **modules** (_iterable_) – 要添加到ModuleList末尾的由模块组成的可迭代结构 |
W
wizardforcel 已提交
705 706 707
| --- | --- |

```py
W
wizardforcel 已提交
708
insert(index, module)
W
wizardforcel 已提交
709 710
```

C
chen 已提交
711
将给定的`module`插入到ModuleList的`index`位置。
W
wizardforcel 已提交
712

C
chen 已提交
713
insert()函数的参数: 
W
wizardforcel 已提交
714

C
chen 已提交
715 716
*   **index** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – 要插入的位置
*   **module** ([_nn.Module_](#torch.nn.Module "torch.nn.Module")) – 要插入的模块
W
wizardforcel 已提交
717

W
wizardforcel 已提交
718

C
chen 已提交
719
### ModuleDict (模块词典)
W
wizardforcel 已提交
720 721

```py
W
wizardforcel 已提交
722
class torch.nn.ModuleDict(modules=None)
W
wizardforcel 已提交
723 724
```

C
chen 已提交
725 726
ModuleDict的作用是将一堆模块(module)存储在一个词典之中。

W
wizardforcel 已提交
727

C
chen 已提交
728
ModuleDict 可以按一般的python词典的索引方式进行索引,但ModuleDict中的模块都已被正确注册,并且对所有的Module method可见。
W
wizardforcel 已提交
729

C
chen 已提交
730
| Parameters: | **modules** (_iterable__,_ _optional_) – 一个由(string: module)映射组成的映射集合(词典)或者 一个由(string, module)键/值对组成的可迭代结构 |
W
wizardforcel 已提交
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
| --- | --- |

Example:

```py
class MyModule(nn.Module):
    def __init__(self):
        super(MyModule, self).__init__()
        self.choices = nn.ModuleDict({
                'conv': nn.Conv2d(10, 10, 3),
                'pool': nn.MaxPool2d(3)
        })
        self.activations = nn.ModuleDict([
                ['lrelu', nn.LeakyReLU()],
                ['prelu', nn.PReLU()]
        ])

    def forward(self, x, choice, act):
        x = self.choices[choice](x)
        x = self.activations[act](x)
        return x

```

```py
W
wizardforcel 已提交
756
clear()
W
wizardforcel 已提交
757
```
C
chen 已提交
758
移除ModuleDict中所有的元素。
W
wizardforcel 已提交
759 760

```py
W
wizardforcel 已提交
761
items()
W
wizardforcel 已提交
762 763
```

C
chen 已提交
764
返回一个由ModuleDict中的键/值对组成的可迭代结构。
W
wizardforcel 已提交
765 766

```py
W
wizardforcel 已提交
767
keys()
W
wizardforcel 已提交
768 769
```

C
chen 已提交
770
返回一个由ModuleDict中的键组成的可迭代结构。
W
wizardforcel 已提交
771 772

```py
W
wizardforcel 已提交
773
pop(key)
W
wizardforcel 已提交
774
```
C
chen 已提交
775
`key`这个键从ModuleDict中删除,并将其对应的模块返回。
W
wizardforcel 已提交
776

C
chen 已提交
777
| Parameters: | **key** (_string_) – 要从ModuleDict中弹出的键 |
W
wizardforcel 已提交
778 779 780
| --- | --- |

```py
W
wizardforcel 已提交
781
update(modules)
W
wizardforcel 已提交
782 783
```

C
chen 已提交
784
通过传入的映射或者由键/值对组成的可迭代结构对当前的ModuleDict进行更新,如果传入对象与当前ModuleDict中存在键重复,当前ModuleDict中这些重复的键所对应的值将被覆盖。
W
wizardforcel 已提交
785

C
chen 已提交
786
| Parameters: | **modules** (_iterable_) – 一个由(string: `Module`)映射组成的映射集合(词典)或者 一个由(string: `Module`)键/值对组成的可迭代结构 |
W
wizardforcel 已提交
787 788 789
| --- | --- |

```py
W
wizardforcel 已提交
790
values()
W
wizardforcel 已提交
791 792
```

C
chen 已提交
793
返回一个由ModuleDict中的值组成的可迭代结构。
W
wizardforcel 已提交
794

C
chen 已提交
795
### ParameterList (参数列表)
W
wizardforcel 已提交
796 797

```py
W
wizardforcel 已提交
798
class torch.nn.ParameterList(parameters=None)
W
wizardforcel 已提交
799
```
C
chen 已提交
800
ParameterList的作用是将一堆参数(parameter)存储到一个列表中。
W
wizardforcel 已提交
801

C
chen 已提交
802
ParameterList 可以按一般的python列表的索引方式进行索引,但ParameterList中的参数(parameter)都已被正确注册,并且对所有的Module method可见。
W
wizardforcel 已提交
803 804


C
chen 已提交
805
| Parameters: | **parameters** (_iterable__,_ _optional_) – 要添加到ParameterList之上的由parameter组成的可迭代结构 |
W
wizardforcel 已提交
806 807
| --- | --- |

C
chen 已提交
808
例子:
W
wizardforcel 已提交
809 810 811 812 813 814 815 816

```py
class MyModule(nn.Module):
    def __init__(self):
        super(MyModule, self).__init__()
        self.params = nn.ParameterList([nn.Parameter(torch.randn(10, 10)) for i in range(10)])

    def forward(self, x):
C
chen 已提交
817
        # ParameterList可以被当作一个迭代器,同时也可以使用index索引
W
wizardforcel 已提交
818 819 820 821 822 823 824
        for i, p in enumerate(self.params):
            x = self.params[i // 2].mm(x) + p.mm(x)
        return x

```

```py
W
wizardforcel 已提交
825
append(parameter)
W
wizardforcel 已提交
826 827
```

C
chen 已提交
828
将一个parameter添加到ParameterList的末尾。
W
wizardforcel 已提交
829

C
chen 已提交
830
| Parameters: | **parameter** ([_nn.Parameter_](#torch.nn.Parameter "torch.nn.Parameter")) – 要添加的参数 |
W
wizardforcel 已提交
831 832 833
| --- | --- |

```py
W
wizardforcel 已提交
834
extend(parameters)
W
wizardforcel 已提交
835 836
```

C
chen 已提交
837
将一个由parameter组成的Python可迭代结构添加到ParameterList的末尾。
W
wizardforcel 已提交
838

C
chen 已提交
839
| Parameters: | **parameters** (_iterable_) – 要添加到ParameterList的末尾的由parameter组成的Python可迭代结构 |
W
wizardforcel 已提交
840 841
| --- | --- |

C
chen 已提交
842
### ParameterDict (参数词典)
W
wizardforcel 已提交
843 844

```py
W
wizardforcel 已提交
845
class torch.nn.ParameterDict(parameters=None)
W
wizardforcel 已提交
846 847
```

C
chen 已提交
848
ParameterDict的作用是将一堆参数(Parameter)存储在一个词典之中。
W
wizardforcel 已提交
849

C
chen 已提交
850
ParameterDict 可以按一般的python词典的索引方式进行索引,但ParameterDictt中的参数都已被正确注册,并且对所有的Module method可见。
W
wizardforcel 已提交
851

C
chen 已提交
852
| Parameters: | **parameters** (_iterable__,_ _optional_) – 一个由(string:[`Parameter`](#torch.nn.Parameter "torch.nn.Parameter"))映射组成的映射集合(词典)或者 一个由(string, [`Parameter`](#torch.nn.Parameter "torch.nn.Parameter"))键/值对组成的可迭代结构 |
W
wizardforcel 已提交
853 854
| --- | --- |

C
chen 已提交
855
例子:
W
wizardforcel 已提交
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872

```py
class MyModule(nn.Module):
    def __init__(self):
        super(MyModule, self).__init__()
        self.params = nn.ParameterDict({
                'left': nn.Parameter(torch.randn(5, 10)),
                'right': nn.Parameter(torch.randn(5, 10))
        })

    def forward(self, x, choice):
        x = self.params[choice].mm(x)
        return x

```

```py
W
wizardforcel 已提交
873
clear()
W
wizardforcel 已提交
874
```
C
chen 已提交
875
移除ParameterDict中所有的元素。
W
wizardforcel 已提交
876 877

```py
W
wizardforcel 已提交
878
items()
W
wizardforcel 已提交
879 880
```

C
chen 已提交
881
返回一个由ParameterDict中的键/值对组成的可迭代结构。
W
wizardforcel 已提交
882 883

```py
W
wizardforcel 已提交
884
keys()
W
wizardforcel 已提交
885 886
```

C
chen 已提交
887
返回一个由 ParameterDict中的键组成的可迭代结构。
W
wizardforcel 已提交
888 889

```py
W
wizardforcel 已提交
890
pop(key)
W
wizardforcel 已提交
891 892
```

C
chen 已提交
893
将key这个键从ParameterDict中删除,并将其对应的模块返回。
W
wizardforcel 已提交
894

C
chen 已提交
895
| Parameters: | **key** (_string_) – 要从ParameterDict中弹出的键 |
W
wizardforcel 已提交
896 897 898
| --- | --- |

```py
W
wizardforcel 已提交
899
update(parameters)
W
wizardforcel 已提交
900 901
```

C
chen 已提交
902
通过传入的映射或者由键/值对组成的可迭代结构对当前的ParameterDict进行更新,如果传入对象与当前ParameterDict中存在键重复,当前ParameterDict中这些重复的键所对应的值将被覆盖。
W
wizardforcel 已提交
903

C
chen 已提交
904
| Parameters: | **parameters** (_iterable_) – modules (iterable) – 一个由(string: [`Parameter`](#torch.nn.Parameter "torch.nn.Parameter"))映射组成的映射集合(词典)或者 一个由(string: [`Parameter`](#torch.nn.Parameter "torch.nn.Parameter"))键/值对组成的可迭代结构 |
W
wizardforcel 已提交
905 906 907
| --- | --- |

```py
W
wizardforcel 已提交
908
values()
W
wizardforcel 已提交
909 910
```

C
chen 已提交
911
返回一个由ParameterDict中的值组成的可迭代结构。
W
wizardforcel 已提交
912

C
chen 已提交
913
## Convolution layers (卷积层)
W
wizardforcel 已提交
914 915 916 917

### Conv1d

```py
W
wizardforcel 已提交
918
class torch.nn.Conv1d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)
W
wizardforcel 已提交
919 920
```

C
chen 已提交
921
利用指定大小的一维卷积核对输入的多通道一维输入信号进行一维卷积操作的卷积层。
W
wizardforcel 已提交
922

C
chen 已提交
923
在最简单的情况下,对于输入大小为![](img/1dad4f3ff614c986028f7100e0205f6d.jpg),输出大小为![](img/a03de8b18f61a493174a56530fb03f1d.jpg)的一维卷积层,其卷积计算过程可以如下表述:
W
wizardforcel 已提交
924 925 926

![](img/806f7530da55bf294a636b8c7ed38bcb.jpg)

C
chen 已提交
927
这里的![](img/d5d3d32b4a35f91edb54c3c3f87d582e.jpg)符号实际上是一个互相关([cross-correlation](https://en.wikipedia.org/wiki/Cross-correlation)) 操作符(大家可以自己查一下互相关和真卷积的区别,互相关因为实现起来很简单,所以一般的深度学习框架都是用互相关操作取代真卷积), ![](img/9341d9048ac485106d2b2ee8de14876f.jpg) is a batch size, ![](img/6c8feca3b2da3d6cf371417edff4be4f.jpg) 代表通道的数量, ![](img/db4a9fef02111450bf98261889de550c.jpg) 代表信号序列的长度。
W
wizardforcel 已提交
928

C
chen 已提交
929
*   `stride` 参数控制了互相关操作(伪卷积)的步长,参数的数据类型一般是单个数字或者一个只有一个元素的元组。
W
wizardforcel 已提交
930

C
chen 已提交
931
*   `padding` 参数控制了要在一维卷积核的输入信号的各维度各边上要补齐0的层数。
W
wizardforcel 已提交
932

C
chen 已提交
933
*   `dilation` 参数控制了卷积核中各元素之间的距离;这也被称为多孔算法(à trous algorithm)。这个概念有点难解释,这个链接[link](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md)用可视化的方法很好地解释了`dilation`的作用。
W
wizardforcel 已提交
934

C
chen 已提交
935
*   `groups` 控制了输入输出之间的连接(connections)的数量。`in_channels``out_channels` 必须能被 `groups` 整除。举个栗子, 
W
wizardforcel 已提交
936

C
chen 已提交
937 938
    &gt; *   当 groups=1, 此Conv1d层会使用一个卷积层进行所有输入到输出的卷积操作。
    
C
chen 已提交
939
    &gt; *   当 groups=2, 此时Conv1d层会产生两个并列的卷积层。同时,输入通道被分为两半,两个卷积层分别处理一半的输入通道,同时各自产生一半的输出通道。最后这两个卷积层的输出会被concatenated一起,作为此Conv1d层的输出。
C
chen 已提交
940
    
C
chen 已提交
941
    &gt; *   当 groups= `in_channels`, 每个输入通道都会被单独的一组卷积层处理,这个组的大小是![](img/19131f9f53448ae579b613bc7bc90158.jpg)
W
wizardforcel 已提交
942 943 944

Note

C
chen 已提交
945
取决于你卷积核的大小,有些时候输入数据中某些列(最后几列)可能不会参与计算(比如列数整除卷积核大小有余数,而又没有padding,那最后的余数列一般不会参与卷积计算),这主要是因为pytorch中的互相关操作[cross-correlation](https://en.wikipedia.org/wiki/Cross-correlation)是保证计算正确的操作(valid operation), 而不是满操作(full operation)。所以实际操作中,还是要亲尽量选择好合适的padding参数哦。
W
wizardforcel 已提交
946 947 948

Note

C
chen 已提交
949 950
`groups == in_channels` 并且 `out_channels == K * in_channels`(其中K是正整数)的时候,这个操作也被称为深度卷积。
举个创建深度卷积层的例子,对于一个大小为 ![](img/7db3e5e5d600c81e77756d5eee050505.jpg) 的输入,要构建一个深度乘数为`K`的深度卷积层,可以通过以下参数来创建:![](img/eab8f2745761d762e48a59446243af90.jpg)
W
wizardforcel 已提交
951 952

Note
C
chen 已提交
953

C
chen 已提交
954
当程序的运行环境是使用了CuDNN的CUDA环境的时候,一些非确定性的算法(nondeterministic algorithm)可能会被采用以提高整个计算的性能。如果不想使用这些非确定性的算法,你可以通过设置`torch.backends.cudnn.deterministic = True`来让整个计算过程保持确定性(可能会损失一定的计算性能)。对于后端(background),你可以看一下这一部分[Reproducibility](notes/randomness.html)了解其相关信息。
W
wizardforcel 已提交
955

C
chen 已提交
956
Conv1d的参数: 
W
wizardforcel 已提交
957

C
chen 已提交
958 959 960 961
*   **in_channels** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – 输入通道个数
*   **out_channels** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – 输出通道个数
*   **kernel_size** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – 卷积核大小
*   **stride** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 卷积操作的步长。 默认: 1
C
chen 已提交
962
*   **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 输入数据各维度各边上要补齐0的层数。 默认: 0
C
chen 已提交
963 964 965
*   **dilation** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 卷积核各元素之间的距离。 默认: 1
*   **groups** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – 输入通道与输出通道之间相互隔离的连接的个数。 默认:1
*   **bias** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – 如果被置为 `True`,向输出增加一个偏差量,此偏差是可学习参数。 默认:`True`
W
wizardforcel 已提交
966

W
wizardforcel 已提交
967

W
wizardforcel 已提交
968 969 970 971 972

```py
Shape:
```

C
chen 已提交
973
*   输入: ![](img/7db3e5e5d600c81e77756d5eee050505.jpg)
W
wizardforcel 已提交
974

C
chen 已提交
975
*   输出: ![](img/3423094375906aa21d1b2e095e95c230.jpg) 其中
W
wizardforcel 已提交
976 977 978

    ![](img/91d48a39a90c6b4ed37ac863c1a8ff7b.jpg)

C
chen 已提交
979
| 内部Variables: | 
W
wizardforcel 已提交
980

C
chen 已提交
981 982
*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – Conv1d模块中的一个大小为(out_channels, in_channels, kernel_size)的权重张量,这些权重可训练学习(learnable)。这些权重的初始值的采样空间是![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg), 其中![](img/69aab1ce658aabc9a2d986ae8281e2ad.jpg)
*   **bias** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – 模块的偏差项,大小为(out_channels),可训练学习。如果构造Conv1d时构造函数中的`bias` 被置为 `True`,那么这些权重的初始值的采样空间是![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg), 其中 ![](img/69aab1ce658aabc9a2d986ae8281e2ad.jpg)
W
wizardforcel 已提交
983

C
chen 已提交
984
例子:
W
wizardforcel 已提交
985 986 987 988 989 990 991 992 993 994 995

```py
>>> m = nn.Conv1d(16, 33, 3, stride=2)
>>> input = torch.randn(20, 16, 50)
>>> output = m(input)

```

### Conv2d

```py
W
wizardforcel 已提交
996
class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)
W
wizardforcel 已提交
997
```
C
chen 已提交
998
利用指定大小的二维卷积核对输入的多通道二维输入信号进行二维卷积操作的卷积层。
W
wizardforcel 已提交
999

C
chen 已提交
1000
在最简单的情况下,对于输入大小为![](img/a6c3a4e9779c159b39576bee3400a00b.jpg),输出大小为![](img/4b354af142fb0f01680d390ef552829f.jpg)的二维维卷积层,其卷积计算过程可以如下表述:
W
wizardforcel 已提交
1001 1002 1003

![](img/a4928651cb959fa7871eaebdb489b083.jpg)

C
chen 已提交
1004 1005
这里的![](img/d5d3d32b4a35f91edb54c3c3f87d582e.jpg)符号实际上是一个二维互相关([cross-correlation](https://en.wikipedia.org/wiki/Cross-correlation)) 操作符(大家可以自己查一下互相关和真卷积的区别,互相关因为实现起来很简单,所以一般的深度学习框架都是用互相关操作取代真卷积), ![](img/9341d9048ac485106d2b2ee8de14876f.jpg) is a batch size, ![](img/6c8feca3b2da3d6cf371417edff4be4f.jpg) 代表通道的数量, ![](img/9b7d9beafd65e2cf6493bdca741827a5.jpg) 是输入的二维数据的像素高度,![](img/90490a34512e9bd1843ed4da713d0813.jpg) 是输入的二维数据的像素宽度。

W
wizardforcel 已提交
1006

C
chen 已提交
1007
*   `stride` 参数控制了互相关操作(伪卷积)的步长,参数的数据类型一般是单个数字或者一个只有一个元素的元组。
W
wizardforcel 已提交
1008

C
chen 已提交
1009
*   `padding` 参数控制了要在二维卷积核的输入信号的各维度各边上要补齐0的层数。
W
wizardforcel 已提交
1010

C
chen 已提交
1011
*   `dilation` 参数控制了卷积核中各元素之间的距离;这也被称为多孔算法(à trous algorithm)。这个概念有点难解释,这个链接[link](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md)用可视化的方法很好地解释了`dilation`的作用。
W
wizardforcel 已提交
1012

C
chen 已提交
1013
*   `groups` 控制了输入输出之间的连接(connections)的数量。`in_channels``out_channels` 必须能被 `groups` 整除。举个栗子, 
W
wizardforcel 已提交
1014

C
chen 已提交
1015 1016
    &gt; *   当 groups=1, 此Conv1d层会使用一个卷积层进行所有输入到输出的卷积操作。
    
C
chen 已提交
1017
    &gt; *   当 groups=2, 此时Conv1d层会产生两个并列的卷积层。同时,输入通道被分为两半,两个卷积层分别处理一半的输入通道,同时各自产生一半的输出通道。最后这两个卷积层的输出会被concatenated一起,作为此Conv1d层的输出。
C
chen 已提交
1018
    
C
chen 已提交
1019
    &gt; *   当 groups= `in_channels`, 每个输入通道都会被单独的一组卷积层处理,这个组的大小是![](img/19131f9f53448ae579b613bc7bc90158.jpg)
W
wizardforcel 已提交
1020

C
chen 已提交
1021

C
chen 已提交
1022
`kernel_size`, `stride`, `padding`, `dilation`这几个参数均支持一下输入形式:
W
wizardforcel 已提交
1023

C
chen 已提交
1024 1025
> *   一个 `int` 数字 – 二维数据的高和宽这两个维度都会采用这一个数字。
> *   一个由两个int数字组成的`tuple`– 这种情况下,二维数据的高这一维度会采用元组中的第一个`int`数字,宽这一维度会采用第二个`int`数字。
W
wizardforcel 已提交
1026 1027 1028

Note

C
chen 已提交
1029
取决于你卷积核的大小,有些时候输入数据中某些列(最后几列)可能不会参与计算(比如列数整除卷积核大小有余数,而又没有padding,那最后的余数列一般不会参与卷积计算),这主要是因为pytorch中的互相关操作[cross-correlation](https://en.wikipedia.org/wiki/Cross-correlation)是保证计算正确的操作(valid operation), 而不是满操作(full operation)。所以实际操作中,还是要亲尽量选择好合适的padding参数哦。
W
wizardforcel 已提交
1030 1031

Note
C
chen 已提交
1032
`groups == in_channels` 并且 `out_channels == K * in_channels`(其中K是正整数)的时候,这个操作也被称为深度卷积。
W
wizardforcel 已提交
1033

C
chen 已提交
1034
换句话说,对于一个大小为![](img/0385ad868fed790d36381b9e8788c18b.jpg)的输入,要构建一个深度乘数为`K`的深度卷积层,可以通过以下参数来创建:![](img/8aee041e54a302b342d50912ce67f44b.jpg)
W
wizardforcel 已提交
1035 1036 1037

Note

C
chen 已提交
1038
当程序的运行环境是使用了CuDNN的CUDA环境的时候,一些非确定性的算法(nondeterministic algorithm)可能会被采用以提高整个计算的性能。如果不想使用这些非确定性的算法,你可以通过设置`torch.backends.cudnn.deterministic = True`来让整个计算过程保持确定性(可能会损失一定的计算性能)。对于后端(background),你可以看一下这一部分[Reproducibility](notes/randomness.html)了解其相关信息。
W
wizardforcel 已提交
1039

C
chen 已提交
1040
Conv2d的参数: 
W
wizardforcel 已提交
1041

C
chen 已提交
1042 1043 1044 1045
*   **in_channels** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – 输入通道个数
*   **out_channels** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – 输出通道个数
*   **kernel_size** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – 卷积核大小
*   **stride** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) –卷积操作的步长。 默认: 1
C
chen 已提交
1046
*   **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 输入数据各维度各边上要补齐0的层数。 默认: 0
C
chen 已提交
1047 1048 1049
*   **dilation** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) –卷积核各元素之间的距离。 默认: 1
*   **groups** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – 输入通道与输出通道之间相互隔离的连接的个数。 默认:1
*   **bias** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – 如果被置为 `True`,向输出增加一个偏差量,此偏差是可学习参数。 默认:`True`
W
wizardforcel 已提交
1050 1051 1052 1053 1054

```py
Shape:
```

C
chen 已提交
1055
*   输入: ![](img/0385ad868fed790d36381b9e8788c18b.jpg)
W
wizardforcel 已提交
1056

C
chen 已提交
1057
*   输出: ![](img/d3edfe8a9bbdd73ba5c4b566353777f0.jpg) 其中
W
wizardforcel 已提交
1058 1059 1060 1061 1062

    ![](img/a89a5326ab89279b92f4720f63b4eaae.jpg)

    ![](img/03f69d6e3dffc3254359e41f8b310667.jpg)

C
chen 已提交
1063
| 内部Variables: | 
W
wizardforcel 已提交
1064

C
chen 已提交
1065 1066
*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – Conv2d模块中的一个大小为 (out_channels, in_channels, kernel_size[0], kernel_size[1])的权重张量,这些权重可训练学习(learnable)。这些权重的初始值的采样空间是 ![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg), 其中![](img/c12e2153347b696ebb784e5675cc566e.jpg)
*   **bias** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – 块的偏差项,大小为(out_channels),可训练学习。如果构造Conv2d时构造函数中的`bias` 被置为 `True`,那么这些权重的初始值的采样空间是![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg),其中![](img/c12e2153347b696ebb784e5675cc566e.jpg)
W
wizardforcel 已提交
1067

W
wizardforcel 已提交
1068

W
wizardforcel 已提交
1069

C
chen 已提交
1070
例子:
W
wizardforcel 已提交
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086

```py
>>> # With square kernels and equal stride
>>> m = nn.Conv2d(16, 33, 3, stride=2)
>>> # non-square kernels and unequal stride and with padding
>>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
>>> # non-square kernels and unequal stride and with padding and dilation
>>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1))
>>> input = torch.randn(20, 16, 50, 100)
>>> output = m(input)

```

### Conv3d

```py
W
wizardforcel 已提交
1087
class torch.nn.Conv3d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)
W
wizardforcel 已提交
1088 1089
```

C
chen 已提交
1090
利用指定大小的三维卷积核对输入的多通道三维输入信号进行三维卷积操作的卷积层。
W
wizardforcel 已提交
1091

C
chen 已提交
1092
最简单的情况下,对于输入大小为![](img/ca863d6b44a0246998de77c7c423ec32.jpg),输出大小为![](img/f05e8faaf90b4c16b23ca0165e8e09f4.jpg) 的三维卷积层,其卷积计算过程可以如下表述:
W
wizardforcel 已提交
1093 1094 1095

![](img/39831867c152a21de6e580bf01c0cb7f.jpg)

C
chen 已提交
1096
这里的 ![](img/d5d3d32b4a35f91edb54c3c3f87d582e.jpg)符号实际上是一个三维互相关 [cross-correlation](https://en.wikipedia.org/wiki/Cross-correlation) 操作符。
W
wizardforcel 已提交
1097

C
chen 已提交
1098
*   `stride` 数控制了互相关操作(伪卷积)的步长。
W
wizardforcel 已提交
1099

C
chen 已提交
1100
*   `padding` 参数控制了要在三维卷积核的输入信号的各维度各边上要补齐0的层数。
W
wizardforcel 已提交
1101

C
chen 已提交
1102
*   `dilation` 参数控制了卷积核中各元素之间的距离;这也被称为多孔算法(à trous algorithm)。这个概念有点难解释,这个链接[link](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md)用可视化的方法很好地解释了`dilation`的作用。
W
wizardforcel 已提交
1103

C
chen 已提交
1104
*   `groups` 控制了输入输出之间的连接(connections)的数量。`in_channels``out_channels` 必须能被 `groups` 整除。举个栗子,
W
wizardforcel 已提交
1105

C
chen 已提交
1106 1107 1108 1109 1110 1111 1112
   &gt; *   当 groups=1, 此Conv3d层会使用一个卷积层进行对所有输入到输出的卷积操作。
   
   &gt; *   当 groups=2, 此时Conv3d层会产生两个并列的卷积层。同时,输入通道被分为两半,两个卷积层分别处理一半的输入通道,同时各自产生一半的输出通道。最后这两个卷积层的输出会被concatenated一起,作为此Conv3d层的输出。
   
   &gt; *   当 groups= in_channels, 每个输入通道都会被单独的一组卷积层处理,这个组的大小是 ![](img/648a514da1dace3deacf3f078287e157.jpg).

`kernel_size`, `stride`, `padding`, `dilation`这几个参数均支持一下输入形式:
W
wizardforcel 已提交
1113

C
chen 已提交
1114 1115
> *   一个 `int` 数字 – 三维维数据的深度,高和宽这三个维度都会采用这一个数字。
> *   一个由三个int数字组成的`tuple`– 这种情况下,三维数据的深度这一维度会采用元组中的第一个`int`数字,高这一维度会采用元组中的第二个`int`数字,宽这一维度会采用第三个`int`数字。
W
wizardforcel 已提交
1116 1117 1118 1119


Note

C
chen 已提交
1120
取决于你卷积核的大小,有些时候输入数据中某些列(最后几列)可能不会参与计算(比如列数整除卷积核大小有余数,而又没有padding,那最后的余数列一般不会参与卷积计算),这主要是因为pytorch中的互相关操作[cross-correlation](https://en.wikipedia.org/wiki/Cross-correlation)是保证计算正确的操作(valid operation), 而不是满操作(full operation)。所以实际操作中,还是要亲尽量选择好合适的padding参数哦。
W
wizardforcel 已提交
1121 1122 1123

Note

C
chen 已提交
1124
`groups == in_channels` 并且 `out_channels == K * in_channels`(其中K是正整数)的时候,这个操作也被称为深度卷积。
W
wizardforcel 已提交
1125

C
chen 已提交
1126
换句话说,对于一个大小为  ![](img/a8d71105bc4954eb54660bc5d37c23de.jpg) 的输入,要构建一个深度乘数为`K`的深度卷积层,可以通过以下参数来创建:![](img/8aee041e54a302b342d50912ce67f44b.jpg)
W
wizardforcel 已提交
1127 1128 1129

Note

C
chen 已提交
1130
当程序的运行环境是使用了CuDNN的CUDA环境的时候,一些非确定性的算法(nondeterministic algorithm)可能会被采用以提高整个计算的性能。如果不想使用这些非确定性的算法,你可以通过设置`torch.backends.cudnn.deterministic = True`来让整个计算过程保持确定性(可能会损失一定的计算性能)。对于后端(background),你可以看一下这一部分[Reproducibility](notes/randomness.html)了解其相关信息。
W
wizardforcel 已提交
1131

W
wizardforcel 已提交
1132
Parameters: 
W
wizardforcel 已提交
1133

C
chen 已提交
1134 1135 1136 1137
*   **in_channels** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – 输入通道的个数
*   **out_channels** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – 卷积操作输出通道的个数
*   **kernel_size** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – 卷积核大小
*   **stride** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 卷积操作的步长。 默认: 1
C
chen 已提交
1138
*   **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 输入数据各维度各边上要补齐0的层数。 默认: 0
C
chen 已提交
1139 1140 1141
*   **dilation** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 卷积核各元素之间的距离。 默认: 1
*   **groups** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – 输入通道与输出通道之间相互隔离的连接的个数。 默认:1
*   **bias** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – 如果被置为 `True`,向输出增加一个偏差量,此偏差是可学习参数。 默认:`True`
W
wizardforcel 已提交
1142

W
wizardforcel 已提交
1143 1144 1145 1146 1147

```py
Shape:
```

C
chen 已提交
1148
*   输入: ![](img/a8d71105bc4954eb54660bc5d37c23de.jpg)
W
wizardforcel 已提交
1149

C
chen 已提交
1150
*   输出: ![](img/f05e8faaf90b4c16b23ca0165e8e09f4.jpg) where
W
wizardforcel 已提交
1151 1152 1153 1154 1155 1156 1157

    ![](img/bbc2662490bb72269672fe81af1fe003.jpg)

    ![](img/b7ca056f55603d0632bb03bdf9435d47.jpg)

    ![](img/d040a26cd9a91c4d230afd4c15d0e1e6.jpg)

C
chen 已提交
1158
| 内部Variables: | 
W
wizardforcel 已提交
1159

C
chen 已提交
1160 1161
*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – Conv3d模块中的一个大小为 (out_channels, in_channels, kernel_size[0], kernel_size[1], kernel_size[2]) 的权重张量,这些权重可训练学习(learnable)。这些权重的初始值的采样空间是![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg),其中![](img/378f5c5b47c36239b817ad23a612a9f7.jpg)
*   **bias** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – 模块的偏差项,大小为(out_channels),可训练学习。如果构造Conv1d时构造函数中的`bias` 被置为 `True`,那么这些权重的初始值的采样空间是 ![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg) ,其中 ![](img/378f5c5b47c36239b817ad23a612a9f7.jpg)
W
wizardforcel 已提交
1162

W
wizardforcel 已提交
1163

W
wizardforcel 已提交
1164

C
chen 已提交
1165
例子:
W
wizardforcel 已提交
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179

```py
>>> # With square kernels and equal stride
>>> m = nn.Conv3d(16, 33, 3, stride=2)
>>> # non-square kernels and unequal stride and with padding
>>> m = nn.Conv3d(16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(4, 2, 0))
>>> input = torch.randn(20, 16, 10, 50, 100)
>>> output = m(input)

```

### ConvTranspose1d

```py
W
wizardforcel 已提交
1180
class torch.nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True, dilation=1)
W
wizardforcel 已提交
1181 1182
```

C
chen 已提交
1183
利用指定大小的一维转置卷积核对输入的多通道一维输入信号进行转置卷积(当然此卷积也是互相关操作,cross-correlation)操作的模块。
C
chen 已提交
1184

C
chen 已提交
1185
该模块可以看作是Conv1d相对于其输入的梯度(the gradient of Conv1d with respect to its input, 直译), 转置卷积又被称为小数步长卷积或是反卷积(尽管这不是一个真正意义上的反卷积)。
W
wizardforcel 已提交
1186

C
chen 已提交
1187
*   `stride` 控制了转置卷积操作的步长
C
chen 已提交
1188

C
chen 已提交
1189
*   `padding` 控制了要在输入的各维度的各边上补齐0的层数,与Conv1d不同的地方,此padding参数与实际补齐0的层数的关系为`层数 = kernel_size - 1 - padding`,详情请见下面的note。
C
chen 已提交
1190

C
chen 已提交
1191
  *   `output_padding` 控制了转置卷积操作输出的各维度的长度增量,但注意这个参数不是说要往转置卷积的输出上pad 0,而是直接控制转置卷积的输出大小为根据此参数pad后的大小。更多的详情请见下面的note。
W
wizardforcel 已提交
1192

C
chen 已提交
1193
*   `dilation` 控制了卷积核中各点之间的空间距离;这也被称为多孔算法(à trous algorithm)。这个概念有点难解释,这个链接[link](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md)用可视化的方法很好地解释了dilation的作用。
W
wizardforcel 已提交
1194

C
chen 已提交
1195
*   `groups` 控制了输入输出之间的连接(connections)的数量。`in_channels``out_channels` 必须能被 `groups` 整除。举个栗子,
W
wizardforcel 已提交
1196

C
chen 已提交
1197 1198 1199 1200 1201
    &gt; *   当 groups=1, 此Conv1d层会使用一个卷积层进行所有输入到输出的卷积操作。
    
    &gt; *   当 groups=2, 此时Conv1d层会产生两个并列的卷积层。同时,输入通道被分为两半,两个卷积层分别处理一半的输入通道,同时各自产生一半的输出通道。最后这两个卷积层的输出会被concatenated一起,作为此Conv1d层的输出。
    
    &gt; *   当 groups= `in_channels`, 每个输入通道都会被单独的一组卷积层处理,这个组的大小是![](img/648a514da1dace3deacf3f078287e157.jpg)。
W
wizardforcel 已提交
1202 1203 1204

Note

C
chen 已提交
1205
取决于你卷积核的大小,有些时候输入数据中某些列(最后几列)可能不会参与计算(比如列数整除卷积核大小有余数,而又没有padding,那最后的余数列一般不会参与卷积计算),这主要是因为pytorch中的互相关操作[cross-correlation](https://en.wikipedia.org/wiki/Cross-correlation)是保证计算正确的操作(valid operation), 而不是满操作(full operation)。所以实际操作中,还是要亲尽量选择好合适的padding参数哦。
W
wizardforcel 已提交
1206 1207 1208

Note

C
chen 已提交
1209
`padding` 参数控制了要在输入的各维度各边上补齐0的层数,与在Conv1d中不同的是,在转置卷积操作过程中,此padding参数与实际补齐0的层数的关系为`层数 = kernel_size - 1 - padding`, 这样设置的主要原因是当使用相同的参数构建[`Conv1d`](#torch.nn.Conv1d "torch.nn.Conv1d")[`ConvTranspose1d`](#torch.nn.ConvTranspose1d "torch.nn.ConvTranspose1d")模块的时候,这种设置能够实现两个模块有正好相反的输入输出的大小,即Conv1d的输出大小是其对应的ConvTranspose1d模块的输入大小,而ConvTranspose1d的输出大小又恰好是其对应的Conv1d模块的输入大小。然而,当`stride > 1`的时候,[`Conv1d`](#torch.nn.Conv1d "torch.nn.Conv1d") 的一个输出大小可能会对应多个输入大小,上一个note中就详细的介绍了这种情况,这样的情况下要保持前面提到两种模块的输入输出保持反向一致,那就要用到 `output_padding`参数了,这个参数可以增加转置卷积输出的某一维度的大小,以此来达到前面提到的同参数构建的[`Conv1d`](#torch.nn.Conv1d "torch.nn.Conv1d")[`ConvTranspose1d`](#torch.nn.ConvTranspose1d "torch.nn.ConvTranspose1d")模块的输入输出方向一致。 但注意这个参数不是说要往转置卷积的输出上pad 0,而是直接控制转置卷积的输出各维度的大小为根据此参数pad后的大小。
W
wizardforcel 已提交
1210 1211 1212

Note

C
chen 已提交
1213
当程序的运行环境是使用了CuDNN的CUDA环境的时候,一些非确定性的算法(nondeterministic algorithm)可能会被采用以提高整个计算的性能。如果不想使用这些非确定性的算法,你可以通过设置`torch.backends.cudnn.deterministic = True`来让整个计算过程保持确定性(可能会损失一定的计算性能)。对于后端(background),你可以看一下这一部分[Reproducibility](notes/randomness.html)了解其相关信息。
W
wizardforcel 已提交
1214

W
wizardforcel 已提交
1215
Parameters: 
W
wizardforcel 已提交
1216 1217


C
chen 已提交
1218 1219 1220 1221 1222 1223 1224 1225 1226
*   **in_channels** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – 输入通道的个数
*   **out_channels** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – 卷积操作输出通道的个数
*   **kernel_size** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – 卷积核大小
*   **stride** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 卷积操作的步长。 默认: 1
*   **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – `kernel_size - 1 - padding` 层 0 会被补齐到输入数据的各边上。 默认: 0
*   **output_padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 输出的各维度要增加的大小。默认:0 
*   **groups** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – 输入通道与输出通道之间相互隔离的连接的个数。 默认:1
*   **bias** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – 如果被置为 `True`,向输出增加一个偏差量,此偏差是可学习参数。 默认:`True`
*   **dilation** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 卷积核各元素之间的距离。 默认: 1
W
wizardforcel 已提交
1227

W
wizardforcel 已提交
1228 1229 1230 1231 1232

```py
Shape:
```

C
chen 已提交
1233
*   输入: ![](img/7db3e5e5d600c81e77756d5eee050505.jpg)
W
wizardforcel 已提交
1234

C
chen 已提交
1235
*   输出: ![](img/3423094375906aa21d1b2e095e95c230.jpg) 其中,
W
wizardforcel 已提交
1236 1237 1238 1239 1240

    ![](img/c37a7e44707d3c08522f44ab4e4d6841.jpg)

| Variables: | 

C
chen 已提交
1241 1242
*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) –  模块中的一个大小为 (in_channels, out_channels, kernel_size[0])的权重张量,这些权重可训练学习(learnable)。这些权重的初始值的采样空间是![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg),其中 ![](img/69aab1ce658aabc9a2d986ae8281e2ad.jpg)
*   **bias** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – 模块的偏差项,大小为 (out_channels), 如果构造函数中的 `bias` 被置为 `True`,那么这些权重的初始值的采样空间是 ![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg) ,其中 ![](img/69aab1ce658aabc9a2d986ae8281e2ad.jpg)
W
wizardforcel 已提交
1243

W
wizardforcel 已提交
1244

W
wizardforcel 已提交
1245 1246 1247 1248

### ConvTranspose2d

```py
W
wizardforcel 已提交
1249
class torch.nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True, dilation=1)
W
wizardforcel 已提交
1250 1251
```

C
chen 已提交
1252
利用指定大小的二维转置卷积核对输入的多通道二维输入信号进行转置卷积(当然此卷积也是互相关操作,cross-correlation)操作的模块。
W
wizardforcel 已提交
1253

C
chen 已提交
1254
该模块可以看作是Conv2d相对于其输入的梯度(the gradient of Conv2d with respect to its input, 直译), 转置卷积又被称为小数步长卷积或是反卷积(尽管这不是一个真正意义上的反卷积)。
W
wizardforcel 已提交
1255

C
chen 已提交
1256
*   `stride` 控制了转置卷积操作的步长 
W
wizardforcel 已提交
1257

C
chen 已提交
1258
*   `padding` 控制了要在输入的各维度的各边上补齐0的层数,与Conv1d不同的地方,此padding参数与实际补齐0的层数的关系为`层数 = kernel_size - 1 - padding`,详情请见下面的note。
W
wizardforcel 已提交
1259

C
chen 已提交
1260
  *   `output_padding` 控制了转置卷积操作输出的各维度的长度增量,但注意这个参数不是说要往转置卷积的输出上pad 0,而是直接控制转置卷积的输出大小为根据此参数pad后的大小。更多的详情请见下面的note。
W
wizardforcel 已提交
1261

C
chen 已提交
1262
*   `dilation` 控制了卷积核中各点之间的空间距离;这也被称为多孔算法(à trous algorithm)。这个概念有点难解释,这个链接[link](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md)用可视化的方法很好地解释了dilation的作用。
W
wizardforcel 已提交
1263

C
chen 已提交
1264
*   `groups` 控制了输入输出之间的连接(connections)的数量。`in_channels``out_channels` 必须能被 `groups` 整除。举个栗子,
W
wizardforcel 已提交
1265

C
chen 已提交
1266 1267 1268 1269 1270 1271 1272
    &gt; *   当 groups=1, 此Conv1d层会使用一个卷积层进行所有输入到输出的卷积操作。
    
    &gt; *   当 groups=2, 此时Conv1d层会产生两个并列的卷积层。同时,输入通道被分为两半,两个卷积层分别处理一半的输入通道,同时各自产生一半的输出通道。最后这两个卷积层的输出会被concatenated一起,作为此Conv1d层的输出。
    
    &gt; *   当 groups= `in_channels`, 每个输入通道都会被单独的一组卷积层处理,这个组的大小是![](img/648a514da1dace3deacf3f078287e157.jpg)。
    
`kernel_size`, `stride`, `padding`, `output_padding` 这几个参数均支持一下输入形式:
W
wizardforcel 已提交
1273

C
chen 已提交
1274 1275
> *   一个 `int` 数字 – 二维维数据的高和宽这两个维度都会采用这一个数字。
> *   一个由两个int数字组成的`tuple`– 这种情况下,二维数据的高这一维度会采用元组中的第一个`int`数字,宽这一维度会采用第二个`int`数字。
W
wizardforcel 已提交
1276 1277 1278

Note

C
chen 已提交
1279 1280
取决于你卷积核的大小,有些时候输入数据中某些列(最后几列)可能不会参与计算(比如列数整除卷积核大小有余数,而又没有padding,那最后的余数列一般不会参与卷积计算),这主要是因为pytorch中的互相关操作[cross-correlation](https://en.wikipedia.org/wiki/Cross-correlation)是保证计算正确的操作(valid operation), 而不是满操作(full operation)。所以实际操作中,还是要亲尽量选择好合适的padding参数哦。

W
wizardforcel 已提交
1281 1282 1283

Note

C
chen 已提交
1284
`padding` 参数控制了要在输入的各维度各边上补齐0的层数,与在Conv1d中不同的是,在转置卷积操作过程中,此padding参数与实际补齐0的层数的关系为`层数 = kernel_size - 1 - padding`, 这样设置的主要原因是当使用相同的参数构建[`Conv2d`](#torch.nn.Conv2d "torch.nn.Conv2d")[`ConvTranspose2d`](#torch.nn.ConvTranspose2d "torch.nn.ConvTranspose2d")模块的时候,这种设置能够实现两个模块有正好相反的输入输出的大小,即Conv2d的输出大小是其对应的ConvTranspose2d模块的输入大小,而ConvTranspose2d的输出大小又恰好是其对应的Conv2d模块的输入大小。然而,当`stride > 1`的时候,[`Conv2d`](#torch.nn.Conv2d "torch.nn.Conv2d") 的一个输出大小可能会对应多个输入大小,上一个note中就详细的介绍了这种情况,这样的情况下要保持前面提到两种模块的输入输出保持反向一致,那就要用到 `output_padding`参数了,这个参数可以增加转置卷积输出的某一维度的大小,以此来达到前面提到的同参数构建的[`Conv2d`](#torch.nn.Conv2d "torch.nn.Conv2d")[`ConvTranspose2d`](#torch.nn.ConvTranspose2d "torch.nn.ConvTranspose2d")模块的输入输出方向一致。 但注意这个参数不是说要往转置卷积的输出上pad 0,而是直接控制转置卷积的输出各维度的大小为根据此参数pad后的大小。
W
wizardforcel 已提交
1285 1286 1287

Note

C
chen 已提交
1288
当程序的运行环境是使用了CuDNN的CUDA环境的时候,一些非确定性的算法(nondeterministic algorithm)可能会被采用以提高整个计算的性能。如果不想使用这些非确定性的算法,你可以通过设置`torch.backends.cudnn.deterministic = True`来让整个计算过程保持确定性(可能会损失一定的计算性能)。对于后端(background),你可以看一下这一部分[Reproducibility](notes/randomness.html)了解其相关信息。
W
wizardforcel 已提交
1289

C
chen 已提交
1290
Parameters:
W
wizardforcel 已提交
1291

C
chen 已提交
1292 1293 1294 1295 1296 1297 1298 1299 1300
*   **in_channels** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – 输入通道的个数
*   **out_channels** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – 卷积操作输出通道的个数
*   **kernel_size** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – 卷积核大小
*   **stride** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 卷积操作的步长。 默认: 1
*   **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – `kernel_size - 1 - padding` 层 0 会被补齐到输入数据的各边上。 默认: 0
*   **output_padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 输出的各维度要增加的大小。默认:0 
*   **groups** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – 输入通道与输出通道之间相互隔离的连接的个数。 默认:1
*   **bias** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – 如果被置为 `True`,向输出增加一个偏差量,此偏差是可学习参数。 默认:`True`
*   **dilation** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 卷积核各元素之间的距离。 默认: 1
W
wizardforcel 已提交
1301

W
wizardforcel 已提交
1302 1303 1304 1305 1306

```py
Shape:
```

C
chen 已提交
1307 1308
*   输入: ![](img/0385ad868fed790d36381b9e8788c18b.jpg)
*   输出: ![](img/d3edfe8a9bbdd73ba5c4b566353777f0.jpg) 其中
W
wizardforcel 已提交
1309 1310 1311 1312 1313 1314 1315

![](img/a2616e3fb8e8e919b799c2e62921c374.jpg)

![](img/dee6540c49e827b0ececaf0154154b54.jpg)

| Variables: | 

C
chen 已提交
1316 1317
*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) –  模块中的一个大小为 (in_channels, out_channels, kernel_size[0], kernel_size[1])的权重张量,这些权重可训练学习(learnable)。这些权重的初始值的采样空间是![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg),其中 ![](img/c12e2153347b696ebb784e5675cc566e.jpg)
*   **bias** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – 模块的偏差项,大小为 (out_channels), 如果构造函数中的 `bias` 被置为 `True`,那么这些权重的初始值的采样空间是 ![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg) ,其中 ![](img/c12e2153347b696ebb784e5675cc566e.jpg)
W
wizardforcel 已提交
1318

W
wizardforcel 已提交
1319

W
wizardforcel 已提交
1320

C
chen 已提交
1321
例子:
W
wizardforcel 已提交
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345

```py
>>> # With square kernels and equal stride
>>> m = nn.ConvTranspose2d(16, 33, 3, stride=2)
>>> # non-square kernels and unequal stride and with padding
>>> m = nn.ConvTranspose2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
>>> input = torch.randn(20, 16, 50, 100)
>>> output = m(input)
>>> # exact output size can be also specified as an argument
>>> input = torch.randn(1, 16, 12, 12)
>>> downsample = nn.Conv2d(16, 16, 3, stride=2, padding=1)
>>> upsample = nn.ConvTranspose2d(16, 16, 3, stride=2, padding=1)
>>> h = downsample(input)
>>> h.size()
torch.Size([1, 16, 6, 6])
>>> output = upsample(h, output_size=input.size())
>>> output.size()
torch.Size([1, 16, 12, 12])

```

### ConvTranspose3d

```py
W
wizardforcel 已提交
1346
class torch.nn.ConvTranspose3d(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True, dilation=1)
W
wizardforcel 已提交
1347 1348
```

C
chen 已提交
1349
利用指定大小的三维转置卷积核对输入的多通道三维输入信号进行转置卷积(当然此卷积也是互相关操作,cross-correlation)操作的模块。转置卷积的操作本质是将各通道输入与卷积核做乘法,然后返回各通道与此卷积核乘积结果之和(卷积的定义)。
W
wizardforcel 已提交
1350

C
chen 已提交
1351
该模块可以看作是Conv3d相对于其输入的梯度(the gradient of Conv3d with respect to its input, 直译), 转置卷积又被称为小数步长卷积或是反卷积(尽管这不是一个真正意义上的反卷积)。
W
wizardforcel 已提交
1352

C
chen 已提交
1353
*   `stride` 控制了转置卷积操作的步长 
W
wizardforcel 已提交
1354

C
chen 已提交
1355
*   `padding` 控制了要在输入的各维度的各边上补齐0的层数,与Conv1d不同的地方,此padding参数与实际补齐0的层数的关系为`层数 = kernel_size - 1 - padding`,详情请见下面的note。
W
wizardforcel 已提交
1356

C
chen 已提交
1357
  *   `output_padding` 控制了转置卷积操作输出的各维度的长度增量,但注意这个参数不是说要往转置卷积的输出上pad 0,而是直接控制转置卷积的输出大小为根据此参数pad后的大小。更多的详情请见下面的note。
W
wizardforcel 已提交
1358

C
chen 已提交
1359
*   `dilation` 控制了卷积核中各点之间的空间距离;这也被称为多孔算法(à trous algorithm)。这个概念有点难解释,这个链接[link](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md)用可视化的方法很好地解释了dilation的作用。
W
wizardforcel 已提交
1360

C
chen 已提交
1361
*   `groups` 控制了输入输出之间的连接(connections)的数量。`in_channels``out_channels` 必须能被 `groups` 整除。举个栗子,
W
wizardforcel 已提交
1362

C
chen 已提交
1363 1364 1365 1366 1367 1368 1369
    &gt; *   当 groups=1, 此Conv1d层会使用一个卷积层进行所有输入到输出的卷积操作。
    
    &gt; *   当 groups=2, 此时Conv1d层会产生两个并列的卷积层。同时,输入通道被分为两半,两个卷积层分别处理一半的输入通道,同时各自产生一半的输出通道。最后这两个卷积层的输出会被concatenated一起,作为此Conv1d层的输出。
    
    &gt; *   当 groups= `in_channels`, 每个输入通道都会被单独的一组卷积层处理,这个组的大小是![](img/648a514da1dace3deacf3f078287e157.jpg)。
    
`kernel_size`, `stride`, `padding`, `output_padding` 这几个参数均支持一下输入形式:
W
wizardforcel 已提交
1370

C
chen 已提交
1371 1372
> *   一个 `int` 数字 – 三维维数据的深度,高和宽这两个维度都会采用这一个数字。
> *   一个由三个int数字组成的`tuple`– 这种情况下,三维数据的深度这一维度会采用元组中的第一个`int`数字,高这一维度会采用元组中的第二个`int`数字,宽这一维度会采用第三个`int`数字。
W
wizardforcel 已提交
1373 1374 1375

Note

C
chen 已提交
1376
取决于你卷积核的大小,有些时候输入数据中某些列(最后几列)可能不会参与计算(比如列数整除卷积核大小有余数,而又没有padding,那最后的余数列一般不会参与卷积计算),这主要是因为pytorch中的互相关操作[cross-correlation](https://en.wikipedia.org/wiki/Cross-correlation)是保证计算正确的操作(valid operation), 而不是满操作(full operation)。所以实际操作中,还是要亲尽量选择好合适的padding参数哦。
W
wizardforcel 已提交
1377 1378 1379 1380


Note

C
chen 已提交
1381
`padding` 参数控制了要在输入的各维度各边上补齐0的层数,与在Conv3d中不同的是,在转置卷积操作过程中,此padding参数与实际补齐0的层数的关系为`层数 = kernel_size - 1 - padding`, 这样设置的主要原因是当使用相同的参数构建[`Conv3d`](#torch.nn.Conv3d "torch.nn.Conv3d")[`ConvTranspose3d`](#torch.nn.ConvTranspose3d "torch.nn.ConvTranspose3d")模块的时候,这种设置能够实现两个模块有正好相反的输入输出的大小,即Conv3d的输出大小是其对应的ConvTranspose3d模块的输入大小,而ConvTranspose3d的输出大小又恰好是其对应的Conv3d模块的输入大小。然而,当`stride > 1`的时候,[`Conv3d`](#torch.nn.Conv3d "torch.nn.Conv3d") 的一个输出大小可能会对应多个输入大小,上一个note中就详细的介绍了这种情况,这样的情况下要保持前面提到两种模块的输入输出保持反向一致,那就要用到 `output_padding`参数了,这个参数可以增加转置卷积输出的某一维度的大小,以此来达到前面提到的同参数构建的[`Conv3d`](#torch.nn.Conv3d "torch.nn.Conv3d")[`ConvTranspose3d`](#torch.nn.ConvTranspose3d "torch.nn.ConvTranspose3d")模块的输入输出方向一致。 但注意这个参数不是说要往转置卷积的输出上pad 0,而是直接控制转置卷积的输出各维度的大小为根据此参数pad后的大小。
W
wizardforcel 已提交
1382

C
chen 已提交
1383
Note
W
wizardforcel 已提交
1384

C
chen 已提交
1385
当程序的运行环境是使用了CuDNN的CUDA环境的时候,一些非确定性的算法(nondeterministic algorithm)可能会被采用以提高整个计算的性能。如果不想使用这些非确定性的算法,你可以通过设置`torch.backends.cudnn.deterministic = True`来让整个计算过程保持确定性(可能会损失一定的计算性能)。对于后端(background),你可以看一下这一部分[Reproducibility](notes/randomness.html)了解其相关信息。
W
wizardforcel 已提交
1386

C
chen 已提交
1387
Parameters:
W
wizardforcel 已提交
1388

C
chen 已提交
1389 1390 1391 1392 1393 1394 1395 1396 1397
*   **in_channels** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – 输入通道的个数
*   **out_channels** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – 卷积操作输出通道的个数
*   **kernel_size** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – 卷积核大小
*   **stride** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 卷积操作的步长。 默认: 1
*   **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – `kernel_size - 1 - padding` 层 0 会被补齐到输入数据的各边上。 默认: 0
*   **output_padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 输出的各维度要增加的大小。默认:0 
*   **groups** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – 输入通道与输出通道之间相互隔离的连接的个数。 默认:1
*   **bias** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – 如果被置为 `True`,向输出增加一个偏差量,此偏差是可学习参数。 默认:`True`
*   **dilation** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 卷积核各元素之间的距离。 默认: 1
W
wizardforcel 已提交
1398 1399 1400 1401 1402

```py
Shape:
```

C
chen 已提交
1403 1404
*   输入: ![](img/a8d71105bc4954eb54660bc5d37c23de.jpg)
*   输出: ![](img/f05e8faaf90b4c16b23ca0165e8e09f4.jpg) 其中
W
wizardforcel 已提交
1405 1406 1407 1408 1409 1410 1411 1412 1413

![](img/35234de680c85870881b7f5d9e8de589.jpg)

![](img/044bc4ee93fc4a1725b5b5dc5840b408.jpg)

![](img/133b249f21b73617ee100c4c072eee15.jpg)

| Variables: | 

C
chen 已提交
1414 1415
*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) –  模块中的一个大小为 (in_channels, out_channels, kernel_size[0], kernel_size[1], kernel_size[2])的权重张量,这些权重可训练学习(learnable)。这些权重的初始值的采样空间是![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg),其中 ![](img/378f5c5b47c36239b817ad23a612a9f7.jpg)
*   **bias** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – 模块的偏差项,大小为 (out_channels), 如果构造函数中的 `bias` 被置为 `True`,那么这些权重的初始值的采样空间是 ![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg),其中 ![](img/378f5c5b47c36239b817ad23a612a9f7.jpg)
W
wizardforcel 已提交
1416

C
chen 已提交
1417
例子:
W
wizardforcel 已提交
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431

```py
>>> # With square kernels and equal stride
>>> m = nn.ConvTranspose3d(16, 33, 3, stride=2)
>>> # non-square kernels and unequal stride and with padding
>>> m = nn.ConvTranspose3d(16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(0, 4, 2))
>>> input = torch.randn(20, 16, 10, 50, 100)
>>> output = m(input)

```

### Unfold

```py
W
wizardforcel 已提交
1432
class torch.nn.Unfold(kernel_size, dilation=1, padding=0, stride=1)
W
wizardforcel 已提交
1433 1434
```

C
330  
chen 已提交
1435
将一个batch的输入张量展开成由多个滑动局部块组成的形式。(im2col的扩展模块,起到基本类似im2col的作用)
W
wizardforcel 已提交
1436

C
chen 已提交
1437 1438
以一个大小为![](img/2468b226c29a7e754a9c20f0214fa85f.jpg)的批次化(batched)输入张量为例,其中![](img/9341d9048ac485106d2b2ee8de14876f.jpg)是batch的大小,![](img/6c8feca3b2da3d6cf371417edff4be4f.jpg)是通道数量,![](img/28ec51e742166ea3400be6e7343bbfa5.jpg)代表了任意空间维度。那Unfold这个操作在此张量上的操作就是,将这个张量展开成由多个`kernel_size`大小的滑动块组成的大小为![](img/4e1cad10fa9480fa82adbe59a5ae81fa.jpg)的三维张量,其中![](img/a8846766f2e1b47021f1520993773ccb.jpg)是每个块中数的个数(每个块有![](img/8c7a54ca7193bc3a6c5ace8c3b07d24c.jpg)个空间位置,每个空间位置存储一个通道大小为![](img/6c8feca3b2da3d6cf371417edff4be4f.jpg)的向量),![](img/db4a9fef02111450bf98261889de550c.jpg)是块的个数:

W
wizardforcel 已提交
1439 1440

![](img/1d2c6a9103e2b33f725602aebf90364e.jpg)
C
chen 已提交
1441
(这张图有问题啊,编辑整理的时候注意修正一下)
W
wizardforcel 已提交
1442

C
chen 已提交
1443
其中 ![](img/42a2dca8a9cb6104321cf29ae30fd56a.jpg) 是由上面例子中的`input`各空间维度组成的,![](img/9566974d45a96737f7e0ecf302d877b8.jpg)遍历了各个空间维度。
W
wizardforcel 已提交
1444

C
chen 已提交
1445
因此,索引Fold操作的`output`的最后一个维度等价于索引某一个block,而索引操作的返回值是这个索引到的block中的所有值。
W
wizardforcel 已提交
1446 1447


C
chen 已提交
1448 1449 1450 1451 1452
`padding`, `stride``dilation` 参数指明了滑动块的相关性质。

*   `stride` 控制了滑动块的步长。
*   `padding` 控制了在变形之前要向input的各维度各边上补齐的0的层数。 
*   `dilation` 控制了卷积核中各点之间的空间距离;这也被称为多孔算法(à trous algorithm)。这个概念有点难解释,这个链接[link](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md)用可视化的方法很好地解释了dilation的作用。
W
wizardforcel 已提交
1453

W
wizardforcel 已提交
1454
Parameters: 
W
wizardforcel 已提交
1455

C
chen 已提交
1456 1457 1458 1459
*   **kernel_size** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – 滑动块的大小
*   **stride** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 滑动块在输入各维度上的步长。默认: 1
*   **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 在输入各维度各边上补齐0的层数。
*   **dilation** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 控制了各元素之间的距离(没有指明元素具体指的是谁的元素,猜测是输出的)。默认:1 
W
wizardforcel 已提交
1460

W
wizardforcel 已提交
1461

W
wizardforcel 已提交
1462

C
chen 已提交
1463 1464
*   如果 `kernel_size`, `dilation`, `padding` 或者 `stride`的值是一个int,或是一个长度为1的int元组,在相关操作的时候各个空间维度上都会使用这同一个值。 
*   如果输出向量有两个空间维度,那么此Fold操作有时又被称为`im2col`
W
wizardforcel 已提交
1465 1466

Note
C
330  
chen 已提交
1467
[`Fold`](#torch.nn.Fold "torch.nn.Fold")在执行类`col2im`的操作的时候,主要是是通过集成此im(输出张量)分裂出所有对应位置的col(输入的滑动块)来复原原im。而[`Unfold`](#torch.nn.Unfold "torch.nn.Unfold")则是通过从输入张量中不断拷贝数值到相应的block中来生成由滑动块组成的输出张量。所以,如果滑动块之间如果有数值重叠,那这些滑动块之间并不是互逆的。
W
wizardforcel 已提交
1468 1469 1470

Warning

C
chen 已提交
1471
目前,只有四维张量(比如批次化的图像张量)支持这个操作。
W
wizardforcel 已提交
1472 1473 1474 1475 1476

```py
Shape:
```

C
chen 已提交
1477 1478
*   输入: ![](img/2468b226c29a7e754a9c20f0214fa85f.jpg)
*   输出: ![](img/4e1cad10fa9480fa82adbe59a5ae81fa.jpg)
W
wizardforcel 已提交
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506

Examples:

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

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

```

### Fold

```py
W
wizardforcel 已提交
1507
class torch.nn.Fold(output_size, kernel_size, dilation=1, padding=0, stride=1)
W
wizardforcel 已提交
1508 1509
```

C
330  
chen 已提交
1510
将由滑动局部块组成的数组集合为一个大张量。(类col2im)
W
wizardforcel 已提交
1511

C
chen 已提交
1512
考虑一个包含了很多个滑动局部块的输入张量,比如,一批图像分割块(patches of images)的集合,大小为![](img/9e56ff5e3827b936da5cfa3a5258b12e.jpg),其中![](img/9341d9048ac485106d2b2ee8de14876f.jpg)是batch大小, ![](img/a8846766f2e1b47021f1520993773ccb.jpg) 是一个块中的数值个数(每个块有![](img/8c7a54ca7193bc3a6c5ace8c3b07d24c.jpg)个空间位置,每个空间位置存储一个通道大小为![](img/6c8feca3b2da3d6cf371417edff4be4f.jpg)的向量),![](img/db4a9fef02111450bf98261889de550c.jpg)是滑动块的个数。(这些大小参数严格遵循了[`Unfold`](#torch.nn.Unfold "torch.nn.Unfold")操作的输出向量的大小规定。)Fold操作通过求和重叠值的方式来将这些局部块集合为一个大小为![](img/c2176aae9e099eeee07cc00c4dc7b7e7.jpg)`output`张量。与 [`Unfold`](#torch.nn.Unfold "torch.nn.Unfold")类似,这些参数必须满足:
W
wizardforcel 已提交
1513 1514 1515

![](img/465bba7070e80a7e5964f46f7f5ed8bb.jpg)

C
chen 已提交
1516
其中![](img/9566974d45a96737f7e0ecf302d877b8.jpg)遍历了各个空间维度。
W
wizardforcel 已提交
1517

C
chen 已提交
1518
*   `output_size` 描述了要生成的output的各空间维度的大小。有时,同样数量的滑动块,可能会产生多种`input`的形状,比如,当`stride > 0`的时候,这时候,设置`output_size`参数就会显得极为重要。
W
wizardforcel 已提交
1519

C
chen 已提交
1520
`padding`, `stride``dilation` 参数指明了滑动块的相关性质。
W
wizardforcel 已提交
1521

C
chen 已提交
1522 1523 1524
*   `stride` 控制了滑动块的步长。
*   `padding` 控制了在变形之前要向input的各维度各边上补齐的0的层数。 
*   `dilation` 控制了卷积核中各点之间的空间距离;这也被称为多孔算法(à trous algorithm)。这个概念有点难解释,这个链接[link](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md)用可视化的方法很好地解释了dilation的作用。
W
wizardforcel 已提交
1525

W
wizardforcel 已提交
1526
Parameters: 
W
wizardforcel 已提交
1527

C
chen 已提交
1528
*   **output_size** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) –  输出向量的各空间维度的大小 (i.e., `input.sizes()[2:]`)
W
wizardforcel 已提交
1529

C
chen 已提交
1530 1531 1532 1533
*   **kernel_size** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – 滑动块的大小
*   **stride** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 滑动块在输入各维度上的步长。默认: 1
*   **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 在输入各维度各边上补齐0的层数。
*   **dilation** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – 控制了各元素之间的距离(没有指明元素具体指的是谁的元素,猜测是输出的)。默认:1 
W
wizardforcel 已提交
1534

W
wizardforcel 已提交
1535 1536 1537



C
chen 已提交
1538 1539 1540 1541
*   如果`output_size``kernel_size`, `dilation`, `padding` 或者 `stride`是一个int或者长度为1的int元组,在相关操作的时候各个空间维度上都会使用这同一个值。 
*   如果此输出向量的空间维度数为2,那么此Fold操作有时又被称为`col2im`

Note
C
330  
chen 已提交
1542
[`Fold`](#torch.nn.Fold "torch.nn.Fold")在执行类`col2im`的操作的时候,主要是是通过集成此im(输出张量)分裂出所有对应位置的col(输入的滑动块)来复原原im。而[`Unfold`](#torch.nn.Unfold "torch.nn.Unfold")则是通过从输入张量中不断拷贝数值到相应的block中来生成由滑动块组成的输出张量。所以,如果滑动块之间如果有数值重叠,那这些滑动块之间并不是互逆的。
W
wizardforcel 已提交
1543 1544 1545

Warning

C
chen 已提交
1546 1547
目前,只有四维张量(比如批次化的图像张量)支持这个操作。

W
wizardforcel 已提交
1548 1549 1550 1551 1552

```py
Shape:
```

C
chen 已提交
1553 1554
*   输入: ![](img/4e1cad10fa9480fa82adbe59a5ae81fa.jpg)
*   输出: ![](img/c2176aae9e099eeee07cc00c4dc7b7e7.jpg) 
W
wizardforcel 已提交
1555

C
chen 已提交
1556
举例:
W
wizardforcel 已提交
1557 1558 1559 1560 1561 1562 1563 1564 1565

```py
>>> fold = nn.Fold(output_size=(4, 5), kernel_size=(2, 2))
>>> input = torch.randn(1, 3 * 2 * 2, 1)
>>> output = fold(input)
>>> output.size()

```

C
red  
chen 已提交
1566
` 卷积层部分Fold 与 Unfold 是1.0新增的内容,猜测其主要目的是开放col2im和im2col这两个通过矩阵乘法实现卷积操作的前序接口,要好好理解这部分可能要了解一下现在主流框架通过大矩阵乘法来实现卷积操作这一通用做法了,这一篇文章就介绍的很好[Implementing convolution as a matrix multiplication](https://buptldy.github.io/2016/10/01/2016-10-01-im2col/),这一段如果感觉我的直译晦涩难懂,那我深感抱歉并建议看一下英文原版,虽然我觉得英文原版介绍的也是晦涩难懂`
C
chen 已提交
1567

C
330  
chen 已提交
1568
## 池化层(Pooling layers)
W
wizardforcel 已提交
1569 1570 1571 1572

### MaxPool1d

```py
W
wizardforcel 已提交
1573
class torch.nn.MaxPool1d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)
W
wizardforcel 已提交
1574
```
C
330  
chen 已提交
1575
对输入的多通道信号执行一维最大池化操作。
W
wizardforcel 已提交
1576

C
330  
chen 已提交
1577
最简单的情况下,对于输入大小为 ![](img/5816e96aa78b7425cf792435bba8bc29.jpg) ,输出大小为![](img/d131773750846713475c600aa8cd917a.jpg)的池化操作,此池化过程可表述如下:
W
wizardforcel 已提交
1578 1579 1580

![](img/9e414c5b7df992e54f3227bb130be349.jpg)

C
330  
chen 已提交
1581 1582
`padding` 参数控制了要在输入信号的各维度各边上要补齐0的层数。
`dilation` 参数控制了池化核中各元素之间的距离;这也被称为多孔算法(à trous algorithm)。这个概念有点难解释,这个链接[link](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md)用可视化的方法很好地解释了`dilation`的作用。
W
wizardforcel 已提交
1583

W
wizardforcel 已提交
1584
Parameters: 
W
wizardforcel 已提交
1585

C
330  
chen 已提交
1586 1587 1588 1589 1590 1591
*   **kernel_size** – 最大池化操作的滑动窗大小
*   **stride** – 滑动窗的步长,默认值是 `kernel_size`
*   **padding** – 要在输入信号的各维度各边上要补齐0的层数
*   **dilation** – 滑动窗中各元素之间的距离
*   **return_indices** – 如果此参数被设置为`True`, 那么此池化层在返回输出信号的同时还会返回一连串滑动窗最大值的索引位置,即每个滑动窗的最大值位置信息。这些信息可以在后面的上采样[`torch.nn.MaxUnpool1d`](#torch.nn.MaxUnpool1d "torch.nn.MaxUnpool1d")中被用到。
*   **ceil_mode** – 如果此参数被设置·True,计算输出信号大小的时候,会使用向上取整,代替默认的向下取整的操作 when True, will use `ceil` instead of `floor` to compute the output shape
W
wizardforcel 已提交
1592

W
wizardforcel 已提交
1593

W
wizardforcel 已提交
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617

```py
Shape:
```

*   Input: ![](img/3ceb415a2a1558bab9998c277f780ec3.jpg)

*   Output: ![](img/d131773750846713475c600aa8cd917a.jpg), where

    ![](img/ff16cce6b4741640e8adc0a271cd4592.jpg)

Examples:

```py
>>> # pool of size=3, stride=2
>>> m = nn.MaxPool1d(3, stride=2)
>>> input = torch.randn(20, 16, 50)
>>> output = m(input)

```

### MaxPool2d

```py
W
wizardforcel 已提交
1618
class torch.nn.MaxPool2d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)
W
wizardforcel 已提交
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
```

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

In the simplest case, the output value of the layer with input size ![](img/23f8772594b27bd387be708fe9c085e1.jpg), output ![](img/a0ef05f779873fc4dcbf020b1ea14754.jpg) and `kernel_size` ![](img/6384e001ad4c0989683deb86f6ffbd2f.jpg) can be precisely described as:

![](img/caa8cbcbb8bbbbc6b0e47f9daa80ab12.jpg)

If `padding` is non-zero, then the input is implicitly zero-padded on both sides for `padding` number of points. `dilation` controls the spacing between the kernel points. It is harder to describe, but this [link](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md) has a nice visualization of what `dilation` does.

The parameters `kernel_size`, `stride`, `padding`, `dilation` can either be:

> *   a single `int` – in which case the same value is used for the height and width dimension
W
wizardforcel 已提交
1632
> *   a `tuple` of two ints – in which case, the first `int` is used for the height dimension, and the second `int` for the width dimension
W
wizardforcel 已提交
1633

W
wizardforcel 已提交
1634
Parameters: 
W
wizardforcel 已提交
1635 1636 1637 1638 1639 1640

*   **kernel_size** – the size of the window to take a max over
*   **stride** – the stride of the window. Default value is `kernel_size`
*   **padding** – implicit zero padding to be added on both sides
*   **dilation** – a parameter that controls the stride of elements in the window
*   **return_indices** – if `True`, will return the max indices along with the outputs. Useful for [`torch.nn.MaxUnpool2d`](#torch.nn.MaxUnpool2d "torch.nn.MaxUnpool2d") later
W
wizardforcel 已提交
1641
*   **ceil_mode** – when True, will use `ceil` instead of `floor` to compute the output shape
W
wizardforcel 已提交
1642

W
wizardforcel 已提交
1643

W
wizardforcel 已提交
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671

```py
Shape:
```

*   Input: ![](img/ff71b16eb10237262566c6907acaaf1f.jpg)

*   Output: ![](img/a0ef05f779873fc4dcbf020b1ea14754.jpg), where

    ![](img/991d42318f90dcb68b26938c542b8457.jpg)

    ![](img/1e35edf42ee6921adb435b5ca638d406.jpg)

Examples:

```py
>>> # pool of square window of size=3, stride=2
>>> m = nn.MaxPool2d(3, stride=2)
>>> # pool of non-square window
>>> m = nn.MaxPool2d((3, 2), stride=(2, 1))
>>> input = torch.randn(20, 16, 50, 32)
>>> output = m(input)

```

### MaxPool3d

```py
W
wizardforcel 已提交
1672
class torch.nn.MaxPool3d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)
W
wizardforcel 已提交
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
```

Applies a 3D max pooling over an input signal composed of several input planes. This is not a test

In the simplest case, the output value of the layer with input size ![](img/f5a45f7b445db562b21cfcb525637aab.jpg), output ![](img/41ca4c8d4c65c979d2d643c6f62ea280.jpg) and `kernel_size` ![](img/f5dcdebf9a81b9d15227749ae7535eb7.jpg) can be precisely described as:

![](img/f0f7a770dcfb802e7fc0f8995cfad3d7.jpg)

If `padding` is non-zero, then the input is implicitly zero-padded on both sides for `padding` number of points. `dilation` controls the spacing between the kernel points. It is harder to describe, but this [link](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md) has a nice visualization of what `dilation` does.

The parameters `kernel_size`, `stride`, `padding`, `dilation` can either be:

> *   a single `int` – in which case the same value is used for the depth, height and width dimension
W
wizardforcel 已提交
1686
> *   a `tuple` of three ints – in which case, the first `int` is used for the depth dimension, the second `int` for the height dimension and the third `int` for the width dimension
W
wizardforcel 已提交
1687

W
wizardforcel 已提交
1688
Parameters: 
W
wizardforcel 已提交
1689 1690 1691 1692 1693 1694

*   **kernel_size** – the size of the window to take a max over
*   **stride** – the stride of the window. Default value is `kernel_size`
*   **padding** – implicit zero padding to be added on all three sides
*   **dilation** – a parameter that controls the stride of elements in the window
*   **return_indices** – if `True`, will return the max indices along with the outputs. Useful for [`torch.nn.MaxUnpool3d`](#torch.nn.MaxUnpool3d "torch.nn.MaxUnpool3d") later
W
wizardforcel 已提交
1695
*   **ceil_mode** – when True, will use `ceil` instead of `floor` to compute the output shape
W
wizardforcel 已提交
1696

W
wizardforcel 已提交
1697

W
wizardforcel 已提交
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727

```py
Shape:
```

*   Input: ![](img/c187d190013d0785320e3412fe8cd669.jpg)

*   Output: ![](img/41ca4c8d4c65c979d2d643c6f62ea280.jpg), where

    ![](img/0e49f319aa911192458f7b02321eff3a.jpg)

    ![](img/b8fbd329439d7eba62abdf0df19f464d.jpg)

    ![](img/eb1d0c30d1cf681f38e8391bd7d03dff.jpg)

Examples:

```py
>>> # pool of square window of size=3, stride=2
>>> m = nn.MaxPool3d(3, stride=2)
>>> # pool of non-square window
>>> m = nn.MaxPool3d((3, 2, 2), stride=(2, 1, 2))
>>> input = torch.randn(20, 16, 50,44, 31)
>>> output = m(input)

```

### MaxUnpool1d

```py
W
wizardforcel 已提交
1728
class torch.nn.MaxUnpool1d(kernel_size, stride=None, padding=0)
W
wizardforcel 已提交
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
```

Computes a partial inverse of [`MaxPool1d`](#torch.nn.MaxPool1d "torch.nn.MaxPool1d").

[`MaxPool1d`](#torch.nn.MaxPool1d "torch.nn.MaxPool1d") is not fully invertible, since the non-maximal values are lost.

[`MaxUnpool1d`](#torch.nn.MaxUnpool1d "torch.nn.MaxUnpool1d") takes in as input the output of [`MaxPool1d`](#torch.nn.MaxPool1d "torch.nn.MaxPool1d") including the indices of the maximal values and computes a partial inverse in which all non-maximal values are set to zero.

Note

[`MaxPool1d`](#torch.nn.MaxPool1d "torch.nn.MaxPool1d") can map several input sizes to the same output sizes. Hence, the inversion process can get ambiguous. To accommodate this, you can provide the needed output size as an additional argument `output_size` in the forward call. See the Inputs and Example below.

W
wizardforcel 已提交
1741
Parameters: 
W
wizardforcel 已提交
1742 1743 1744 1745 1746

*   **kernel_size** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – Size of the max pooling window.
*   **stride** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – Stride of the max pooling window. It is set to `kernel_size` by default.
*   **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – Padding that was added to the input

W
wizardforcel 已提交
1747

W
wizardforcel 已提交
1748 1749 1750 1751 1752

```py
Inputs:
```

W
wizardforcel 已提交
1753 1754 1755
*   `input`: the input Tensor to invert
*   `indices`: the indices given out by [`MaxPool1d`](#torch.nn.MaxPool1d "torch.nn.MaxPool1d")
*   `output_size` (optional): the targeted output size
W
wizardforcel 已提交
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792

```py
Shape:
```

*   Input: ![](img/ccc1792005f1eb97a439118aeba930e9.jpg)

*   Output: ![](img/1b0403b4ee318895368afc8fa37b9407.jpg), where

    ![](img/9618fc866026e724d16c5481dd67dc4c.jpg)

    or as given by `output_size` in the call operator

Example:

```py
>>> pool = nn.MaxPool1d(2, stride=2, return_indices=True)
>>> unpool = nn.MaxUnpool1d(2, stride=2)
>>> input = torch.tensor([[[1., 2, 3, 4, 5, 6, 7, 8]]])
>>> output, indices = pool(input)
>>> unpool(output, indices)
tensor([[[ 0.,  2.,  0.,  4.,  0.,  6.,  0., 8.]]])

>>> # Example showcasing the use of output_size
>>> input = torch.tensor([[[1., 2, 3, 4, 5, 6, 7, 8, 9]]])
>>> output, indices = pool(input)
>>> unpool(output, indices, output_size=input.size())
tensor([[[ 0.,  2.,  0.,  4.,  0.,  6.,  0., 8.,  0.]]])

>>> unpool(output, indices)
tensor([[[ 0.,  2.,  0.,  4.,  0.,  6.,  0., 8.]]])

```

### MaxUnpool2d

```py
W
wizardforcel 已提交
1793
class torch.nn.MaxUnpool2d(kernel_size, stride=None, padding=0)
W
wizardforcel 已提交
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
```

Computes a partial inverse of [`MaxPool2d`](#torch.nn.MaxPool2d "torch.nn.MaxPool2d").

[`MaxPool2d`](#torch.nn.MaxPool2d "torch.nn.MaxPool2d") is not fully invertible, since the non-maximal values are lost.

[`MaxUnpool2d`](#torch.nn.MaxUnpool2d "torch.nn.MaxUnpool2d") takes in as input the output of [`MaxPool2d`](#torch.nn.MaxPool2d "torch.nn.MaxPool2d") including the indices of the maximal values and computes a partial inverse in which all non-maximal values are set to zero.

Note

[`MaxPool2d`](#torch.nn.MaxPool2d "torch.nn.MaxPool2d") can map several input sizes to the same output sizes. Hence, the inversion process can get ambiguous. To accommodate this, you can provide the needed output size as an additional argument `output_size` in the forward call. See the Inputs and Example below.

W
wizardforcel 已提交
1806
Parameters: 
W
wizardforcel 已提交
1807 1808 1809 1810 1811

*   **kernel_size** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – Size of the max pooling window.
*   **stride** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – Stride of the max pooling window. It is set to `kernel_size` by default.
*   **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – Padding that was added to the input

W
wizardforcel 已提交
1812

W
wizardforcel 已提交
1813 1814 1815 1816 1817

```py
Inputs:
```

W
wizardforcel 已提交
1818 1819 1820
*   `input`: the input Tensor to invert
*   `indices`: the indices given out by [`MaxPool2d`](#torch.nn.MaxPool2d "torch.nn.MaxPool2d")
*   `output_size` (optional): the targeted output size
W
wizardforcel 已提交
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864

```py
Shape:
```

*   Input: ![](img/ff71b16eb10237262566c6907acaaf1f.jpg)

*   Output: ![](img/a0ef05f779873fc4dcbf020b1ea14754.jpg), where

    ![](img/f6dd707e18ccbf75f607d05338443e87.jpg)

    ![](img/ac5d54ef9922f9e0dbe2dc916bf9d80b.jpg)

    or as given by `output_size` in the call operator

Example:

```py
>>> pool = nn.MaxPool2d(2, stride=2, return_indices=True)
>>> unpool = nn.MaxUnpool2d(2, stride=2)
>>> input = torch.tensor([[[[ 1.,  2,  3,  4],
 [ 5,  6,  7,  8],
 [ 9, 10, 11, 12],
 [13, 14, 15, 16]]]])
>>> output, indices = pool(input)
>>> unpool(output, indices)
tensor([[[[  0.,   0.,   0.,   0.],
 [  0.,   6.,   0.,   8.],
 [  0.,   0.,   0.,   0.],
 [  0.,  14.,   0.,  16.]]]])

>>> # specify a different output size than input size
>>> unpool(output, indices, output_size=torch.Size([1, 1, 5, 5]))
tensor([[[[  0.,   0.,   0.,   0.,   0.],
 [  6.,   0.,   8.,   0.,   0.],
 [  0.,   0.,   0.,  14.,   0.],
 [ 16.,   0.,   0.,   0.,   0.],
 [  0.,   0.,   0.,   0.,   0.]]]])

```

### MaxUnpool3d

```py
W
wizardforcel 已提交
1865
class torch.nn.MaxUnpool3d(kernel_size, stride=None, padding=0)
W
wizardforcel 已提交
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
```

Computes a partial inverse of [`MaxPool3d`](#torch.nn.MaxPool3d "torch.nn.MaxPool3d").

[`MaxPool3d`](#torch.nn.MaxPool3d "torch.nn.MaxPool3d") is not fully invertible, since the non-maximal values are lost. [`MaxUnpool3d`](#torch.nn.MaxUnpool3d "torch.nn.MaxUnpool3d") takes in as input the output of [`MaxPool3d`](#torch.nn.MaxPool3d "torch.nn.MaxPool3d") including the indices of the maximal values and computes a partial inverse in which all non-maximal values are set to zero.

Note

[`MaxPool3d`](#torch.nn.MaxPool3d "torch.nn.MaxPool3d") can map several input sizes to the same output sizes. Hence, the inversion process can get ambiguous. To accommodate this, you can provide the needed output size as an additional argument `output_size` in the forward call. See the Inputs section below.

W
wizardforcel 已提交
1876
Parameters: 
W
wizardforcel 已提交
1877 1878 1879 1880 1881

*   **kernel_size** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – Size of the max pooling window.
*   **stride** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – Stride of the max pooling window. It is set to `kernel_size` by default.
*   **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – Padding that was added to the input

W
wizardforcel 已提交
1882

W
wizardforcel 已提交
1883 1884 1885 1886 1887

```py
Inputs:
```

W
wizardforcel 已提交
1888 1889 1890
*   `input`: the input Tensor to invert
*   `indices`: the indices given out by [`MaxPool3d`](#torch.nn.MaxPool3d "torch.nn.MaxPool3d")
*   `output_size` (optional): the targeted output size
W
wizardforcel 已提交
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923

```py
Shape:
```

*   Input: ![](img/c187d190013d0785320e3412fe8cd669.jpg)

*   Output: ![](img/41ca4c8d4c65c979d2d643c6f62ea280.jpg), where

    ![](img/190cbccb4ab554a9b19bfc3df956f982.jpg)

    ![](img/785a4e892f32eee65446b4e269fc452b.jpg)

    ![](img/e666e9d78ffab5d03b4cf1adf1a6e331.jpg)

    or as given by `output_size` in the call operator

Example:

```py
>>> # pool of square window of size=3, stride=2
>>> pool = nn.MaxPool3d(3, stride=2, return_indices=True)
>>> unpool = nn.MaxUnpool3d(3, stride=2)
>>> output, indices = pool(torch.randn(20, 16, 51, 33, 15))
>>> unpooled_output = unpool(output, indices)
>>> unpooled_output.size()
torch.Size([20, 16, 51, 33, 15])

```

### AvgPool1d

```py
W
wizardforcel 已提交
1924
class torch.nn.AvgPool1d(kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True)
W
wizardforcel 已提交
1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
```

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

In the simplest case, the output value of the layer with input size ![](img/5816e96aa78b7425cf792435bba8bc29.jpg), output ![](img/d131773750846713475c600aa8cd917a.jpg) and `kernel_size` ![](img/a1c2f8d5b1226e67bdb44b12a6ddf18b.jpg) can be precisely described as:

![](img/5df0036df168f4a16d4437d91968f640.jpg)

If `padding` is non-zero, then the input is implicitly zero-padded on both sides for `padding` number of points.

The parameters `kernel_size`, `stride`, `padding` can each be an `int` or a one-element tuple.

W
wizardforcel 已提交
1937
Parameters: 
W
wizardforcel 已提交
1938 1939 1940 1941

*   **kernel_size** – the size of the window
*   **stride** – the stride of the window. Default value is `kernel_size`
*   **padding** – implicit zero padding to be added on both sides
W
wizardforcel 已提交
1942
*   **ceil_mode** – when True, will use `ceil` instead of `floor` to compute the output shape
W
wizardforcel 已提交
1943 1944
*   **count_include_pad** – when True, will include the zero-padding in the averaging calculation

W
wizardforcel 已提交
1945

W
wizardforcel 已提交
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969

```py
Shape:
```

*   Input: ![](img/3ceb415a2a1558bab9998c277f780ec3.jpg)

*   Output: ![](img/d131773750846713475c600aa8cd917a.jpg), where

    ![](img/ad61a9298a545292682229fef2f1a910.jpg)

Examples:

```py
>>> # pool with window of size=3, stride=2
>>> m = nn.AvgPool1d(3, stride=2)
>>> m(torch.tensor([[[1.,2,3,4,5,6,7]]]))
tensor([[[ 2.,  4.,  6.]]])

```

### AvgPool2d

```py
W
wizardforcel 已提交
1970
class torch.nn.AvgPool2d(kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True)
W
wizardforcel 已提交
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
```

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

In the simplest case, the output value of the layer with input size ![](img/23f8772594b27bd387be708fe9c085e1.jpg), output ![](img/a0ef05f779873fc4dcbf020b1ea14754.jpg) and `kernel_size` ![](img/6384e001ad4c0989683deb86f6ffbd2f.jpg) can be precisely described as:

![](img/b7a0e1d0a42a3626724c14d89a10a44f.jpg)

If `padding` is non-zero, then the input is implicitly zero-padded on both sides for `padding` number of points.

The parameters `kernel_size`, `stride`, `padding` can either be:

> *   a single `int` – in which case the same value is used for the height and width dimension
W
wizardforcel 已提交
1984
> *   a `tuple` of two ints – in which case, the first `int` is used for the height dimension, and the second `int` for the width dimension
W
wizardforcel 已提交
1985

W
wizardforcel 已提交
1986
Parameters: 
W
wizardforcel 已提交
1987 1988 1989 1990

*   **kernel_size** – the size of the window
*   **stride** – the stride of the window. Default value is `kernel_size`
*   **padding** – implicit zero padding to be added on both sides
W
wizardforcel 已提交
1991
*   **ceil_mode** – when True, will use `ceil` instead of `floor` to compute the output shape
W
wizardforcel 已提交
1992 1993
*   **count_include_pad** – when True, will include the zero-padding in the averaging calculation

W
wizardforcel 已提交
1994

W
wizardforcel 已提交
1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022

```py
Shape:
```

*   Input: ![](img/ff71b16eb10237262566c6907acaaf1f.jpg)

*   Output: ![](img/a0ef05f779873fc4dcbf020b1ea14754.jpg), where

    ![](img/8b8b2b1a77c4f104a936efb1708366ef.jpg)

    ![](img/2792347200dabe493ae8baee428f9bf8.jpg)

Examples:

```py
>>> # pool of square window of size=3, stride=2
>>> m = nn.AvgPool2d(3, stride=2)
>>> # pool of non-square window
>>> m = nn.AvgPool2d((3, 2), stride=(2, 1))
>>> input = torch.randn(20, 16, 50, 32)
>>> output = m(input)

```

### AvgPool3d

```py
W
wizardforcel 已提交
2023
class torch.nn.AvgPool3d(kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True)
W
wizardforcel 已提交
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
```

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

In the simplest case, the output value of the layer with input size ![](img/f5a45f7b445db562b21cfcb525637aab.jpg), output ![](img/41ca4c8d4c65c979d2d643c6f62ea280.jpg) and `kernel_size` ![](img/f5dcdebf9a81b9d15227749ae7535eb7.jpg) can be precisely described as:

![](img/79acedd31cd18baac8d97ab96a7092e0.jpg)

If `padding` is non-zero, then the input is implicitly zero-padded on all three sides for `padding` number of points.

The parameters `kernel_size`, `stride` can either be:

> *   a single `int` – in which case the same value is used for the depth, height and width dimension
W
wizardforcel 已提交
2037
> *   a `tuple` of three ints – in which case, the first `int` is used for the depth dimension, the second `int` for the height dimension and the third `int` for the width dimension
W
wizardforcel 已提交
2038

W
wizardforcel 已提交
2039
Parameters: 
W
wizardforcel 已提交
2040 2041 2042 2043

*   **kernel_size** – the size of the window
*   **stride** – the stride of the window. Default value is `kernel_size`
*   **padding** – implicit zero padding to be added on all three sides
W
wizardforcel 已提交
2044
*   **ceil_mode** – when True, will use `ceil` instead of `floor` to compute the output shape
W
wizardforcel 已提交
2045 2046
*   **count_include_pad** – when True, will include the zero-padding in the averaging calculation

W
wizardforcel 已提交
2047

W
wizardforcel 已提交
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077

```py
Shape:
```

*   Input: ![](img/c187d190013d0785320e3412fe8cd669.jpg)

*   Output: ![](img/41ca4c8d4c65c979d2d643c6f62ea280.jpg), where

    ![](img/443035401ce7a1144122a862f34493cf.jpg)

    ![](img/8488a299a75cb56e138e1dc5a24a10db.jpg)

    ![](img/c799c115b670c02d039f828fe1afa443.jpg)

Examples:

```py
>>> # pool of square window of size=3, stride=2
>>> m = nn.AvgPool3d(3, stride=2)
>>> # pool of non-square window
>>> m = nn.AvgPool3d((3, 2, 2), stride=(2, 1, 2))
>>> input = torch.randn(20, 16, 50,44, 31)
>>> output = m(input)

```

### FractionalMaxPool2d

```py
W
wizardforcel 已提交
2078
class torch.nn.FractionalMaxPool2d(kernel_size, output_size=None, output_ratio=None, return_indices=False, _random_samples=None)
W
wizardforcel 已提交
2079 2080 2081 2082 2083 2084 2085 2086
```

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

Fractional MaxPooling is described in detail in the paper [Fractional MaxPooling](http://arxiv.org/abs/1412.6071) by Ben Graham

The max-pooling operation is applied in ![](img/52ec12db6613ee8a0f6f41143ab2e8a2.jpg) regions by a stochastic step size determined by the target output size. The number of output features is equal to the number of input planes.

W
wizardforcel 已提交
2087
Parameters: 
W
wizardforcel 已提交
2088

W
wizardforcel 已提交
2089 2090
*   **kernel_size** – the size of the window to take a max over. Can be a single number k (for a square kernel of k x k) or a tuple `(kh x kw)`
*   **output_size** – the target output size of the image of the form `oH x oW`. Can be a tuple `(oH, oW)` or a single number oH for a square image `oH x oH`
W
wizardforcel 已提交
2091 2092 2093
*   **output_ratio** – If one wants to have an output size as a ratio of the input size, this option can be given. This has to be a number or tuple in the range (0, 1)
*   **return_indices** – if `True`, will return the indices along with the outputs. Useful to pass to `nn.MaxUnpool2d()`. Default: `False`

W
wizardforcel 已提交
2094

W
wizardforcel 已提交
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110

Examples

```py
>>> # pool of square window of size=3, and target output size 13x12
>>> m = nn.FractionalMaxPool2d(3, output_size=(13, 12))
>>> # pool of square window and target output size being half of input image size
>>> m = nn.FractionalMaxPool2d(3, output_ratio=(0.5, 0.5))
>>> input = torch.randn(20, 16, 50, 32)
>>> output = m(input)

```

### LPPool1d

```py
W
wizardforcel 已提交
2111
class torch.nn.LPPool1d(norm_type, kernel_size, stride=None, ceil_mode=False)
W
wizardforcel 已提交
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
```

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

On each window, the function computed is:

![](img/e4451f809255881ee286970ddf3fb377.jpg)

*   At p = infinity, one gets Max Pooling
*   At p = 1, one gets Sum Pooling (which is proportional to Average Pooling)

Note

W
wizardforcel 已提交
2125
If the sum to the power of `p` is zero, the gradient of this function is not defined. This implementation will set the gradient to zero in this case.
W
wizardforcel 已提交
2126

W
wizardforcel 已提交
2127
Parameters: 
W
wizardforcel 已提交
2128 2129 2130

*   **kernel_size** – a single int, the size of the window
*   **stride** – a single int, the stride of the window. Default value is `kernel_size`
W
wizardforcel 已提交
2131
*   **ceil_mode** – when True, will use `ceil` instead of `floor` to compute the output shape
W
wizardforcel 已提交
2132

W
wizardforcel 已提交
2133

W
wizardforcel 已提交
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159

```py
Shape:
```

*   Input: ![](img/3ceb415a2a1558bab9998c277f780ec3.jpg)

*   Output: ![](img/d131773750846713475c600aa8cd917a.jpg), where

    ![](img/5d246e9891509c48081bc89191e64418.jpg)

```py
Examples::
```

```py
>>> # power-2 pool of window of length 3, with stride 2.
>>> m = nn.LPPool1d(2, 3, stride=2)
>>> input = torch.randn(20, 16, 50)
>>> output = m(input)

```

### LPPool2d

```py
W
wizardforcel 已提交
2160
class torch.nn.LPPool2d(norm_type, kernel_size, stride=None, ceil_mode=False)
W
wizardforcel 已提交
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
```

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

On each window, the function computed is:

![](img/e4451f809255881ee286970ddf3fb377.jpg)

*   At p = ![](img/b0c1b8fa38555e0b1ca3265b84bb3974.jpg), one gets Max Pooling
*   At p = 1, one gets Sum Pooling (which is proportional to average pooling)

The parameters `kernel_size`, `stride` can either be:

> *   a single `int` – in which case the same value is used for the height and width dimension
W
wizardforcel 已提交
2175
> *   a `tuple` of two ints – in which case, the first `int` is used for the height dimension, and the second `int` for the width dimension
W
wizardforcel 已提交
2176 2177 2178

Note

W
wizardforcel 已提交
2179
If the sum to the power of `p` is zero, the gradient of this function is not defined. This implementation will set the gradient to zero in this case.
W
wizardforcel 已提交
2180

W
wizardforcel 已提交
2181
Parameters: 
W
wizardforcel 已提交
2182 2183 2184

*   **kernel_size** – the size of the window
*   **stride** – the stride of the window. Default value is `kernel_size`
W
wizardforcel 已提交
2185
*   **ceil_mode** – when True, will use `ceil` instead of `floor` to compute the output shape
W
wizardforcel 已提交
2186

W
wizardforcel 已提交
2187

W
wizardforcel 已提交
2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215

```py
Shape:
```

*   Input: ![](img/ff71b16eb10237262566c6907acaaf1f.jpg)

*   Output: ![](img/a0ef05f779873fc4dcbf020b1ea14754.jpg), where

    ![](img/44bfdaa5e6b603085c2da3eddb558556.jpg)

    ![](img/d59b07475dea090e5f7110600d8f8bdc.jpg)

Examples:

```py
>>> # power-2 pool of square window of size=3, stride=2
>>> m = nn.LPPool2d(2, 3, stride=2)
>>> # pool of non-square window of power 1.2
>>> m = nn.LPPool2d(1.2, (3, 2), stride=(2, 1))
>>> input = torch.randn(20, 16, 50, 32)
>>> output = m(input)

```

### AdaptiveMaxPool1d

```py
W
wizardforcel 已提交
2216
class torch.nn.AdaptiveMaxPool1d(output_size, return_indices=False)
W
wizardforcel 已提交
2217 2218 2219 2220 2221 2222
```

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

The output size is H, for any input size. The number of output features is equal to the number of input planes.

W
wizardforcel 已提交
2223
Parameters: 
W
wizardforcel 已提交
2224 2225 2226 2227

*   **output_size** – the target output size H
*   **return_indices** – if `True`, will return the indices along with the outputs. Useful to pass to nn.MaxUnpool1d. Default: `False`

W
wizardforcel 已提交
2228

W
wizardforcel 已提交
2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242

Examples

```py
>>> # target output size of 5
>>> m = nn.AdaptiveMaxPool1d(5)
>>> input = torch.randn(1, 64, 8)
>>> output = m(input)

```

### AdaptiveMaxPool2d

```py
W
wizardforcel 已提交
2243
class torch.nn.AdaptiveMaxPool2d(output_size, return_indices=False)
W
wizardforcel 已提交
2244 2245 2246 2247 2248 2249
```

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

The output is of size H x W, for any input size. The number of output features is equal to the number of input planes.

W
wizardforcel 已提交
2250
Parameters: 
W
wizardforcel 已提交
2251 2252 2253 2254

*   **output_size** – the target output size of the image of the form H x W. Can be a tuple (H, W) or a single H for a square image H x H. H and W can be either a `int`, or `None` which means the size will be the same as that of the input.
*   **return_indices** – if `True`, will return the indices along with the outputs. Useful to pass to nn.MaxUnpool2d. Default: `False`

W
wizardforcel 已提交
2255

W
wizardforcel 已提交
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277

Examples

```py
>>> # target output size of 5x7
>>> m = nn.AdaptiveMaxPool2d((5,7))
>>> input = torch.randn(1, 64, 8, 9)
>>> output = m(input)
>>> # target output size of 7x7 (square)
>>> m = nn.AdaptiveMaxPool2d(7)
>>> input = torch.randn(1, 64, 10, 9)
>>> output = m(input)
>>> # target output size of 10x7
>>> m = nn.AdaptiveMaxPool2d((None, 7))
>>> input = torch.randn(1, 64, 10, 9)
>>> output = m(input)

```

### AdaptiveMaxPool3d

```py
W
wizardforcel 已提交
2278
class torch.nn.AdaptiveMaxPool3d(output_size, return_indices=False)
W
wizardforcel 已提交
2279 2280 2281 2282 2283 2284
```

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

The output is of size D x H x W, for any input size. The number of output features is equal to the number of input planes.

W
wizardforcel 已提交
2285
Parameters: 
W
wizardforcel 已提交
2286 2287 2288 2289

*   **output_size** – the target output size of the image of the form D x H x W. Can be a tuple (D, H, W) or a single D for a cube D x D x D. D, H and W can be either a `int`, or `None` which means the size will be the same as that of the input.
*   **return_indices** – if `True`, will return the indices along with the outputs. Useful to pass to nn.MaxUnpool3d. Default: `False`

W
wizardforcel 已提交
2290

W
wizardforcel 已提交
2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312

Examples

```py
>>> # target output size of 5x7x9
>>> m = nn.AdaptiveMaxPool3d((5,7,9))
>>> input = torch.randn(1, 64, 8, 9, 10)
>>> output = m(input)
>>> # target output size of 7x7x7 (cube)
>>> m = nn.AdaptiveMaxPool3d(7)
>>> input = torch.randn(1, 64, 10, 9, 8)
>>> output = m(input)
>>> # target output size of 7x9x8
>>> m = nn.AdaptiveMaxPool3d((7, None, None))
>>> input = torch.randn(1, 64, 10, 9, 8)
>>> output = m(input)

```

### AdaptiveAvgPool1d

```py
W
wizardforcel 已提交
2313
class torch.nn.AdaptiveAvgPool1d(output_size)
W
wizardforcel 已提交
2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
```

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

The output size is H, for any input size. The number of output features is equal to the number of input planes.

| Parameters: | **output_size** – the target output size H |
| --- | --- |

Examples

```py
>>> # target output size of 5
>>> m = nn.AdaptiveAvgPool1d(5)
>>> input = torch.randn(1, 64, 8)
>>> output = m(input)

```

### AdaptiveAvgPool2d

```py
W
wizardforcel 已提交
2336
class torch.nn.AdaptiveAvgPool2d(output_size)
W
wizardforcel 已提交
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
```

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

The output is of size H x W, for any input size. The number of output features is equal to the number of input planes.

| Parameters: | **output_size** – the target output size of the image of the form H x W. Can be a tuple (H, W) or a single H for a square image H x H H and W can be either a `int`, or `None` which means the size will be the same as that of the input. |
| --- | --- |

Examples

```py
>>> # target output size of 5x7
>>> m = nn.AdaptiveAvgPool2d((5,7))
>>> input = torch.randn(1, 64, 8, 9)
>>> output = m(input)
>>> # target output size of 7x7 (square)
>>> m = nn.AdaptiveAvgPool2d(7)
>>> input = torch.randn(1, 64, 10, 9)
>>> output = m(input)
>>> # target output size of 10x7
>>> m = nn.AdaptiveMaxPool2d((None, 7))
>>> input = torch.randn(1, 64, 10, 9)
>>> output = m(input)

```

### AdaptiveAvgPool3d

```py
W
wizardforcel 已提交
2367
class torch.nn.AdaptiveAvgPool3d(output_size)
W
wizardforcel 已提交
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399
```

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

The output is of size D x H x W, for any input size. The number of output features is equal to the number of input planes.

| Parameters: | **output_size** – the target output size of the form D x H x W. Can be a tuple (D, H, W) or a single number D for a cube D x D x D D, H and W can be either a `int`, or `None` which means the size will be the same as that of the input. |
| --- | --- |

Examples

```py
>>> # target output size of 5x7x9
>>> m = nn.AdaptiveAvgPool3d((5,7,9))
>>> input = torch.randn(1, 64, 8, 9, 10)
>>> output = m(input)
>>> # target output size of 7x7x7 (cube)
>>> m = nn.AdaptiveAvgPool3d(7)
>>> input = torch.randn(1, 64, 10, 9, 8)
>>> output = m(input)
>>> # target output size of 7x9x8
>>> m = nn.AdaptiveMaxPool3d((7, None, None))
>>> input = torch.randn(1, 64, 10, 9, 8)
>>> output = m(input)

```

## Padding layers

### ReflectionPad1d

```py
W
wizardforcel 已提交
2400
class torch.nn.ReflectionPad1d(padding)
W
wizardforcel 已提交
2401 2402 2403 2404
```

Pads the input tensor using the reflection of the input boundary.

W
wizardforcel 已提交
2405
For `N`-dimensional padding, use [`torch.nn.functional.pad()`](#torch.nn.functional.pad "torch.nn.functional.pad").
W
wizardforcel 已提交
2406

W
wizardforcel 已提交
2407
| Parameters: | **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – the size of the padding. If is `int`, uses the same padding in all boundaries. If a 2-`tuple`, uses (![](img/08b2cac9ee37dde4cec3d372ebbfa0bd.jpg), ![](img/9f56071a00e2baa50d7fa9bde997852d.jpg)) |
W
wizardforcel 已提交
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441
| --- | --- |

```py
Shape:
```

*   Input: ![](img/964aa6df63e83f4468aa090441f01972.jpg)
*   Output: ![](img/ac2661719f40fc422e2b1590a1e7b4a4.jpg) where ![](img/e2294a717e6d12035072d23c45273863.jpg)

Examples:

```py
>>> m = nn.ReflectionPad1d(2)
>>> input = torch.arange(8, dtype=torch.float).reshape(1, 2, 4)
>>> input
tensor([[[0., 1., 2., 3.],
 [4., 5., 6., 7.]]])
>>> m(input)
tensor([[[2., 1., 0., 1., 2., 3., 2., 1.],
 [6., 5., 4., 5., 6., 7., 6., 5.]]])
>>> m(input)
tensor([[[2., 1., 0., 1., 2., 3., 2., 1.],
 [6., 5., 4., 5., 6., 7., 6., 5.]]])
>>> # using different paddings for different sides
>>> m = nn.ReflectionPad1d((3, 1))
>>> m(input)
tensor([[[3., 2., 1., 0., 1., 2., 3., 2.],
 [7., 6., 5., 4., 5., 6., 7., 6.]]])

```

### ReflectionPad2d

```py
W
wizardforcel 已提交
2442
class torch.nn.ReflectionPad2d(padding)
W
wizardforcel 已提交
2443 2444 2445 2446
```

Pads the input tensor using the reflection of the input boundary.

W
wizardforcel 已提交
2447
For `N`-dimensional padding, use [`torch.nn.functional.pad()`](#torch.nn.functional.pad "torch.nn.functional.pad").
W
wizardforcel 已提交
2448

W
wizardforcel 已提交
2449
| Parameters: | **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – the size of the padding. If is `int`, uses the same padding in all boundaries. If a 4-`tuple`, uses (![](img/08b2cac9ee37dde4cec3d372ebbfa0bd.jpg), ![](img/9f56071a00e2baa50d7fa9bde997852d.jpg), ![](img/65f6ce26141c225acd502a7bef164f66.jpg), ![](img/9a98061e27ba6ed06e846767b9c77c3a.jpg)) |
W
wizardforcel 已提交
2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
| --- | --- |

```py
Shape:
```

*   Input: ![](img/ff71b16eb10237262566c6907acaaf1f.jpg)

*   Output: ![](img/a0ef05f779873fc4dcbf020b1ea14754.jpg) where

    ![](img/75aa7c4a6c84e0ccb8aa91592cf6a077.jpg) ![](img/e2294a717e6d12035072d23c45273863.jpg)

Examples:

```py
>>> m = nn.ReflectionPad2d(2)
>>> input = torch.arange(9, dtype=torch.float).reshape(1, 1, 3, 3)
>>> input
tensor([[[[0., 1., 2.],
 [3., 4., 5.],
 [6., 7., 8.]]]])
>>> m(input)
tensor([[[[8., 7., 6., 7., 8., 7., 6.],
 [5., 4., 3., 4., 5., 4., 3.],
 [2., 1., 0., 1., 2., 1., 0.],
 [5., 4., 3., 4., 5., 4., 3.],
 [8., 7., 6., 7., 8., 7., 6.],
 [5., 4., 3., 4., 5., 4., 3.],
 [2., 1., 0., 1., 2., 1., 0.]]]])
>>> # using different paddings for different sides
>>> m = nn.ReflectionPad2d((1, 1, 2, 0))
>>> m(input)
tensor([[[[7., 6., 7., 8., 7.],
 [4., 3., 4., 5., 4.],
 [1., 0., 1., 2., 1.],
 [4., 3., 4., 5., 4.],
 [7., 6., 7., 8., 7.]]]])

```

### ReplicationPad1d

```py
W
wizardforcel 已提交
2493
class torch.nn.ReplicationPad1d(padding)
W
wizardforcel 已提交
2494 2495 2496 2497
```

Pads the input tensor using replication of the input boundary.

W
wizardforcel 已提交
2498
For `N`-dimensional padding, use [`torch.nn.functional.pad()`](#torch.nn.functional.pad "torch.nn.functional.pad").
W
wizardforcel 已提交
2499

W
wizardforcel 已提交
2500
| Parameters: | **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – the size of the padding. If is `int`, uses the same padding in all boundaries. If a 2-`tuple`, uses (![](img/08b2cac9ee37dde4cec3d372ebbfa0bd.jpg), ![](img/9f56071a00e2baa50d7fa9bde997852d.jpg)) |
W
wizardforcel 已提交
2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
| --- | --- |

```py
Shape:
```

*   Input: ![](img/964aa6df63e83f4468aa090441f01972.jpg)
*   Output: ![](img/ac2661719f40fc422e2b1590a1e7b4a4.jpg) where ![](img/e2294a717e6d12035072d23c45273863.jpg)

Examples:

```py
>>> m = nn.ReplicationPad1d(2)
>>> input = torch.arange(8, dtype=torch.float).reshape(1, 2, 4)
>>> input
tensor([[[0., 1., 2., 3.],
 [4., 5., 6., 7.]]])
>>> m(input)
tensor([[[0., 0., 0., 1., 2., 3., 3., 3.],
 [4., 4., 4., 5., 6., 7., 7., 7.]]])
>>> # using different paddings for different sides
>>> m = nn.ReplicationPad1d((3, 1))
>>> m(input)
tensor([[[0., 0., 0., 0., 1., 2., 3., 3.],
 [4., 4., 4., 4., 5., 6., 7., 7.]]])

```

### ReplicationPad2d

```py
W
wizardforcel 已提交
2532
class torch.nn.ReplicationPad2d(padding)
W
wizardforcel 已提交
2533 2534 2535 2536
```

Pads the input tensor using replication of the input boundary.

W
wizardforcel 已提交
2537
For `N`-dimensional padding, use [`torch.nn.functional.pad()`](#torch.nn.functional.pad "torch.nn.functional.pad").
W
wizardforcel 已提交
2538

W
wizardforcel 已提交
2539
| Parameters: | **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – the size of the padding. If is `int`, uses the same padding in all boundaries. If a 4-`tuple`, uses (![](img/08b2cac9ee37dde4cec3d372ebbfa0bd.jpg), ![](img/9f56071a00e2baa50d7fa9bde997852d.jpg), ![](img/65f6ce26141c225acd502a7bef164f66.jpg), ![](img/9a98061e27ba6ed06e846767b9c77c3a.jpg)) |
W
wizardforcel 已提交
2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579
| --- | --- |

```py
Shape:
```

*   Input: ![](img/ff71b16eb10237262566c6907acaaf1f.jpg)
*   Output: ![](img/a0ef05f779873fc4dcbf020b1ea14754.jpg) where ![](img/75aa7c4a6c84e0ccb8aa91592cf6a077.jpg) ![](img/e2294a717e6d12035072d23c45273863.jpg)

Examples:

```py
>>> m = nn.ReplicationPad2d(2)
>>> input = torch.arange(9, dtype=torch.float).reshape(1, 1, 3, 3)
>>> input
tensor([[[[0., 1., 2.],
 [3., 4., 5.],
 [6., 7., 8.]]]])
>>> m(input)
tensor([[[[0., 0., 0., 1., 2., 2., 2.],
 [0., 0., 0., 1., 2., 2., 2.],
 [0., 0., 0., 1., 2., 2., 2.],
 [3., 3., 3., 4., 5., 5., 5.],
 [6., 6., 6., 7., 8., 8., 8.],
 [6., 6., 6., 7., 8., 8., 8.],
 [6., 6., 6., 7., 8., 8., 8.]]]])
>>> # using different paddings for different sides
>>> m = nn.ReplicationPad2d((1, 1, 2, 0))
>>> m(input)
tensor([[[[0., 0., 1., 2., 2.],
 [0., 0., 1., 2., 2.],
 [0., 0., 1., 2., 2.],
 [3., 3., 4., 5., 5.],
 [6., 6., 7., 8., 8.]]]])

```

### ReplicationPad3d

```py
W
wizardforcel 已提交
2580
class torch.nn.ReplicationPad3d(padding)
W
wizardforcel 已提交
2581 2582 2583 2584
```

Pads the input tensor using replication of the input boundary.

W
wizardforcel 已提交
2585
For `N`-dimensional padding, use [`torch.nn.functional.pad()`](#torch.nn.functional.pad "torch.nn.functional.pad").
W
wizardforcel 已提交
2586

W
wizardforcel 已提交
2587
| Parameters: | **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – the size of the padding. If is `int`, uses the same padding in all boundaries. If a 6-`tuple`, uses (![](img/08b2cac9ee37dde4cec3d372ebbfa0bd.jpg), ![](img/9f56071a00e2baa50d7fa9bde997852d.jpg), ![](img/65f6ce26141c225acd502a7bef164f66.jpg), ![](img/9a98061e27ba6ed06e846767b9c77c3a.jpg), ![](img/bffb266183e8fa640240e16a45076c34.jpg), ![](img/9138ac0ee6f6e96dfe795ead91ec0003.jpg)) |
W
wizardforcel 已提交
2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
| --- | --- |

```py
Shape:
```

*   Input: ![](img/c187d190013d0785320e3412fe8cd669.jpg)
*   Output: ![](img/41ca4c8d4c65c979d2d643c6f62ea280.jpg) where ![](img/006114d9c80210ede5da92f2f3a44bb7.jpg) ![](img/75aa7c4a6c84e0ccb8aa91592cf6a077.jpg) ![](img/e2294a717e6d12035072d23c45273863.jpg)

Examples:

```py
>>> m = nn.ReplicationPad3d(3)
>>> input = torch.randn(16, 3, 8, 320, 480)
>>> output = m(input)
>>> # using different paddings for different sides
>>> m = nn.ReplicationPad3d((3, 3, 6, 6, 1, 1))
>>> output = m(input)

```

### ZeroPad2d

```py
W
wizardforcel 已提交
2612
class torch.nn.ZeroPad2d(padding)
W
wizardforcel 已提交
2613 2614 2615 2616
```

Pads the input tensor boundaries with zero.

W
wizardforcel 已提交
2617
For `N`-dimensional padding, use [`torch.nn.functional.pad()`](#torch.nn.functional.pad "torch.nn.functional.pad").
W
wizardforcel 已提交
2618

W
wizardforcel 已提交
2619
| Parameters: | **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – the size of the padding. If is `int`, uses the same padding in all boundaries. If a 4-`tuple`, uses (![](img/08b2cac9ee37dde4cec3d372ebbfa0bd.jpg), ![](img/9f56071a00e2baa50d7fa9bde997852d.jpg), ![](img/65f6ce26141c225acd502a7bef164f66.jpg), ![](img/9a98061e27ba6ed06e846767b9c77c3a.jpg)) |
W
wizardforcel 已提交
2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659
| --- | --- |

```py
Shape:
```

*   Input: ![](img/ff71b16eb10237262566c6907acaaf1f.jpg)
*   Output: ![](img/a0ef05f779873fc4dcbf020b1ea14754.jpg) where ![](img/75aa7c4a6c84e0ccb8aa91592cf6a077.jpg) ![](img/e2294a717e6d12035072d23c45273863.jpg)

Examples:

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

```

### ConstantPad1d

```py
W
wizardforcel 已提交
2660
class torch.nn.ConstantPad1d(padding, value)
W
wizardforcel 已提交
2661 2662 2663 2664
```

Pads the input tensor boundaries with a constant value.

W
wizardforcel 已提交
2665
For `N`-dimensional padding, use [`torch.nn.functional.pad()`](#torch.nn.functional.pad "torch.nn.functional.pad").
W
wizardforcel 已提交
2666

W
wizardforcel 已提交
2667
| Parameters: | **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – the size of the padding. If is `int`, uses the same padding in both boundaries. If a 2-`tuple`, uses (![](img/08b2cac9ee37dde4cec3d372ebbfa0bd.jpg), ![](img/9f56071a00e2baa50d7fa9bde997852d.jpg)) |
W
wizardforcel 已提交
2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
| --- | --- |

```py
Shape:
```

*   Input: ![](img/964aa6df63e83f4468aa090441f01972.jpg)
*   Output: ![](img/ac2661719f40fc422e2b1590a1e7b4a4.jpg) where ![](img/e2294a717e6d12035072d23c45273863.jpg)

Examples:

```py
>>> m = nn.ConstantPad1d(2, 3.5)
>>> input = torch.randn(1, 2, 4)
>>> input
tensor([[[-1.0491, -0.7152, -0.0749,  0.8530],
 [-1.3287,  1.8966,  0.1466, -0.2771]]])
>>> m(input)
tensor([[[ 3.5000,  3.5000, -1.0491, -0.7152, -0.0749,  0.8530,  3.5000,
 3.5000],
 [ 3.5000,  3.5000, -1.3287,  1.8966,  0.1466, -0.2771,  3.5000,
 3.5000]]])
>>> m = nn.ConstantPad1d(2, 3.5)
>>> input = torch.randn(1, 2, 3)
>>> input
tensor([[[ 1.6616,  1.4523, -1.1255],
 [-3.6372,  0.1182, -1.8652]]])
>>> m(input)
tensor([[[ 3.5000,  3.5000,  1.6616,  1.4523, -1.1255,  3.5000,  3.5000],
 [ 3.5000,  3.5000, -3.6372,  0.1182, -1.8652,  3.5000,  3.5000]]])
>>> # using different paddings for different sides
>>> m = nn.ConstantPad1d((3, 1), 3.5)
>>> m(input)
tensor([[[ 3.5000,  3.5000,  3.5000,  1.6616,  1.4523, -1.1255,  3.5000],
 [ 3.5000,  3.5000,  3.5000, -3.6372,  0.1182, -1.8652,  3.5000]]])

```

### ConstantPad2d

```py
W
wizardforcel 已提交
2709
class torch.nn.ConstantPad2d(padding, value)
W
wizardforcel 已提交
2710 2711 2712 2713
```

Pads the input tensor boundaries with a constant value.

W
wizardforcel 已提交
2714
For `N`-dimensional padding, use [`torch.nn.functional.pad()`](#torch.nn.functional.pad "torch.nn.functional.pad").
W
wizardforcel 已提交
2715

W
wizardforcel 已提交
2716
| Parameters: | **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – the size of the padding. If is `int`, uses the same padding in all boundaries. If a 4-`tuple`, uses (![](img/08b2cac9ee37dde4cec3d372ebbfa0bd.jpg), ![](img/9f56071a00e2baa50d7fa9bde997852d.jpg), ![](img/65f6ce26141c225acd502a7bef164f66.jpg), ![](img/9a98061e27ba6ed06e846767b9c77c3a.jpg)) |
W
wizardforcel 已提交
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761
| --- | --- |

```py
Shape:
```

*   Input: ![](img/ff71b16eb10237262566c6907acaaf1f.jpg)
*   Output: ![](img/a0ef05f779873fc4dcbf020b1ea14754.jpg) where ![](img/75aa7c4a6c84e0ccb8aa91592cf6a077.jpg) ![](img/e2294a717e6d12035072d23c45273863.jpg)

Examples:

```py
>>> m = nn.ConstantPad2d(2, 3.5)
>>> input = torch.randn(1, 2, 2)
>>> input
tensor([[[ 1.6585,  0.4320],
 [-0.8701, -0.4649]]])
>>> m(input)
tensor([[[ 3.5000,  3.5000,  3.5000,  3.5000,  3.5000,  3.5000],
 [ 3.5000,  3.5000,  3.5000,  3.5000,  3.5000,  3.5000],
 [ 3.5000,  3.5000,  1.6585,  0.4320,  3.5000,  3.5000],
 [ 3.5000,  3.5000, -0.8701, -0.4649,  3.5000,  3.5000],
 [ 3.5000,  3.5000,  3.5000,  3.5000,  3.5000,  3.5000],
 [ 3.5000,  3.5000,  3.5000,  3.5000,  3.5000,  3.5000]]])
>>> m(input)
tensor([[[ 3.5000,  3.5000,  3.5000,  3.5000,  3.5000,  3.5000],
 [ 3.5000,  3.5000,  3.5000,  3.5000,  3.5000,  3.5000],
 [ 3.5000,  3.5000,  1.6585,  0.4320,  3.5000,  3.5000],
 [ 3.5000,  3.5000, -0.8701, -0.4649,  3.5000,  3.5000],
 [ 3.5000,  3.5000,  3.5000,  3.5000,  3.5000,  3.5000],
 [ 3.5000,  3.5000,  3.5000,  3.5000,  3.5000,  3.5000]]])
>>> # using different paddings for different sides
>>> m = nn.ConstantPad2d((3, 0, 2, 1), 3.5)
>>> m(input)
tensor([[[ 3.5000,  3.5000,  3.5000,  3.5000,  3.5000],
 [ 3.5000,  3.5000,  3.5000,  3.5000,  3.5000],
 [ 3.5000,  3.5000,  3.5000,  1.6585,  0.4320],
 [ 3.5000,  3.5000,  3.5000, -0.8701, -0.4649],
 [ 3.5000,  3.5000,  3.5000,  3.5000,  3.5000]]])

```

### ConstantPad3d

```py
W
wizardforcel 已提交
2762
class torch.nn.ConstantPad3d(padding, value)
W
wizardforcel 已提交
2763 2764 2765 2766
```

Pads the input tensor boundaries with a constant value.

W
wizardforcel 已提交
2767
For `N`-dimensional padding, use [`torch.nn.functional.pad()`](#torch.nn.functional.pad "torch.nn.functional.pad").
W
wizardforcel 已提交
2768

W
wizardforcel 已提交
2769
| Parameters: | **padding** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ [_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")) – the size of the padding. If is `int`, uses the same padding in all boundaries. If a 6-`tuple`, uses (![](img/08b2cac9ee37dde4cec3d372ebbfa0bd.jpg), ![](img/9f56071a00e2baa50d7fa9bde997852d.jpg), ![](img/65f6ce26141c225acd502a7bef164f66.jpg), ![](img/9a98061e27ba6ed06e846767b9c77c3a.jpg), ![](img/bffb266183e8fa640240e16a45076c34.jpg), ![](img/9138ac0ee6f6e96dfe795ead91ec0003.jpg)) |
W
wizardforcel 已提交
2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795
| --- | --- |

```py
Shape:
```

*   Input: ![](img/c187d190013d0785320e3412fe8cd669.jpg)
*   Output: ![](img/41ca4c8d4c65c979d2d643c6f62ea280.jpg) where ![](img/006114d9c80210ede5da92f2f3a44bb7.jpg) ![](img/75aa7c4a6c84e0ccb8aa91592cf6a077.jpg) ![](img/e2294a717e6d12035072d23c45273863.jpg)

Examples:

```py
>>> m = nn.ConstantPad3d(3, 3.5)
>>> input = torch.randn(16, 3, 10, 20, 30)
>>> output = m(input)
>>> # using different paddings for different sides
>>> m = nn.ConstantPad3d((3, 3, 6, 6, 0, 1), 3.5)
>>> output = m(input)

```

## Non-linear activations (weighted sum, nonlinearity)

### ELU

```py
W
wizardforcel 已提交
2796
class torch.nn.ELU(alpha=1.0, inplace=False)
W
wizardforcel 已提交
2797 2798 2799 2800 2801 2802
```

Applies the element-wise function:

![](img/1285687f031aec0751f4e0481f97b6b0.jpg)

W
wizardforcel 已提交
2803
Parameters: 
W
wizardforcel 已提交
2804 2805 2806 2807

*   **alpha** – the ![](img/82005cc2e0087e2a52c7e43df4a19a00.jpg) value for the ELU formulation. Default: 1.0
*   **inplace** – can optionally do the operation in-place. Default: `False`

W
wizardforcel 已提交
2808

W
wizardforcel 已提交
2809 2810 2811 2812 2813

```py
Shape:
```

W
wizardforcel 已提交
2814
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

![https://pytorch.org/docs/stable/_images//ELU.png](img/5d789140032850b13d5c00493bf62412.jpg)

Examples:

```py
>>> m = nn.ELU()
>>> input = torch.randn(2)
>>> output = m(input)

```

### Hardshrink

```py
W
wizardforcel 已提交
2831
class torch.nn.Hardshrink(lambd=0.5)
W
wizardforcel 已提交
2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844
```

Applies the hard shrinkage function element-wise:

![](img/f934a1a7fa1553c38403f2e010708ed9.jpg)

| Parameters: | **lambd** – the ![](img/5e8df2ba7e47a784c714d176ed8bbb7a.jpg) value for the Hardshrink formulation. Default: 0.5 |
| --- | --- |

```py
Shape:
```

W
wizardforcel 已提交
2845
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

![https://pytorch.org/docs/stable/_images//Hardshrink.png](img/45889773f687ed0d33a3ef9b66b0da32.jpg)

Examples:

```py
>>> m = nn.Hardshrink()
>>> input = torch.randn(2)
>>> output = m(input)

```

### Hardtanh

```py
W
wizardforcel 已提交
2862
class torch.nn.Hardtanh(min_val=-1.0, max_val=1.0, inplace=False, min_value=None, max_value=None)
W
wizardforcel 已提交
2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874
```

Applies the HardTanh function element-wise

HardTanh is defined as:

![](img/988cd664634d88b1e654ea5e8fe27d9a.jpg)

The range of the linear region ![](img/f30fa7744d61427a11bf0e75b1557a16.jpg) can be adjusted using `min_val` and `max_val`.

![https://pytorch.org/docs/stable/_images//Hardtanh.png](img/b22ab176e5aca7ca2b17e84fe525620e.jpg)

W
wizardforcel 已提交
2875
Parameters: 
W
wizardforcel 已提交
2876 2877 2878 2879 2880

*   **min_val** – minimum value of the linear region range. Default: -1
*   **max_val** – maximum value of the linear region range. Default: 1
*   **inplace** – can optionally do the operation in-place. Default: `False`

W
wizardforcel 已提交
2881

W
wizardforcel 已提交
2882 2883 2884 2885 2886 2887 2888

Keyword arguments `min_value` and `max_value` have been deprecated in favor of `min_val` and `max_val`.

```py
Shape:
```

W
wizardforcel 已提交
2889
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

Examples:

```py
>>> m = nn.Hardtanh(-2, 2)
>>> input = torch.randn(2)
>>> output = m(input)

```

### LeakyReLU

```py
W
wizardforcel 已提交
2904
class torch.nn.LeakyReLU(negative_slope=0.01, inplace=False)
W
wizardforcel 已提交
2905 2906 2907 2908 2909 2910 2911 2912 2913 2914
```

Applies the element-wise function:

![](img/92ce1c3da3211f30ef5273403da71c7a.jpg)

or

![](img/377c237cda65f4c68e3138efcc2bfef4.jpg)

W
wizardforcel 已提交
2915
Parameters: 
W
wizardforcel 已提交
2916 2917 2918 2919

*   **negative_slope** – Controls the angle of the negative slope. Default: 1e-2
*   **inplace** – can optionally do the operation in-place. Default: `False`

W
wizardforcel 已提交
2920

W
wizardforcel 已提交
2921 2922 2923 2924 2925

```py
Shape:
```

W
wizardforcel 已提交
2926
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

![https://pytorch.org/docs/stable/_images//LeakyReLU.png](img/7df3c1e498d7d00e9e32ce7716e15fc3.jpg)

Examples:

```py
>>> m = nn.LeakyReLU(0.1)
>>> input = torch.randn(2)
>>> output = m(input)

```

### LogSigmoid

```py
W
wizardforcel 已提交
2943
class torch.nn.LogSigmoid
W
wizardforcel 已提交
2944 2945 2946 2947 2948 2949 2950 2951
```

Applies the element-wise function:

```py
Shape:
```

W
wizardforcel 已提交
2952
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

![https://pytorch.org/docs/stable/_images//LogSigmoid.png](img/f03b653b702dcd536fbb404c6461b399.jpg)

Examples:

```py
>>> m = nn.LogSigmoid()
>>> input = torch.randn(2)
>>> output = m(input)

```

### PReLU

```py
W
wizardforcel 已提交
2969
class torch.nn.PReLU(num_parameters=1, init=0.25)
W
wizardforcel 已提交
2970 2971 2972 2973 2974 2975 2976 2977 2978 2979
```

Applies the element-wise function:

![](img/96fb709d31ba330ca192080e660d4cf1.jpg)

or

![](img/f460dc15bedfa96b8a320033b3f4fd6f.jpg)

W
wizardforcel 已提交
2980
Here ![](img/070b1af5eca3a5c5d72884b536090f17.jpg) is a learnable parameter. When called without arguments, `nn.PReLU()` uses a single parameter ![](img/070b1af5eca3a5c5d72884b536090f17.jpg) across all input channels. If called with `nn.PReLU(nChannels)`, a separate ![](img/070b1af5eca3a5c5d72884b536090f17.jpg) is used for each input channel.
W
wizardforcel 已提交
2981 2982 2983 2984 2985 2986 2987 2988 2989

Note

weight decay should not be used when learning ![](img/070b1af5eca3a5c5d72884b536090f17.jpg) for good performance.

Note

Channel dim is the 2nd dim of input. When input has dims &lt; 2, then there is no channel dim and the number of channels = 1.

W
wizardforcel 已提交
2990
Parameters: 
W
wizardforcel 已提交
2991 2992 2993 2994

*   **num_parameters** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – number of ![](img/070b1af5eca3a5c5d72884b536090f17.jpg) to learn. Although it takes an int as input, there is only two values are legitimate: 1, or the number of channels at input. Default: 1
*   **init** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")) – the initial value of ![](img/070b1af5eca3a5c5d72884b536090f17.jpg). Default: 0.25

W
wizardforcel 已提交
2995

W
wizardforcel 已提交
2996 2997 2998 2999 3000

```py
Shape:
```

W
wizardforcel 已提交
3001
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
3002 3003
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

W
wizardforcel 已提交
3004
| Variables: | **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – the learnable weights of shape (attr:`num_parameters`). The attr:`dtype` is default to |
W
wizardforcel 已提交
3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020
| --- | --- |

![https://pytorch.org/docs/stable/_images//PReLU.png](img/59baba7257ac05b747455a25a3457baf.jpg)

Examples:

```py
>>> m = nn.PReLU()
>>> input = torch.randn(2)
>>> output = m(input)

```

### ReLU

```py
W
wizardforcel 已提交
3021
class torch.nn.ReLU(inplace=False)
W
wizardforcel 已提交
3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034
```

Applies the rectified linear unit function element-wise ![](img/f859c48107afb47986b3297459048c80.jpg)

![https://pytorch.org/docs/stable/_images//ReLU.png](img/6bfe295d2f51e4e33648ffb4273723a6.jpg)

| Parameters: | **inplace** – can optionally do the operation in-place. Default: `False` |
| --- | --- |

```py
Shape:
```

W
wizardforcel 已提交
3035
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

Examples:

```py
>>> m = nn.ReLU()
>>> input = torch.randn(2)
>>> output = m(input)

```

### ReLU6

```py
W
wizardforcel 已提交
3050
class torch.nn.ReLU6(inplace=False)
W
wizardforcel 已提交
3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063
```

Applies the element-wise function:

![](img/38c45c0cb00fa6f9a372816012b26b01.jpg)

| Parameters: | **inplace** – can optionally do the operation in-place. Default: `False` |
| --- | --- |

```py
Shape:
```

W
wizardforcel 已提交
3064
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

![https://pytorch.org/docs/stable/_images//ReLU6.png](img/3a82f9216f0db7d59f6c0f1c169156b0.jpg)

Examples:

```py
>>> m = nn.ReLU6()
>>> input = torch.randn(2)
>>> output = m(input)

```

### RReLU

```py
W
wizardforcel 已提交
3081
class torch.nn.RReLU(lower=0.125, upper=0.3333333333333333, inplace=False)
W
wizardforcel 已提交
3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095
```

Applies the randomized leaky rectified liner unit function, element-wise, as described in the paper:

[Empirical Evaluation of Rectified Activations in Convolutional Network](https://arxiv.org/abs/1505.00853).

The function is defined as:

![](img/69aa6828f2f0bcd0ee1e173223ff4640.jpg)

where ![](img/070b1af5eca3a5c5d72884b536090f17.jpg) is randomly sampled from uniform distribution ![](img/7323b93ed925c9e5b0ce10c8a6c99daf.jpg).

> See: [https://arxiv.org/pdf/1505.00853.pdf](https://arxiv.org/pdf/1505.00853.pdf)

W
wizardforcel 已提交
3096
Parameters: 
W
wizardforcel 已提交
3097 3098 3099 3100 3101

*   **lower** – lower bound of the uniform distribution. Default: ![](img/444fc0427eb64f0bd2c9c16edf680d4f.jpg)
*   **upper** – upper bound of the uniform distribution. Default: ![](img/a90c89c913a1fe1e9462d60d8668936b.jpg)
*   **inplace** – can optionally do the operation in-place. Default: `False`

W
wizardforcel 已提交
3102

W
wizardforcel 已提交
3103 3104 3105 3106 3107

```py
Shape:
```

W
wizardforcel 已提交
3108
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

Examples:

```py
>>> m = nn.RReLU(0.1, 0.3)
>>> input = torch.randn(2)
>>> output = m(input)

```

### SELU

```py
W
wizardforcel 已提交
3123
class torch.nn.SELU(inplace=False)
W
wizardforcel 已提交
3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142
```

Applied element-wise, as:

![](img/c6753a504d14886a424af779f5906dc5.jpg)

with ![](img/e97a0b3de4bafa3464e17a8d8f66fd9d.jpg) and ![](img/aa01199f9b814d719de1e728e4a44ac3.jpg).

![https://pytorch.org/docs/stable/_images//SELU.png](img/10123138310ae40f4a78f55cefe37008.jpg)

More details can be found in the paper [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515) .

| Parameters: | **inplace** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – can optionally do the operation in-place. Default: `False` |
| --- | --- |

```py
Shape:
```

W
wizardforcel 已提交
3143
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

Examples:

```py
>>> m = nn.SELU()
>>> input = torch.randn(2)
>>> output = m(input)

```

### CELU

```py
W
wizardforcel 已提交
3158
class torch.nn.CELU(alpha=1.0, inplace=False)
W
wizardforcel 已提交
3159 3160 3161 3162 3163 3164 3165 3166
```

Applies the element-wise function:

![](img/86d69b42683362b7781f1a5809c0d0d1.jpg)

More details can be found in the paper [Continuously Differentiable Exponential Linear Units](https://arxiv.org/abs/1704.07483) .

W
wizardforcel 已提交
3167
Parameters: 
W
wizardforcel 已提交
3168 3169 3170 3171

*   **alpha** – the ![](img/82005cc2e0087e2a52c7e43df4a19a00.jpg) value for the CELU formulation. Default: 1.0
*   **inplace** – can optionally do the operation in-place. Default: `False`

W
wizardforcel 已提交
3172

W
wizardforcel 已提交
3173 3174 3175 3176 3177

```py
Shape:
```

W
wizardforcel 已提交
3178
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

![https://pytorch.org/docs/stable/_images//CELU.png](img/8d5fd8f893fb491c170f9a38af6edef9.jpg)

Examples:

```py
>>> m = nn.CELU()
>>> input = torch.randn(2)
>>> output = m(input)

```

### Sigmoid

```py
W
wizardforcel 已提交
3195
class torch.nn.Sigmoid
W
wizardforcel 已提交
3196 3197 3198 3199 3200 3201 3202 3203 3204 3205
```

Applies the element-wise function:

![](img/8bf3a718397550598124548beb8c6b23.jpg)

```py
Shape:
```

W
wizardforcel 已提交
3206
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

![https://pytorch.org/docs/stable/_images//Sigmoid.png](img/961caeb46e669eb70392afd515f9bde7.jpg)

Examples:

```py
>>> m = nn.Sigmoid()
>>> input = torch.randn(2)
>>> output = m(input)

```

### Softplus

```py
W
wizardforcel 已提交
3223
class torch.nn.Softplus(beta=1, threshold=20)
W
wizardforcel 已提交
3224 3225 3226 3227 3228 3229 3230 3231 3232 3233
```

Applies the element-wise function:

![](img/a0855ca512a1ba09192648efd45082ad.jpg)

SoftPlus is a smooth approximation to the ReLU function and can be used to constrain the output of a machine to always be positive.

For numerical stability the implementation reverts to the linear function for inputs above a certain value.

W
wizardforcel 已提交
3234
Parameters: 
W
wizardforcel 已提交
3235 3236 3237 3238

*   **beta** – the ![](img/50705df736e9a7919e768cf8c4e4f794.jpg) value for the Softplus formulation. Default: 1
*   **threshold** – values above this revert to a linear function. Default: 20

W
wizardforcel 已提交
3239

W
wizardforcel 已提交
3240 3241 3242 3243 3244

```py
Shape:
```

W
wizardforcel 已提交
3245
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

![https://pytorch.org/docs/stable/_images//Softplus.png](img/af06304134e1f56d7abc15570fa5adb9.jpg)

Examples:

```py
>>> m = nn.Softplus()
>>> input = torch.randn(2)
>>> output = m(input)

```

### Softshrink

```py
W
wizardforcel 已提交
3262
class torch.nn.Softshrink(lambd=0.5)
W
wizardforcel 已提交
3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
```

Applies the soft shrinkage function elementwise:

![](img/5baf58b3007cf434725f41bf2dfae2ce.jpg)

| Parameters: | **lambd** – the ![](img/5e8df2ba7e47a784c714d176ed8bbb7a.jpg) value for the Softshrink formulation. Default: 0.5 |
| --- | --- |

```py
Shape:
```

W
wizardforcel 已提交
3276
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

![https://pytorch.org/docs/stable/_images//Softshrink.png](img/cec198ab680657d41c1d2ac2176e5664.jpg)

Examples:

```py
>>> m = nn.Softshrink()
>>> input = torch.randn(2)
>>> output = m(input)

```

### Softsign

```py
W
wizardforcel 已提交
3293
class torch.nn.Softsign
W
wizardforcel 已提交
3294 3295 3296 3297 3298 3299 3300 3301 3302 3303
```

Applies the element-wise function:

![](img/39ba3e3786920ceb12bc26b08b00de1c.jpg)

```py
Shape:
```

W
wizardforcel 已提交
3304
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

![https://pytorch.org/docs/stable/_images//Softsign.png](img/b92a09469ce9fc0abfbe8c9af4228391.jpg)

Examples:

```py
>>> m = nn.Softsign()
>>> input = torch.randn(2)
>>> output = m(input)

```

### Tanh

```py
W
wizardforcel 已提交
3321
class torch.nn.Tanh
W
wizardforcel 已提交
3322 3323 3324 3325 3326 3327 3328 3329 3330 3331
```

Applies the element-wise function:

![](img/e3f58d9a8cbc89b247dd8de1c28bf7ce.jpg)

```py
Shape:
```

W
wizardforcel 已提交
3332
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

![https://pytorch.org/docs/stable/_images//Tanh.png](img/5605304fc1fec06669e17cc872d47580.jpg)

Examples:

```py
>>> m = nn.Tanh()
>>> input = torch.randn(2)
>>> output = m(input)

```

### Tanhshrink

```py
W
wizardforcel 已提交
3349
class torch.nn.Tanhshrink
W
wizardforcel 已提交
3350 3351 3352 3353 3354 3355 3356 3357 3358 3359
```

Applies the element-wise function:

![](img/136fda10bacf7ae9068ca487ba861805.jpg)

```py
Shape:
```

W
wizardforcel 已提交
3360
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

![https://pytorch.org/docs/stable/_images//Tanhshrink.png](img/8aea39259742ccdb14701a8f3c351b56.jpg)

Examples:

```py
>>> m = nn.Tanhshrink()
>>> input = torch.randn(2)
>>> output = m(input)

```

### Threshold

```py
W
wizardforcel 已提交
3377
class torch.nn.Threshold(threshold, value, inplace=False)
W
wizardforcel 已提交
3378 3379 3380 3381 3382 3383 3384 3385
```

Thresholds each element of the input Tensor

Threshold is defined as:

![](img/3b32031caba73686c02a117e8e307c6f.jpg)

W
wizardforcel 已提交
3386
Parameters: 
W
wizardforcel 已提交
3387 3388 3389 3390 3391

*   **threshold** – The value to threshold at
*   **value** – The value to replace with
*   **inplace** – can optionally do the operation in-place. Default: `False`

W
wizardforcel 已提交
3392

W
wizardforcel 已提交
3393 3394 3395 3396 3397

```py
Shape:
```

W
wizardforcel 已提交
3398
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

Examples:

```py
>>> m = nn.Threshold(0.1, 20)
>>> input = torch.randn(2)
>>> output = m(input)

```

## Non-linear activations (other)

### Softmin

```py
W
wizardforcel 已提交
3415
class torch.nn.Softmin(dim=None)
W
wizardforcel 已提交
3416 3417
```

W
wizardforcel 已提交
3418
Applies the Softmin function to an n-dimensional input Tensor rescaling them so that the elements of the n-dimensional output Tensor lie in the range `(0, 1)` and sum to 1
W
wizardforcel 已提交
3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445

![](img/440f43280457a9287bbddf28553f8f70.jpg)

```py
Shape:
```

*   Input: any shape
*   Output: same as input

| Parameters: | **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). |
| --- | --- |
| Returns: | a Tensor of the same dimension and shape as the input, with values in the range [0, 1] |
| --- | --- |

Examples:

```py
>>> m = nn.Softmin()
>>> input = torch.randn(2, 3)
>>> output = m(input)

```

### Softmax

```py
W
wizardforcel 已提交
3446
class torch.nn.Softmax(dim=None)
W
wizardforcel 已提交
3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468
```

Applies the Softmax function to an n-dimensional input Tensor rescaling them so that the elements of the n-dimensional output Tensor lie in the range (0,1) and sum to 1

Softmax is defined as:

![](img/cbfd37534eccdda606d4f8494c31d2c0.jpg)

```py
Shape:
```

*   Input: any shape
*   Output: same as input

| Returns: | a Tensor of the same dimension and shape as the input with values in the range [0, 1] |
| --- | --- |
| Parameters: | **dim** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – A dimension along which Softmax will be computed (so every slice along dim will sum to 1). |
| --- | --- |

Note

W
wizardforcel 已提交
3469
This module doesn’t work directly with NLLLoss, which expects the Log to be computed between the Softmax and itself. Use `LogSoftmax` instead (it’s faster and has better numerical properties).
W
wizardforcel 已提交
3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482

Examples:

```py
>>> m = nn.Softmax()
>>> input = torch.randn(2, 3)
>>> output = m(input)

```

### Softmax2d

```py
W
wizardforcel 已提交
3483
class torch.nn.Softmax2d
W
wizardforcel 已提交
3484 3485 3486 3487
```

Applies SoftMax over features to each spatial location.

W
wizardforcel 已提交
3488
When given an image of `Channels x Height x Width`, it will apply `Softmax` to each location ![](img/b16a2a186bda385e5f0016f5fe5a5c36.jpg)
W
wizardforcel 已提交
3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512

```py
Shape:
```

*   Input: ![](img/23f8772594b27bd387be708fe9c085e1.jpg)
*   Output: ![](img/23f8772594b27bd387be708fe9c085e1.jpg) (same shape as input)

| Returns: | a Tensor of the same dimension and shape as the input with values in the range [0, 1] |
| --- | --- |

Examples:

```py
>>> m = nn.Softmax2d()
>>> # you softmax over the 2nd dimension
>>> input = torch.randn(2, 3, 12, 13)
>>> output = m(input)

```

### LogSoftmax

```py
W
wizardforcel 已提交
3513
class torch.nn.LogSoftmax(dim=None)
W
wizardforcel 已提交
3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543
```

Applies the ![](img/db163ba416e1349a426e6a137e082ae2.jpg) function to an n-dimensional input Tensor. The LogSoftmax formulation can be simplified as:

![](img/397c4cfa2f291306d481811192d2d5d9.jpg)

```py
Shape:
```

*   Input: any shape
*   Output: same as input

| Parameters: | **dim** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – A dimension along which Softmax will be computed (so every slice along dim will sum to 1). |
| --- | --- |
| Returns: | a Tensor of the same dimension and shape as the input with values in the range [-inf, 0) |
| --- | --- |

Examples:

```py
>>> m = nn.LogSoftmax()
>>> input = torch.randn(2, 3)
>>> output = m(input)

```

### AdaptiveLogSoftmaxWithLoss

```py
W
wizardforcel 已提交
3544
class torch.nn.AdaptiveLogSoftmaxWithLoss(in_features, n_classes, cutoffs, div_value=4.0, head_bias=False)
W
wizardforcel 已提交
3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556
```

Efficient softmax approximation as described in [Efficient softmax approximation for GPUs](https://arxiv.org/abs/1609.04309) by Edouard Grave, Armand Joulin, Moustapha Cissé, David Grangier, and Hervé Jégou.

Adaptive softmax is an approximate strategy for training models with large output spaces. It is most effective when the label distribution is highly imbalanced, for example in natural language modelling, where the word frequency distribution approximately follows the [Zipf’s law](https://en.wikipedia.org/wiki/Zipf%27s_law).

Adaptive softmax partitions the labels into several clusters, according to their frequency. These clusters may contain different number of targets each. Additionally, clusters containing less frequent labels assign lower dimensional embeddings to those labels, which speeds up the computation. For each minibatch, only clusters for which at least one target is present are evaluated.

The idea is that the clusters which are accessed frequently (like the first one, containing most frequent labels), should also be cheap to compute – that is, contain a small number of assigned labels.

We highly recommend taking a look at the original paper for more details.

W
wizardforcel 已提交
3557
*   `cutoffs` should be an ordered Sequence of integers sorted in the increasing order. It controls number of clusters and the partitioning of targets into clusters. For example setting `cutoffs = [10, 100, 1000]` means that first `10` targets will be assigned to the ‘head’ of the adaptive softmax, targets `11, 12, …, 100` will be assigned to the first cluster, and targets `101, 102, …, 1000` will be assigned to the second cluster, while targets `1001, 1002, …, n_classes - 1` will be assigned to the last, third cluster
W
wizardforcel 已提交
3558 3559 3560 3561 3562
*   `div_value` is used to compute the size of each additional cluster, which is given as ![](img/32071c42affaaf731df4e3398b16de10.jpg), where ![](img/5df73ea97de3a7712b50ce2fecfea1a7.jpg) is the cluster index (with clusters for less frequent words having larger indices, and indices starting from ![](img/a3ea24a1f2a3549d3e5b0cacf3ecb7c7.jpg)).
*   `head_bias` if set to True, adds a bias term to the ‘head’ of the adaptive softmax. See paper for details. Set to False in the official implementation.

Warning

W
wizardforcel 已提交
3563
Labels passed as inputs to this module should be sorted accoridng to their frequency. This means that the most frequent label should be represented by the index `0`, and the least frequent label should be represented by the index `n_classes - 1`.
W
wizardforcel 已提交
3564 3565 3566 3567 3568 3569 3570 3571 3572

Note

This module returns a `NamedTuple` with `output` and `loss` fields. See further documentation for details.

Note

To compute log-probabilities for all classes, the `log_prob` method can be used.

W
wizardforcel 已提交
3573
Parameters: 
W
wizardforcel 已提交
3574 3575 3576 3577 3578 3579

*   **in_features** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – Number of features in the input tensor
*   **n_classes** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – Number of classes in the dataset.
*   **cutoffs** (_Sequence_) – Cutoffs used to assign targets to their buckets.
*   **div_value** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – value used as an exponent to compute sizes of the clusters. Default: 4.0

W
wizardforcel 已提交
3580

W
wizardforcel 已提交
3581 3582 3583 3584 3585
| Returns: | 

*   **output** is a Tensor of size `N` containing computed target log probabilities for each example
*   **loss** is a Scalar representing the computed negative log likelihood loss

W
wizardforcel 已提交
3586

W
wizardforcel 已提交
3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599
| Return type: | `NamedTuple` with `output` and `loss` fields |
| --- | --- |

```py
Shape:
```

*   input: ![](img/768be7688f5f58f4766106ddb821b007.jpg)
*   target: ![](img/2a3e2b832e04fe8d66596083b23da518.jpg) where each value satisfies ![](img/fe1e80e9faca308456bc49d4e79013e0.jpg)
*   output: ![](img/2a3e2b832e04fe8d66596083b23da518.jpg)
*   loss: `Scalar`

```py
W
wizardforcel 已提交
3600
log_prob(input)
W
wizardforcel 已提交
3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617
```

Computes log probabilities for all ![](img/b285cfddea560d447d391e9d7ba660ba.jpg)

| Parameters: | **input** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – a minibatch of examples |
| --- | --- |
| Returns: | log-probabilities of for each class ![](img/32624581da7de65d68eb11d4201f9bef.jpg) in range ![](img/4e4201057f969a42a8d2de89e5f7c728.jpg), where ![](img/b285cfddea560d447d391e9d7ba660ba.jpg) is a parameter passed to `AdaptiveLogSoftmaxWithLoss` constructor. |
| --- | --- |

```py
Shape:
```

*   Input: ![](img/768be7688f5f58f4766106ddb821b007.jpg)
*   Output: ![](img/f3bcbc1689556ad810d1c658d44bd970.jpg)

```py
W
wizardforcel 已提交
3618
predict(input)
W
wizardforcel 已提交
3619 3620
```

W
wizardforcel 已提交
3621
This is equivalent to `self.log_pob(input).argmax(dim=1)`, but is more efficient in some cases.
W
wizardforcel 已提交
3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641

| Parameters: | **input** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – a minibatch of examples |
| --- | --- |
| Returns: | a class with the highest probability for each example |
| --- | --- |
| Return type: | output ([Tensor](tensors.html#torch.Tensor "torch.Tensor")) |
| --- | --- |

```py
Shape:
```

*   Input: ![](img/768be7688f5f58f4766106ddb821b007.jpg)
*   Output: ![](img/2a3e2b832e04fe8d66596083b23da518.jpg)

## Normalization layers

### BatchNorm1d

```py
W
wizardforcel 已提交
3642
class torch.nn.BatchNorm1d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
W
wizardforcel 已提交
3643 3644 3645 3646 3647 3648
```

Applies Batch Normalization over a 2D or 3D input (a mini-batch of 1D inputs with optional additional channel dimension) as described in the paper [Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift](https://arxiv.org/abs/1502.03167) .

![](img/beea63da4eceb7d4c8971e826bafbb1a.jpg)

W
wizardforcel 已提交
3649
The mean and standard-deviation are calculated per-dimension over the mini-batches and ![](img/cdab9437b701fd21fb3294cfba7c4bc2.jpg) and ![](img/50705df736e9a7919e768cf8c4e4f794.jpg) are learnable parameter vectors of size `C` (where `C` is the input size). By default, the elements of ![](img/cdab9437b701fd21fb3294cfba7c4bc2.jpg) are sampled from ![](img/7ad9c99a642c915c6d560cbca6352454.jpg) and the elements of ![](img/50705df736e9a7919e768cf8c4e4f794.jpg) are set to 0.
W
wizardforcel 已提交
3650 3651 3652 3653 3654 3655 3656 3657 3658

Also by default, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default `momentum` of 0.1.

If `track_running_stats` is set to `False`, this layer then does not keep running estimates, and batch statistics are instead used during evaluation time as well.

Note

This `momentum` argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is ![](img/05beed2a6202dfed2f2c4d1ddf9f445f.jpg), where ![](img/9d834e987d38585c39d150fe8f46bc74.jpg) is the estimated statistic and ![](img/22c5ed7653e3fae804006a00210327fc.jpg) is the new observed value.

W
wizardforcel 已提交
3659
Because the Batch Normalization is done over the `C` dimension, computing statistics on `(N, L)` slices, it’s common terminology to call this Temporal Batch Normalization.
W
wizardforcel 已提交
3660

W
wizardforcel 已提交
3661
Parameters: 
W
wizardforcel 已提交
3662 3663 3664 3665 3666 3667 3668

*   **num_features** – ![](img/6c8feca3b2da3d6cf371417edff4be4f.jpg) from an expected input of size ![](img/5816e96aa78b7425cf792435bba8bc29.jpg) or ![](img/db4a9fef02111450bf98261889de550c.jpg) from input of size ![](img/b6d0ccc6531c5d648e750c417c5cc72d.jpg)
*   **eps** – a value added to the denominator for numerical stability. Default: 1e-5
*   **momentum** – the value used for the running_mean and running_var computation. Can be set to `None` for cumulative moving average (i.e. simple average). Default: 0.1
*   **affine** – a boolean value that when set to `True`, this module has learnable affine parameters. Default: `True`
*   **track_running_stats** – a boolean value that when set to `True`, this module tracks the running mean and variance, and when set to `False`, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: `True`

W
wizardforcel 已提交
3669

W
wizardforcel 已提交
3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692

```py
Shape:
```

*   Input: ![](img/9b9aebaa467ad07dca05b5086bd21ca2.jpg) or ![](img/5816e96aa78b7425cf792435bba8bc29.jpg)
*   Output: ![](img/9b9aebaa467ad07dca05b5086bd21ca2.jpg) or ![](img/5816e96aa78b7425cf792435bba8bc29.jpg) (same shape as input)

Examples:

```py
>>> # With Learnable Parameters
>>> m = nn.BatchNorm1d(100)
>>> # Without Learnable Parameters
>>> m = nn.BatchNorm1d(100, affine=False)
>>> input = torch.randn(20, 100)
>>> output = m(input)

```

### BatchNorm2d

```py
W
wizardforcel 已提交
3693
class torch.nn.BatchNorm2d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
W
wizardforcel 已提交
3694 3695 3696 3697 3698 3699
```

Applies Batch Normalization over a 4D input (a mini-batch of 2D inputs with additional channel dimension) as described in the paper [Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift](https://arxiv.org/abs/1502.03167) .

![](img/63ee6938c8dea3b7cc66a2a245b15cfc.jpg)

W
wizardforcel 已提交
3700
The mean and standard-deviation are calculated per-dimension over the mini-batches and ![](img/cdab9437b701fd21fb3294cfba7c4bc2.jpg) and ![](img/50705df736e9a7919e768cf8c4e4f794.jpg) are learnable parameter vectors of size `C` (where `C` is the input size). By default, the elements of ![](img/cdab9437b701fd21fb3294cfba7c4bc2.jpg) are sampled from ![](img/7ad9c99a642c915c6d560cbca6352454.jpg) and the elements of ![](img/50705df736e9a7919e768cf8c4e4f794.jpg) are set to 0.
W
wizardforcel 已提交
3701 3702 3703 3704 3705 3706 3707 3708 3709

Also by default, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default `momentum` of 0.1.

If `track_running_stats` is set to `False`, this layer then does not keep running estimates, and batch statistics are instead used during evaluation time as well.

Note

This `momentum` argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is ![](img/05beed2a6202dfed2f2c4d1ddf9f445f.jpg), where ![](img/9d834e987d38585c39d150fe8f46bc74.jpg) is the estimated statistic and ![](img/22c5ed7653e3fae804006a00210327fc.jpg) is the new observed value.

W
wizardforcel 已提交
3710
Because the Batch Normalization is done over the `C` dimension, computing statistics on `(N, H, W)` slices, it’s common terminology to call this Spatial Batch Normalization.
W
wizardforcel 已提交
3711

W
wizardforcel 已提交
3712
Parameters: 
W
wizardforcel 已提交
3713 3714 3715 3716 3717 3718 3719

*   **num_features** – ![](img/6c8feca3b2da3d6cf371417edff4be4f.jpg) from an expected input of size ![](img/23f8772594b27bd387be708fe9c085e1.jpg)
*   **eps** – a value added to the denominator for numerical stability. Default: 1e-5
*   **momentum** – the value used for the running_mean and running_var computation. Can be set to `None` for cumulative moving average (i.e. simple average). Default: 0.1
*   **affine** – a boolean value that when set to `True`, this module has learnable affine parameters. Default: `True`
*   **track_running_stats** – a boolean value that when set to `True`, this module tracks the running mean and variance, and when set to `False`, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: `True`

W
wizardforcel 已提交
3720

W
wizardforcel 已提交
3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743

```py
Shape:
```

*   Input: ![](img/23f8772594b27bd387be708fe9c085e1.jpg)
*   Output: ![](img/23f8772594b27bd387be708fe9c085e1.jpg) (same shape as input)

Examples:

```py
>>> # With Learnable Parameters
>>> m = nn.BatchNorm2d(100)
>>> # Without Learnable Parameters
>>> m = nn.BatchNorm2d(100, affine=False)
>>> input = torch.randn(20, 100, 35, 45)
>>> output = m(input)

```

### BatchNorm3d

```py
W
wizardforcel 已提交
3744
class torch.nn.BatchNorm3d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
W
wizardforcel 已提交
3745 3746 3747 3748 3749 3750
```

Applies Batch Normalization over a 5D input (a mini-batch of 3D inputs with additional channel dimension) as described in the paper [Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift](https://arxiv.org/abs/1502.03167) .

![](img/63ee6938c8dea3b7cc66a2a245b15cfc.jpg)

W
wizardforcel 已提交
3751
The mean and standard-deviation are calculated per-dimension over the mini-batches and ![](img/cdab9437b701fd21fb3294cfba7c4bc2.jpg) and ![](img/50705df736e9a7919e768cf8c4e4f794.jpg) are learnable parameter vectors of size `C` (where `C` is the input size). By default, the elements of ![](img/cdab9437b701fd21fb3294cfba7c4bc2.jpg) are sampled from ![](img/7ad9c99a642c915c6d560cbca6352454.jpg) and the elements of ![](img/50705df736e9a7919e768cf8c4e4f794.jpg) are set to 0.
W
wizardforcel 已提交
3752 3753 3754 3755 3756 3757 3758 3759 3760

Also by default, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default `momentum` of 0.1.

If `track_running_stats` is set to `False`, this layer then does not keep running estimates, and batch statistics are instead used during evaluation time as well.

Note

This `momentum` argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is ![](img/05beed2a6202dfed2f2c4d1ddf9f445f.jpg), where ![](img/9d834e987d38585c39d150fe8f46bc74.jpg) is the estimated statistic and ![](img/22c5ed7653e3fae804006a00210327fc.jpg) is the new observed value.

W
wizardforcel 已提交
3761
Because the Batch Normalization is done over the `C` dimension, computing statistics on `(N, D, H, W)` slices, it’s common terminology to call this Volumetric Batch Normalization or Spatio-temporal Batch Normalization.
W
wizardforcel 已提交
3762

W
wizardforcel 已提交
3763
Parameters: 
W
wizardforcel 已提交
3764 3765 3766 3767 3768 3769 3770

*   **num_features** – ![](img/6c8feca3b2da3d6cf371417edff4be4f.jpg) from an expected input of size ![](img/f5a45f7b445db562b21cfcb525637aab.jpg)
*   **eps** – a value added to the denominator for numerical stability. Default: 1e-5
*   **momentum** – the value used for the running_mean and running_var computation. Can be set to `None` for cumulative moving average (i.e. simple average). Default: 0.1
*   **affine** – a boolean value that when set to `True`, this module has learnable affine parameters. Default: `True`
*   **track_running_stats** – a boolean value that when set to `True`, this module tracks the running mean and variance, and when set to `False`, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: `True`

W
wizardforcel 已提交
3771

W
wizardforcel 已提交
3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794

```py
Shape:
```

*   Input: ![](img/f5a45f7b445db562b21cfcb525637aab.jpg)
*   Output: ![](img/f5a45f7b445db562b21cfcb525637aab.jpg) (same shape as input)

Examples:

```py
>>> # With Learnable Parameters
>>> m = nn.BatchNorm3d(100)
>>> # Without Learnable Parameters
>>> m = nn.BatchNorm3d(100, affine=False)
>>> input = torch.randn(20, 100, 35, 45, 10)
>>> output = m(input)

```

### GroupNorm

```py
W
wizardforcel 已提交
3795
class torch.nn.GroupNorm(num_groups, num_channels, eps=1e-05, affine=True)
W
wizardforcel 已提交
3796 3797 3798 3799 3800 3801 3802 3803 3804 3805
```

Applies Group Normalization over a mini-batch of inputs as described in the paper [Group Normalization](https://arxiv.org/abs/1803.08494) .

![](img/2fee766f06767b7b87b3531029d92e1d.jpg)

The input channels are separated into `num_groups` groups, each containing `num_channels / num_groups` channels. The mean and standard-deviation are calculated separately over the each group. ![](img/cdab9437b701fd21fb3294cfba7c4bc2.jpg) and ![](img/50705df736e9a7919e768cf8c4e4f794.jpg) are learnable per-channel affine transform parameter vectorss of size `num_channels` if `affine` is `True`.

This layer uses statistics computed from input data in both training and evaluation modes.

W
wizardforcel 已提交
3806
Parameters: 
W
wizardforcel 已提交
3807 3808 3809 3810 3811 3812

*   **num_groups** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – number of groups to separate the channels into
*   **num_channels** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – number of channels expected in input
*   **eps** – a value added to the denominator for numerical stability. Default: 1e-5
*   **affine** – a boolean value that when set to `True`, this module has learnable per-channel affine parameters initialized to ones (for weights) and zeros (for biases). Default: `True`.

W
wizardforcel 已提交
3813

W
wizardforcel 已提交
3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839

```py
Shape:
```

*   Input: ![](img/f5be296779e9f325e5c8f0c2284bc073.jpg)
*   Output: ![](img/f5be296779e9f325e5c8f0c2284bc073.jpg) (same shape as input)

Examples:

```py
>>> input = torch.randn(20, 6, 10, 10)
>>> # Separate 6 channels into 3 groups
>>> m = nn.GroupNorm(3, 6)
>>> # Separate 6 channels into 6 groups (equivalent with InstanceNorm)
>>> m = nn.GroupNorm(6, 6)
>>> # Put all 6 channels into a single group (equivalent with LayerNorm)
>>> m = nn.GroupNorm(1, 6)
>>> # Activating the module
>>> output = m(input)

```

### InstanceNorm1d

```py
W
wizardforcel 已提交
3840
class torch.nn.InstanceNorm1d(num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)
W
wizardforcel 已提交
3841 3842 3843 3844 3845 3846
```

Applies Instance Normalization over a 2D or 3D input (a mini-batch of 1D inputs with optional additional channel dimension) as described in the paper [Instance Normalization: The Missing Ingredient for Fast Stylization](https://arxiv.org/abs/1607.08022) .

![](img/63ee6938c8dea3b7cc66a2a245b15cfc.jpg)

W
wizardforcel 已提交
3847
The mean and standard-deviation are calculated per-dimension separately for each object in a mini-batch. ![](img/cdab9437b701fd21fb3294cfba7c4bc2.jpg) and ![](img/50705df736e9a7919e768cf8c4e4f794.jpg) are learnable parameter vectors of size `C` (where `C` is the input size) if `affine` is `True`.
W
wizardforcel 已提交
3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860

By default, this layer uses instance statistics computed from input data in both training and evaluation modes.

If `track_running_stats` is set to `True`, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default `momentum` of 0.1.

Note

This `momentum` argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is ![](img/05beed2a6202dfed2f2c4d1ddf9f445f.jpg), where ![](img/9d834e987d38585c39d150fe8f46bc74.jpg) is the estimated statistic and ![](img/22c5ed7653e3fae804006a00210327fc.jpg) is the new observed value.

Note

[`InstanceNorm1d`](#torch.nn.InstanceNorm1d "torch.nn.InstanceNorm1d") and [`LayerNorm`](#torch.nn.LayerNorm "torch.nn.LayerNorm") are very similar, but have some subtle differences. [`InstanceNorm1d`](#torch.nn.InstanceNorm1d "torch.nn.InstanceNorm1d") is applied on each channel of channeled data like multidimensional time series, but [`LayerNorm`](#torch.nn.LayerNorm "torch.nn.LayerNorm") is usually applied on entire sample and often in NLP tasks. Additionaly, [`LayerNorm`](#torch.nn.LayerNorm "torch.nn.LayerNorm") applies elementwise affine transform, while [`InstanceNorm1d`](#torch.nn.InstanceNorm1d "torch.nn.InstanceNorm1d") usually don’t apply affine transform.

W
wizardforcel 已提交
3861
Parameters: 
W
wizardforcel 已提交
3862 3863 3864 3865 3866 3867 3868

*   **num_features** – ![](img/6c8feca3b2da3d6cf371417edff4be4f.jpg) from an expected input of size ![](img/5816e96aa78b7425cf792435bba8bc29.jpg) or ![](img/db4a9fef02111450bf98261889de550c.jpg) from input of size ![](img/b6d0ccc6531c5d648e750c417c5cc72d.jpg)
*   **eps** – a value added to the denominator for numerical stability. Default: 1e-5
*   **momentum** – the value used for the running_mean and running_var computation. Default: 0.1
*   **affine** – a boolean value that when set to `True`, this module has learnable affine parameters, initialized the same way as done for batch normalization. Default: `False`.
*   **track_running_stats** – a boolean value that when set to `True`, this module tracks the running mean and variance, and when set to `False`, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: `False`

W
wizardforcel 已提交
3869

W
wizardforcel 已提交
3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892

```py
Shape:
```

*   Input: ![](img/5816e96aa78b7425cf792435bba8bc29.jpg)
*   Output: ![](img/5816e96aa78b7425cf792435bba8bc29.jpg) (same shape as input)

Examples:

```py
>>> # Without Learnable Parameters
>>> m = nn.InstanceNorm1d(100)
>>> # With Learnable Parameters
>>> m = nn.InstanceNorm1d(100, affine=True)
>>> input = torch.randn(20, 100, 40)
>>> output = m(input)

```

### InstanceNorm2d

```py
W
wizardforcel 已提交
3893
class torch.nn.InstanceNorm2d(num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)
W
wizardforcel 已提交
3894 3895 3896 3897 3898 3899
```

Applies Instance Normalization over a 4D input (a mini-batch of 2D inputs with additional channel dimension) as described in the paper [Instance Normalization: The Missing Ingredient for Fast Stylization](https://arxiv.org/abs/1607.08022) .

![](img/63ee6938c8dea3b7cc66a2a245b15cfc.jpg)

W
wizardforcel 已提交
3900
The mean and standard-deviation are calculated per-dimension separately for each object in a mini-batch. ![](img/cdab9437b701fd21fb3294cfba7c4bc2.jpg) and ![](img/50705df736e9a7919e768cf8c4e4f794.jpg) are learnable parameter vectors of size `C` (where `C` is the input size) if `affine` is `True`.
W
wizardforcel 已提交
3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913

By default, this layer uses instance statistics computed from input data in both training and evaluation modes.

If `track_running_stats` is set to `True`, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default `momentum` of 0.1.

Note

This `momentum` argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is ![](img/05beed2a6202dfed2f2c4d1ddf9f445f.jpg), where ![](img/9d834e987d38585c39d150fe8f46bc74.jpg) is the estimated statistic and ![](img/22c5ed7653e3fae804006a00210327fc.jpg) is the new observed value.

Note

[`InstanceNorm2d`](#torch.nn.InstanceNorm2d "torch.nn.InstanceNorm2d") and [`LayerNorm`](#torch.nn.LayerNorm "torch.nn.LayerNorm") are very similar, but have some subtle differences. [`InstanceNorm2d`](#torch.nn.InstanceNorm2d "torch.nn.InstanceNorm2d") is applied on each channel of channeled data like RGB images, but [`LayerNorm`](#torch.nn.LayerNorm "torch.nn.LayerNorm") is usually applied on entire sample and often in NLP tasks. Additionaly, [`LayerNorm`](#torch.nn.LayerNorm "torch.nn.LayerNorm") applies elementwise affine transform, while [`InstanceNorm2d`](#torch.nn.InstanceNorm2d "torch.nn.InstanceNorm2d") usually don’t apply affine transform.

W
wizardforcel 已提交
3914
Parameters: 
W
wizardforcel 已提交
3915 3916 3917 3918 3919 3920 3921

*   **num_features** – ![](img/6c8feca3b2da3d6cf371417edff4be4f.jpg) from an expected input of size ![](img/23f8772594b27bd387be708fe9c085e1.jpg)
*   **eps** – a value added to the denominator for numerical stability. Default: 1e-5
*   **momentum** – the value used for the running_mean and running_var computation. Default: 0.1
*   **affine** – a boolean value that when set to `True`, this module has learnable affine parameters, initialized the same way as done for batch normalization. Default: `False`.
*   **track_running_stats** – a boolean value that when set to `True`, this module tracks the running mean and variance, and when set to `False`, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: `False`

W
wizardforcel 已提交
3922

W
wizardforcel 已提交
3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945

```py
Shape:
```

*   Input: ![](img/23f8772594b27bd387be708fe9c085e1.jpg)
*   Output: ![](img/23f8772594b27bd387be708fe9c085e1.jpg) (same shape as input)

Examples:

```py
>>> # Without Learnable Parameters
>>> m = nn.InstanceNorm2d(100)
>>> # With Learnable Parameters
>>> m = nn.InstanceNorm2d(100, affine=True)
>>> input = torch.randn(20, 100, 35, 45)
>>> output = m(input)

```

### InstanceNorm3d

```py
W
wizardforcel 已提交
3946
class torch.nn.InstanceNorm3d(num_features, eps=1e-05, momentum=0.1, affine=False, track_running_stats=False)
W
wizardforcel 已提交
3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966
```

Applies Instance Normalization over a 5D input (a mini-batch of 3D inputs with additional channel dimension) as described in the paper [Instance Normalization: The Missing Ingredient for Fast Stylization](https://arxiv.org/abs/1607.08022) .

![](img/63ee6938c8dea3b7cc66a2a245b15cfc.jpg)

The mean and standard-deviation are calculated per-dimension separately for each object in a mini-batch. ![](img/cdab9437b701fd21fb3294cfba7c4bc2.jpg) and ![](img/50705df736e9a7919e768cf8c4e4f794.jpg) are learnable parameter vectors of size C (where C is the input size) if `affine` is `True`.

By default, this layer uses instance statistics computed from input data in both training and evaluation modes.

If `track_running_stats` is set to `True`, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default `momentum` of 0.1.

Note

This `momentum` argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is ![](img/05beed2a6202dfed2f2c4d1ddf9f445f.jpg), where ![](img/9d834e987d38585c39d150fe8f46bc74.jpg) is the estimated statistic and ![](img/22c5ed7653e3fae804006a00210327fc.jpg) is the new observed value.

Note

[`InstanceNorm3d`](#torch.nn.InstanceNorm3d "torch.nn.InstanceNorm3d") and [`LayerNorm`](#torch.nn.LayerNorm "torch.nn.LayerNorm") are very similar, but have some subtle differences. [`InstanceNorm3d`](#torch.nn.InstanceNorm3d "torch.nn.InstanceNorm3d") is applied on each channel of channeled data like 3D models with RGB color, but [`LayerNorm`](#torch.nn.LayerNorm "torch.nn.LayerNorm") is usually applied on entire sample and often in NLP tasks. Additionaly, [`LayerNorm`](#torch.nn.LayerNorm "torch.nn.LayerNorm") applies elementwise affine transform, while [`InstanceNorm3d`](#torch.nn.InstanceNorm3d "torch.nn.InstanceNorm3d") usually don’t apply affine transform.

W
wizardforcel 已提交
3967
Parameters: 
W
wizardforcel 已提交
3968 3969 3970 3971 3972 3973 3974

*   **num_features** – ![](img/6c8feca3b2da3d6cf371417edff4be4f.jpg) from an expected input of size ![](img/f5a45f7b445db562b21cfcb525637aab.jpg)
*   **eps** – a value added to the denominator for numerical stability. Default: 1e-5
*   **momentum** – the value used for the running_mean and running_var computation. Default: 0.1
*   **affine** – a boolean value that when set to `True`, this module has learnable affine parameters, initialized the same way as done for batch normalization. Default: `False`.
*   **track_running_stats** – a boolean value that when set to `True`, this module tracks the running mean and variance, and when set to `False`, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: `False`

W
wizardforcel 已提交
3975

W
wizardforcel 已提交
3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998

```py
Shape:
```

*   Input: ![](img/f5a45f7b445db562b21cfcb525637aab.jpg)
*   Output: ![](img/f5a45f7b445db562b21cfcb525637aab.jpg) (same shape as input)

Examples:

```py
>>> # Without Learnable Parameters
>>> m = nn.InstanceNorm3d(100)
>>> # With Learnable Parameters
>>> m = nn.InstanceNorm3d(100, affine=True)
>>> input = torch.randn(20, 100, 35, 45, 10)
>>> output = m(input)

```

### LayerNorm

```py
W
wizardforcel 已提交
3999
class torch.nn.LayerNorm(normalized_shape, eps=1e-05, elementwise_affine=True)
W
wizardforcel 已提交
4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013
```

Applies Layer Normalization over a mini-batch of inputs as described in the paper [Layer Normalization](https://arxiv.org/abs/1607.06450) .

![](img/2fee766f06767b7b87b3531029d92e1d.jpg)

The mean and standard-deviation are calculated separately over the last certain number dimensions which have to be of the shape specified by `normalized_shape`. ![](img/cdab9437b701fd21fb3294cfba7c4bc2.jpg) and ![](img/50705df736e9a7919e768cf8c4e4f794.jpg) are learnable affine transform parameters of `normalized_shape` if `elementwise_affine` is `True`.

Note

Unlike Batch Normalization and Instance Normalization, which applies scalar scale and bias for each entire channel/plane with the `affine` option, Layer Normalization applies per-element scale and bias with `elementwise_affine`.

This layer uses statistics computed from input data in both training and evaluation modes.

W
wizardforcel 已提交
4014
Parameters: 
W
wizardforcel 已提交
4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026

*   **normalized_shape** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_list_](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.7)") _or_ _torch.Size_) –

    input shape from an expected input of size

    ![](img/7058ab5ae52adb329c22fa5456ad910f.jpg)

    If a single integer is used, it is treated as a singleton list, and this module will normalize over the last dimension which is expected to be of that specific size.

*   **eps** – a value added to the denominator for numerical stability. Default: 1e-5
*   **elementwise_affine** – a boolean value that when set to `True`, this module has learnable per-element affine parameters initialized to ones (for weights) and zeros (for biases). Default: `True`.

W
wizardforcel 已提交
4027

W
wizardforcel 已提交
4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055

```py
Shape:
```

*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg)
*   Output: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) (same shape as input)

Examples:

```py
>>> input = torch.randn(20, 5, 10, 10)
>>> # With Learnable Parameters
>>> m = nn.LayerNorm(input.size()[1:])
>>> # Without Learnable Parameters
>>> m = nn.LayerNorm(input.size()[1:], elementwise_affine=False)
>>> # Normalize over last two dimensions
>>> m = nn.LayerNorm([10, 10])
>>> # Normalize over last dimension of size 10
>>> m = nn.LayerNorm(10)
>>> # Activating the module
>>> output = m(input)

```

### LocalResponseNorm

```py
W
wizardforcel 已提交
4056
class torch.nn.LocalResponseNorm(size, alpha=0.0001, beta=0.75, k=1.0)
W
wizardforcel 已提交
4057 4058 4059 4060 4061 4062
```

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

![](img/5522547c6e594dc7c5ffe998f57ad26b.jpg)

W
wizardforcel 已提交
4063
Parameters: 
W
wizardforcel 已提交
4064 4065 4066 4067 4068 4069

*   **size** – amount of neighbouring channels used for normalization
*   **alpha** – multiplicative factor. Default: 0.0001
*   **beta** – exponent. Default: 0.75
*   **k** – additive factor. Default: 1

W
wizardforcel 已提交
4070

W
wizardforcel 已提交
4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094

```py
Shape:
```

*   Input: ![](img/0113f670591e6e2a1a50722e1affdce5.jpg)
*   Output: ![](img/0113f670591e6e2a1a50722e1affdce5.jpg) (same shape as input)

Examples:

```py
>>> lrn = nn.LocalResponseNorm(2)
>>> signal_2d = torch.randn(32, 5, 24, 24)
>>> signal_4d = torch.randn(16, 5, 7, 7, 7, 7)
>>> output_2d = lrn(signal_2d)
>>> output_4d = lrn(signal_4d)

```

## Recurrent layers

### RNN

```py
W
wizardforcel 已提交
4095
class torch.nn.RNN(*args, **kwargs)
W
wizardforcel 已提交
4096 4097 4098 4099 4100 4101 4102 4103
```

Applies a multi-layer Elman RNN with ![](img/73b754b4f63e76c0f0327be51d4b263c.jpg) or ![](img/86a6387f3ec09e33de3faaa24f784bca.jpg) non-linearity to an input sequence.

For each element in the input sequence, each layer computes the following function:

![](img/1d1bd72124738a26685d33ce01c89beb.jpg)

W
wizardforcel 已提交
4104
where ![](img/a048a5bfcc0242b6427d15ed11ef7e23.jpg) is the hidden state at time `t`, ![](img/22c5ed7653e3fae804006a00210327fc.jpg) is the input at time `t`, and ![](img/722edd552cee200694a3bfccd4f755df.jpg) is the hidden state of the previous layer at time `t-1` or the initial hidden state at time `0`. If `nonlinearity` is `‘relu’`, then `ReLU` is used instead of `tanh`.
W
wizardforcel 已提交
4105

W
wizardforcel 已提交
4106
Parameters: 
W
wizardforcel 已提交
4107

W
wizardforcel 已提交
4108 4109 4110
*   **input_size** – The number of expected features in the input `x`
*   **hidden_size** – The number of features in the hidden state `h`
*   **num_layers** – Number of recurrent layers. E.g., setting `num_layers=2` would mean stacking two RNNs together to form a `stacked RNN`, with the second RNN taking in outputs of the first RNN and computing the final results. Default: 1
W
wizardforcel 已提交
4111
*   **nonlinearity** – The non-linearity to use. Can be either ‘tanh’ or ‘relu’. Default: ‘tanh’
W
wizardforcel 已提交
4112 4113 4114
*   **bias** – If `False`, then the layer does not use bias weights `b_ih` and `b_hh`. Default: `True`
*   **batch_first** – If `True`, then the input and output tensors are provided as `(batch, seq, feature)`. Default: `False`
*   **dropout** – If non-zero, introduces a `Dropout` layer on the outputs of each RNN layer except the last layer, with dropout probability equal to `dropout`. Default: 0
W
wizardforcel 已提交
4115 4116
*   **bidirectional** – If `True`, becomes a bidirectional RNN. Default: `False`

W
wizardforcel 已提交
4117

W
wizardforcel 已提交
4118 4119 4120 4121 4122

```py
Inputs: input, h_0
```

W
wizardforcel 已提交
4123 4124
*   **input** of shape `(seq_len, batch, input_size)`: tensor containing the features of the input sequence. The input can also be a packed variable length sequence. See [`torch.nn.utils.rnn.pack_padded_sequence()`](#torch.nn.utils.rnn.pack_padded_sequence "torch.nn.utils.rnn.pack_padded_sequence") or [`torch.nn.utils.rnn.pack_sequence()`](#torch.nn.utils.rnn.pack_sequence "torch.nn.utils.rnn.pack_sequence") for details.
*   **h_0** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor containing the initial hidden state for each element in the batch. Defaults to zero if not provided. If the RNN is bidirectional, num_directions should be 2, else it should be 1.
W
wizardforcel 已提交
4125 4126 4127 4128 4129

```py
Outputs: output, h_n
```

W
wizardforcel 已提交
4130
*   **output** of shape `(seq_len, batch, num_directions * hidden_size)`: tensor containing the output features (`h_k`) from the last layer of the RNN, for each `k`. If a [`torch.nn.utils.rnn.PackedSequence`](#torch.nn.utils.rnn.PackedSequence "torch.nn.utils.rnn.PackedSequence") has been given as the input, the output will also be a packed sequence.
W
wizardforcel 已提交
4131

W
wizardforcel 已提交
4132
    For the unpacked case, the directions can be separated using `output.view(seq_len, batch, num_directions, hidden_size)`, with forward and backward being direction `0` and `1` respectively. Similarly, the directions can be separated in the packed case.
W
wizardforcel 已提交
4133

W
wizardforcel 已提交
4134
*   **h_n** (num_layers * num_directions, batch, hidden_size): tensor containing the hidden state for `k = seq_len`.
W
wizardforcel 已提交
4135 4136 4137 4138 4139

    Like _output_, the layers can be separated using `h_n.view(num_layers, num_directions, batch, hidden_size)`.

| Variables: | 

W
wizardforcel 已提交
4140 4141 4142 4143
*   **weight_ih_l[k]** – the learnable input-hidden weights of the k-th layer, of shape `(hidden_size * input_size)` for `k = 0`. Otherwise, the shape is `(hidden_size * hidden_size)`
*   **weight_hh_l[k]** – the learnable hidden-hidden weights of the k-th layer, of shape `(hidden_size * hidden_size)`
*   **bias_ih_l[k]** – the learnable input-hidden bias of the k-th layer, of shape `(hidden_size)`
*   **bias_hh_l[k]** – the learnable hidden-hidden bias of the k-th layer, of shape `(hidden_size)`
W
wizardforcel 已提交
4144

W
wizardforcel 已提交
4145

W
wizardforcel 已提交
4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167

Note

All the weights and biases are initialized from ![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg) where ![](img/cb80fd45c1b2dc2b84b2e80eb48d111e.jpg)

Note

If the following conditions are satisfied: 1) cudnn is enabled, 2) input data is on the GPU 3) input data has dtype `torch.float16` 4) V100 GPU is used, 5) input data is not in `PackedSequence` format persistent algorithm can be selected to improve performance.

Examples:

```py
>>> rnn = nn.RNN(10, 20, 2)
>>> input = torch.randn(5, 3, 10)
>>> h0 = torch.randn(2, 3, 20)
>>> output, hn = rnn(input, h0)

```

### LSTM

```py
W
wizardforcel 已提交
4168
class torch.nn.LSTM(*args, **kwargs)
W
wizardforcel 已提交
4169 4170 4171 4172 4173 4174 4175 4176
```

Applies a multi-layer long short-term memory (LSTM) RNN to an input sequence.

For each element in the input sequence, each layer computes the following function:

![](img/e45b4c4446dc36020077ab726cee248f.jpg)

W
wizardforcel 已提交
4177
where ![](img/a048a5bfcc0242b6427d15ed11ef7e23.jpg) is the hidden state at time `t`, ![](img/a96fd1792ebb964c44e6a4802fe73a45.jpg) is the cell state at time `t`, ![](img/22c5ed7653e3fae804006a00210327fc.jpg) is the input at time `t`, ![](img/722edd552cee200694a3bfccd4f755df.jpg) is the hidden state of the layer at time `t-1` or the initial hidden state at time `0`, and ![](img/0c33b098890c73bacbf2dbe5476b8ea0.jpg), ![](img/39e0c3cfa9742216d02b21de5ed57650.jpg), ![](img/2fe3fba6f09d597fd2b3cd6a1e0b4547.jpg), ![](img/8b4c3e8be7da971e832789294ddd61d4.jpg) are the input, forget, cell, and output gates, respectively. ![](img/2469b2bd2a1ab19ebfcee223dcb52bb1.jpg) is the sigmoid function.
W
wizardforcel 已提交
4178 4179 4180

In a multilayer LSTM, the input ![](img/3aef28832238eb9de1c3d226cc4f026e.jpg) of the ![](img/4c55f62a52ee5572ab96494e9e0a2876.jpg) -th layer (![](img/c2c7ccc0042019ca7a1bb7d536da8a87.jpg)) is the hidden state ![](img/aa2a9f5361143e6f3a32d54920079b52.jpg) of the previous layer multiplied by dropout ![](img/5e5fffda0db50ff1fedeef29921cdf85.jpg) where each ![](img/5b70351b42153bea8ab63d8e783cc0ac.jpg) is a Bernoulli random variable which is ![](img/28256dd5af833c877d63bfabfaa7b301.jpg) with probability `dropout`.

W
wizardforcel 已提交
4181
Parameters: 
W
wizardforcel 已提交
4182

W
wizardforcel 已提交
4183 4184 4185 4186
*   **input_size** – The number of expected features in the input `x`
*   **hidden_size** – The number of features in the hidden state `h`
*   **num_layers** – Number of recurrent layers. E.g., setting `num_layers=2` would mean stacking two LSTMs together to form a `stacked LSTM`, with the second LSTM taking in outputs of the first LSTM and computing the final results. Default: 1
*   **bias** – If `False`, then the layer does not use bias weights `b_ih` and `b_hh`. Default: `True`
W
wizardforcel 已提交
4187
*   **batch_first** – If `True`, then the input and output tensors are provided as (batch, seq, feature). Default: `False`
W
wizardforcel 已提交
4188
*   **dropout** – If non-zero, introduces a `Dropout` layer on the outputs of each LSTM layer except the last layer, with dropout probability equal to `dropout`. Default: 0
W
wizardforcel 已提交
4189 4190
*   **bidirectional** – If `True`, becomes a bidirectional LSTM. Default: `False`

W
wizardforcel 已提交
4191

W
wizardforcel 已提交
4192 4193 4194 4195 4196

```py
Inputs: input, (h_0, c_0)
```

W
wizardforcel 已提交
4197
*   **input** of shape `(seq_len, batch, input_size)`: tensor containing the features of the input sequence. The input can also be a packed variable length sequence. See [`torch.nn.utils.rnn.pack_padded_sequence()`](#torch.nn.utils.rnn.pack_padded_sequence "torch.nn.utils.rnn.pack_padded_sequence") or [`torch.nn.utils.rnn.pack_sequence()`](#torch.nn.utils.rnn.pack_sequence "torch.nn.utils.rnn.pack_sequence") for details.
W
wizardforcel 已提交
4198

W
wizardforcel 已提交
4199
*   **h_0** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor containing the initial hidden state for each element in the batch. If the RNN is bidirectional, num_directions should be 2, else it should be 1.
W
wizardforcel 已提交
4200

W
wizardforcel 已提交
4201
*   **c_0** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor containing the initial cell state for each element in the batch.
W
wizardforcel 已提交
4202

W
wizardforcel 已提交
4203
    If `(h_0, c_0)` is not provided, both **h_0** and **c_0** default to zero.
W
wizardforcel 已提交
4204 4205 4206 4207 4208

```py
Outputs: output, (h_n, c_n)
```

W
wizardforcel 已提交
4209
*   **output** of shape `(seq_len, batch, num_directions * hidden_size)`: tensor containing the output features `(h_t)` from the last layer of the LSTM, for each t. If a [`torch.nn.utils.rnn.PackedSequence`](#torch.nn.utils.rnn.PackedSequence "torch.nn.utils.rnn.PackedSequence") has been given as the input, the output will also be a packed sequence.
W
wizardforcel 已提交
4210

W
wizardforcel 已提交
4211
    For the unpacked case, the directions can be separated using `output.view(seq_len, batch, num_directions, hidden_size)`, with forward and backward being direction `0` and `1` respectively. Similarly, the directions can be separated in the packed case.
W
wizardforcel 已提交
4212

W
wizardforcel 已提交
4213
*   **h_n** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor containing the hidden state for `t = seq_len`.
W
wizardforcel 已提交
4214 4215 4216

    Like _output_, the layers can be separated using `h_n.view(num_layers, num_directions, batch, hidden_size)` and similarly for _c_n_.

W
wizardforcel 已提交
4217
*   **c_n** (num_layers * num_directions, batch, hidden_size): tensor containing the cell state for `t = seq_len`
W
wizardforcel 已提交
4218 4219 4220

| Variables: | 

W
wizardforcel 已提交
4221 4222 4223 4224
*   **weight_ih_l[k]** – the learnable input-hidden weights of the ![](img/3daedae8ea4977a42453935c04c06ad0.jpg) layer `(W_ii&#124;W_if&#124;W_ig&#124;W_io)`, of shape `(4*hidden_size x input_size)`
*   **weight_hh_l[k]** – the learnable hidden-hidden weights of the ![](img/3daedae8ea4977a42453935c04c06ad0.jpg) layer `(W_hi&#124;W_hf&#124;W_hg&#124;W_ho)`, of shape `(4*hidden_size x hidden_size)`
*   **bias_ih_l[k]** – the learnable input-hidden bias of the ![](img/3daedae8ea4977a42453935c04c06ad0.jpg) layer `(b_ii&#124;b_if&#124;b_ig&#124;b_io)`, of shape `(4*hidden_size)`
*   **bias_hh_l[k]** – the learnable hidden-hidden bias of the ![](img/3daedae8ea4977a42453935c04c06ad0.jpg) layer `(b_hi&#124;b_hf&#124;b_hg&#124;b_ho)`, of shape `(4*hidden_size)`
W
wizardforcel 已提交
4225

W
wizardforcel 已提交
4226

W
wizardforcel 已提交
4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249

Note

All the weights and biases are initialized from ![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg) where ![](img/cb80fd45c1b2dc2b84b2e80eb48d111e.jpg)

Note

If the following conditions are satisfied: 1) cudnn is enabled, 2) input data is on the GPU 3) input data has dtype `torch.float16` 4) V100 GPU is used, 5) input data is not in `PackedSequence` format persistent algorithm can be selected to improve performance.

Examples:

```py
>>> rnn = nn.LSTM(10, 20, 2)
>>> input = torch.randn(5, 3, 10)
>>> h0 = torch.randn(2, 3, 20)
>>> c0 = torch.randn(2, 3, 20)
>>> output, (hn, cn) = rnn(input, (h0, c0))

```

### GRU

```py
W
wizardforcel 已提交
4250
class torch.nn.GRU(*args, **kwargs)
W
wizardforcel 已提交
4251 4252 4253 4254 4255 4256 4257 4258
```

Applies a multi-layer gated recurrent unit (GRU) RNN to an input sequence.

For each element in the input sequence, each layer computes the following function:

![](img/76771dd2e48bad7097dc9524356200ef.jpg)

W
wizardforcel 已提交
4259
where ![](img/a048a5bfcc0242b6427d15ed11ef7e23.jpg) is the hidden state at time `t`, ![](img/22c5ed7653e3fae804006a00210327fc.jpg) is the input at time `t`, ![](img/722edd552cee200694a3bfccd4f755df.jpg) is the hidden state of the layer at time `t-1` or the initial hidden state at time `0`, and ![](img/33becaceee3dd4f30f106b6a8605226f.jpg), ![](img/98ba4bd98c899c9f15a00fe76fe782b2.jpg), ![](img/4d63033e7717e68b17fc937ffcbcde4b.jpg) are the reset, update, and new gates, respectively. ![](img/2469b2bd2a1ab19ebfcee223dcb52bb1.jpg) is the sigmoid function.
W
wizardforcel 已提交
4260 4261 4262

In a multilayer GRU, the input ![](img/3aef28832238eb9de1c3d226cc4f026e.jpg) of the ![](img/4c55f62a52ee5572ab96494e9e0a2876.jpg) -th layer (![](img/c2c7ccc0042019ca7a1bb7d536da8a87.jpg)) is the hidden state ![](img/aa2a9f5361143e6f3a32d54920079b52.jpg) of the previous layer multiplied by dropout ![](img/5e5fffda0db50ff1fedeef29921cdf85.jpg) where each ![](img/5b70351b42153bea8ab63d8e783cc0ac.jpg) is a Bernoulli random variable which is ![](img/28256dd5af833c877d63bfabfaa7b301.jpg) with probability `dropout`.

W
wizardforcel 已提交
4263
Parameters: 
W
wizardforcel 已提交
4264

W
wizardforcel 已提交
4265 4266 4267 4268
*   **input_size** – The number of expected features in the input `x`
*   **hidden_size** – The number of features in the hidden state `h`
*   **num_layers** – Number of recurrent layers. E.g., setting `num_layers=2` would mean stacking two GRUs together to form a `stacked GRU`, with the second GRU taking in outputs of the first GRU and computing the final results. Default: 1
*   **bias** – If `False`, then the layer does not use bias weights `b_ih` and `b_hh`. Default: `True`
W
wizardforcel 已提交
4269
*   **batch_first** – If `True`, then the input and output tensors are provided as (batch, seq, feature). Default: `False`
W
wizardforcel 已提交
4270
*   **dropout** – If non-zero, introduces a `Dropout` layer on the outputs of each GRU layer except the last layer, with dropout probability equal to `dropout`. Default: 0
W
wizardforcel 已提交
4271 4272
*   **bidirectional** – If `True`, becomes a bidirectional GRU. Default: `False`

W
wizardforcel 已提交
4273

W
wizardforcel 已提交
4274 4275 4276 4277 4278

```py
Inputs: input, h_0
```

W
wizardforcel 已提交
4279 4280
*   **input** of shape `(seq_len, batch, input_size)`: tensor containing the features of the input sequence. The input can also be a packed variable length sequence. See [`torch.nn.utils.rnn.pack_padded_sequence()`](#torch.nn.utils.rnn.pack_padded_sequence "torch.nn.utils.rnn.pack_padded_sequence") for details.
*   **h_0** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor containing the initial hidden state for each element in the batch. Defaults to zero if not provided. If the RNN is bidirectional, num_directions should be 2, else it should be 1.
W
wizardforcel 已提交
4281 4282 4283 4284 4285

```py
Outputs: output, h_n
```

W
wizardforcel 已提交
4286
*   **output** of shape `(seq_len, batch, num_directions * hidden_size)`: tensor containing the output features h_t from the last layer of the GRU, for each t. If a [`torch.nn.utils.rnn.PackedSequence`](#torch.nn.utils.rnn.PackedSequence "torch.nn.utils.rnn.PackedSequence") has been given as the input, the output will also be a packed sequence. For the unpacked case, the directions can be separated using `output.view(seq_len, batch, num_directions, hidden_size)`, with forward and backward being direction `0` and `1` respectively.
W
wizardforcel 已提交
4287 4288 4289

    Similarly, the directions can be separated in the packed case.

W
wizardforcel 已提交
4290
*   **h_n** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor containing the hidden state for `t = seq_len`
W
wizardforcel 已提交
4291 4292 4293 4294 4295

    Like _output_, the layers can be separated using `h_n.view(num_layers, num_directions, batch, hidden_size)`.

| Variables: | 

W
wizardforcel 已提交
4296 4297 4298 4299
*   **weight_ih_l[k]** – the learnable input-hidden weights of the ![](img/3daedae8ea4977a42453935c04c06ad0.jpg) layer (W_ir&#124;W_iz&#124;W_in), of shape `(3*hidden_size x input_size)`
*   **weight_hh_l[k]** – the learnable hidden-hidden weights of the ![](img/3daedae8ea4977a42453935c04c06ad0.jpg) layer (W_hr&#124;W_hz&#124;W_hn), of shape `(3*hidden_size x hidden_size)`
*   **bias_ih_l[k]** – the learnable input-hidden bias of the ![](img/3daedae8ea4977a42453935c04c06ad0.jpg) layer (b_ir&#124;b_iz&#124;b_in), of shape `(3*hidden_size)`
*   **bias_hh_l[k]** – the learnable hidden-hidden bias of the ![](img/3daedae8ea4977a42453935c04c06ad0.jpg) layer (b_hr&#124;b_hz&#124;b_hn), of shape `(3*hidden_size)`
W
wizardforcel 已提交
4300

W
wizardforcel 已提交
4301

W
wizardforcel 已提交
4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323

Note

All the weights and biases are initialized from ![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg) where ![](img/cb80fd45c1b2dc2b84b2e80eb48d111e.jpg)

Note

If the following conditions are satisfied: 1) cudnn is enabled, 2) input data is on the GPU 3) input data has dtype `torch.float16` 4) V100 GPU is used, 5) input data is not in `PackedSequence` format persistent algorithm can be selected to improve performance.

Examples:

```py
>>> rnn = nn.GRU(10, 20, 2)
>>> input = torch.randn(5, 3, 10)
>>> h0 = torch.randn(2, 3, 20)
>>> output, hn = rnn(input, h0)

```

### RNNCell

```py
W
wizardforcel 已提交
4324
class torch.nn.RNNCell(input_size, hidden_size, bias=True, nonlinearity='tanh')
W
wizardforcel 已提交
4325 4326 4327 4328 4329 4330
```

An Elman RNN cell with tanh or ReLU non-linearity.

![](img/e748fe354d996221dbfa5f8e3412451e.jpg)

W
wizardforcel 已提交
4331
If `nonlinearity` is `‘relu’`, then ReLU is used in place of tanh.
W
wizardforcel 已提交
4332

W
wizardforcel 已提交
4333
Parameters: 
W
wizardforcel 已提交
4334

W
wizardforcel 已提交
4335 4336 4337
*   **input_size** – The number of expected features in the input `x`
*   **hidden_size** – The number of features in the hidden state `h`
*   **bias** – If `False`, then the layer does not use bias weights `b_ih` and `b_hh`. Default: `True`
W
wizardforcel 已提交
4338 4339
*   **nonlinearity** – The non-linearity to use. Can be either ‘tanh’ or ‘relu’. Default: ‘tanh’

W
wizardforcel 已提交
4340

W
wizardforcel 已提交
4341 4342 4343 4344 4345

```py
Inputs: input, hidden
```

W
wizardforcel 已提交
4346 4347
*   **input** of shape `(batch, input_size)`: tensor containing input features
*   **hidden** of shape `(batch, hidden_size)`: tensor containing the initial hidden state for each element in the batch. Defaults to zero if not provided.
W
wizardforcel 已提交
4348 4349 4350 4351 4352

```py
Outputs: h
```

W
wizardforcel 已提交
4353
*   **h’** of shape `(batch, hidden_size)`: tensor containing the next hidden state for each element in the batch
W
wizardforcel 已提交
4354 4355 4356

| Variables: | 

W
wizardforcel 已提交
4357 4358 4359 4360
*   **weight_ih** – the learnable input-hidden weights, of shape `(hidden_size x input_size)`
*   **weight_hh** – the learnable hidden-hidden weights, of shape `(hidden_size x hidden_size)`
*   **bias_ih** – the learnable input-hidden bias, of shape `(hidden_size)`
*   **bias_hh** – the learnable hidden-hidden bias, of shape `(hidden_size)`
W
wizardforcel 已提交
4361

W
wizardforcel 已提交
4362

W
wizardforcel 已提交
4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383

Note

All the weights and biases are initialized from ![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg) where ![](img/cb80fd45c1b2dc2b84b2e80eb48d111e.jpg)

Examples:

```py
>>> rnn = nn.RNNCell(10, 20)
>>> input = torch.randn(6, 3, 10)
>>> hx = torch.randn(3, 20)
>>> output = []
>>> for i in range(6):
 hx = rnn(input[i], hx)
 output.append(hx)

```

### LSTMCell

```py
W
wizardforcel 已提交
4384
class torch.nn.LSTMCell(input_size, hidden_size, bias=True)
W
wizardforcel 已提交
4385 4386 4387 4388 4389 4390 4391 4392
```

A long short-term memory (LSTM) cell.

![](img/fb4d6ec81b25bb8201fbedd23b71b45f.jpg)

where ![](img/2469b2bd2a1ab19ebfcee223dcb52bb1.jpg) is the sigmoid function.

W
wizardforcel 已提交
4393
Parameters: 
W
wizardforcel 已提交
4394

W
wizardforcel 已提交
4395 4396 4397
*   **input_size** – The number of expected features in the input `x`
*   **hidden_size** – The number of features in the hidden state `h`
*   **bias** – If `False`, then the layer does not use bias weights `b_ih` and `b_hh`. Default: `True`
W
wizardforcel 已提交
4398

W
wizardforcel 已提交
4399

W
wizardforcel 已提交
4400 4401 4402 4403 4404

```py
Inputs: input, (h_0, c_0)
```

W
wizardforcel 已提交
4405
*   **input** of shape `(batch, input_size)`: tensor containing input features
W
wizardforcel 已提交
4406

W
wizardforcel 已提交
4407
*   **h_0** of shape `(batch, hidden_size)`: tensor containing the initial hidden state for each element in the batch.
W
wizardforcel 已提交
4408

W
wizardforcel 已提交
4409
*   **c_0** of shape `(batch, hidden_size)`: tensor containing the initial cell state for each element in the batch.
W
wizardforcel 已提交
4410

W
wizardforcel 已提交
4411
    If `(h_0, c_0)` is not provided, both **h_0** and **c_0** default to zero.
W
wizardforcel 已提交
4412 4413 4414 4415 4416

```py
Outputs: h_1, c_1
```

W
wizardforcel 已提交
4417 4418
*   **h_1** of shape `(batch, hidden_size)`: tensor containing the next hidden state for each element in the batch
*   **c_1** of shape `(batch, hidden_size)`: tensor containing the next cell state for each element in the batch
W
wizardforcel 已提交
4419 4420 4421

| Variables: | 

W
wizardforcel 已提交
4422 4423 4424 4425
*   **weight_ih** – the learnable input-hidden weights, of shape `(4*hidden_size x input_size)`
*   **weight_hh** – the learnable hidden-hidden weights, of shape `(4*hidden_size x hidden_size)`
*   **bias_ih** – the learnable input-hidden bias, of shape `(4*hidden_size)`
*   **bias_hh** – the learnable hidden-hidden bias, of shape `(4*hidden_size)`
W
wizardforcel 已提交
4426

W
wizardforcel 已提交
4427

W
wizardforcel 已提交
4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449

Note

All the weights and biases are initialized from ![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg) where ![](img/cb80fd45c1b2dc2b84b2e80eb48d111e.jpg)

Examples:

```py
>>> rnn = nn.LSTMCell(10, 20)
>>> input = torch.randn(6, 3, 10)
>>> hx = torch.randn(3, 20)
>>> cx = torch.randn(3, 20)
>>> output = []
>>> for i in range(6):
 hx, cx = rnn(input[i], (hx, cx))
 output.append(hx)

```

### GRUCell

```py
W
wizardforcel 已提交
4450
class torch.nn.GRUCell(input_size, hidden_size, bias=True)
W
wizardforcel 已提交
4451 4452 4453 4454 4455 4456 4457 4458
```

A gated recurrent unit (GRU) cell

![](img/a557e5b089bda248c2e25791d88d4b2a.jpg)

where ![](img/2469b2bd2a1ab19ebfcee223dcb52bb1.jpg) is the sigmoid function.

W
wizardforcel 已提交
4459
Parameters: 
W
wizardforcel 已提交
4460

W
wizardforcel 已提交
4461 4462 4463
*   **input_size** – The number of expected features in the input `x`
*   **hidden_size** – The number of features in the hidden state `h`
*   **bias** – If `False`, then the layer does not use bias weights `b_ih` and `b_hh`. Default: `True`
W
wizardforcel 已提交
4464

W
wizardforcel 已提交
4465

W
wizardforcel 已提交
4466 4467 4468 4469 4470

```py
Inputs: input, hidden
```

W
wizardforcel 已提交
4471 4472
*   **input** of shape `(batch, input_size)`: tensor containing input features
*   **hidden** of shape `(batch, hidden_size)`: tensor containing the initial hidden state for each element in the batch. Defaults to zero if not provided.
W
wizardforcel 已提交
4473 4474 4475 4476 4477

```py
Outputs: h
```

W
wizardforcel 已提交
4478
*   **h’** of shape `(batch, hidden_size)`: tensor containing the next hidden state for each element in the batch
W
wizardforcel 已提交
4479 4480 4481

| Variables: | 

W
wizardforcel 已提交
4482 4483 4484 4485
*   **weight_ih** – the learnable input-hidden weights, of shape `(3*hidden_size x input_size)`
*   **weight_hh** – the learnable hidden-hidden weights, of shape `(3*hidden_size x hidden_size)`
*   **bias_ih** – the learnable input-hidden bias, of shape `(3*hidden_size)`
*   **bias_hh** – the learnable hidden-hidden bias, of shape `(3*hidden_size)`
W
wizardforcel 已提交
4486

W
wizardforcel 已提交
4487

W
wizardforcel 已提交
4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510

Note

All the weights and biases are initialized from ![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg) where ![](img/cb80fd45c1b2dc2b84b2e80eb48d111e.jpg)

Examples:

```py
>>> rnn = nn.GRUCell(10, 20)
>>> input = torch.randn(6, 3, 10)
>>> hx = torch.randn(3, 20)
>>> output = []
>>> for i in range(6):
 hx = rnn(input[i], hx)
 output.append(hx)

```

## Linear layers

### Linear

```py
W
wizardforcel 已提交
4511
class torch.nn.Linear(in_features, out_features, bias=True)
W
wizardforcel 已提交
4512 4513 4514 4515
```

Applies a linear transformation to the incoming data: ![](img/8c4834b7cb4b9c7a795bf354412e8dd3.jpg)

W
wizardforcel 已提交
4516
Parameters: 
W
wizardforcel 已提交
4517 4518 4519 4520 4521

*   **in_features** – size of each input sample
*   **out_features** – size of each output sample
*   **bias** – If set to False, the layer will not learn an additive bias. Default: `True`

W
wizardforcel 已提交
4522

W
wizardforcel 已提交
4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535

```py
Shape:
```

*   Input: ![](img/37251f14c8c7345b66309c1ce6181e4d.jpg) where ![](img/28ec51e742166ea3400be6e7343bbfa5.jpg) means any number of additional dimensions
*   Output: ![](img/052531b4914630967eb9a6ed4f143697.jpg) where all but the last dimension are the same shape as the input.

| Variables: | 

*   **weight** – the learnable weights of the module of shape ![](img/7bdd499093e2167451c56eb5c4480786.jpg). The values are initialized from ![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg), where ![](img/9d1dd979275f32a1bcc00f4e3885e68c.jpg)
*   **bias** – the learnable bias of the module of shape ![](img/27eac2d9aa3b57eabe07fcce145717d2.jpg). If `bias` is `True`, the values are initialized from ![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg) where ![](img/9d1dd979275f32a1bcc00f4e3885e68c.jpg)

W
wizardforcel 已提交
4536

W
wizardforcel 已提交
4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551

Examples:

```py
>>> m = nn.Linear(20, 30)
>>> input = torch.randn(128, 20)
>>> output = m(input)
>>> print(output.size())
torch.Size([128, 30])

```

### Bilinear

```py
W
wizardforcel 已提交
4552
class torch.nn.Bilinear(in1_features, in2_features, out_features, bias=True)
W
wizardforcel 已提交
4553 4554 4555 4556
```

Applies a bilinear transformation to the incoming data: ![](img/a0d89d1240ed669c322d042acea66b2c.jpg)

W
wizardforcel 已提交
4557
Parameters: 
W
wizardforcel 已提交
4558 4559 4560 4561 4562 4563

*   **in1_features** – size of each first input sample
*   **in2_features** – size of each second input sample
*   **out_features** – size of each output sample
*   **bias** – If set to False, the layer will not learn an additive bias. Default: `True`

W
wizardforcel 已提交
4564

W
wizardforcel 已提交
4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577

```py
Shape:
```

*   Input: ![](img/9cf39fb88b1a94018532514fcb3e125c.jpg), ![](img/5b3219dff177846f3a5aebdb36ae5d30.jpg) where ![](img/28ec51e742166ea3400be6e7343bbfa5.jpg) means any number of additional dimensions. All but the last dimension of the inputs should be the same.
*   Output: ![](img/052531b4914630967eb9a6ed4f143697.jpg) where all but the last dimension are the same shape as the input.

| Variables: | 

*   **weight** – the learnable weights of the module of shape ![](img/3f2a47921a3568c8f0f8c45847fd2ad3.jpg). The values are initialized from ![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg), where ![](img/76606e23079bb41cbaeb5fa9ddc71c86.jpg)
*   **bias** – the learnable bias of the module of shape ![](img/27eac2d9aa3b57eabe07fcce145717d2.jpg) If `bias` is `True`, the values are initialized from ![](img/3d305f1c240ff844b6cb2c1c6660e0af.jpg), where ![](img/76606e23079bb41cbaeb5fa9ddc71c86.jpg)

W
wizardforcel 已提交
4578

W
wizardforcel 已提交
4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596

Examples:

```py
>>> m = nn.Bilinear(20, 30, 40)
>>> input1 = torch.randn(128, 20)
>>> input2 = torch.randn(128, 30)
>>> output = m(input1, input2)
>>> print(output.size())
torch.Size([128, 40])

```

## Dropout layers

### Dropout

```py
W
wizardforcel 已提交
4597
class torch.nn.Dropout(p=0.5, inplace=False)
W
wizardforcel 已提交
4598 4599 4600 4601 4602 4603 4604 4605
```

During training, randomly zeroes some of the elements of the input tensor with probability `p` using samples from a Bernoulli distribution. Each channel will be zeroed out independently on every forward call.

This has proven to be an effective technique for regularization and preventing the co-adaptation of neurons as described in the paper [Improving neural networks by preventing co-adaptation of feature detectors](https://arxiv.org/abs/1207.0580) .

Furthermore, the outputs are scaled by a factor of ![](img/37052da8591fea742432c58ac3a4dc59.jpg) during training. This means that during evaluation the module simply computes an identity function.

W
wizardforcel 已提交
4606
Parameters: 
W
wizardforcel 已提交
4607 4608 4609 4610

*   **p** – probability of an element to be zeroed. Default: 0.5
*   **inplace** – If set to `True`, will do this operation in-place. Default: `False`

W
wizardforcel 已提交
4611

W
wizardforcel 已提交
4612 4613 4614 4615 4616

```py
Shape:
```

W
wizardforcel 已提交
4617 4618
*   Input: `Any`. Input can be of any shape
*   Output: `Same`. Output is of the same shape as input
W
wizardforcel 已提交
4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631

Examples:

```py
>>> m = nn.Dropout(p=0.2)
>>> input = torch.randn(20, 16)
>>> output = m(input)

```

### Dropout2d

```py
W
wizardforcel 已提交
4632
class torch.nn.Dropout2d(p=0.5, inplace=False)
W
wizardforcel 已提交
4633 4634 4635 4636 4637 4638 4639 4640 4641 4642
```

Randomly zero out entire channels (a channel is a 2D feature map, e.g., the ![](img/d8fdd0e28cfb03738fc5227885ee035a.jpg)-th channel of the ![](img/31df9c730e19ca29b59dce64b99d98c1.jpg)-th sample in the batched input is a 2D tensor ![](img/5bc8fbe2fea3359e55846184c5eb123a.jpg)) of the input tensor). Each channel will be zeroed out independently on every forward call. with probability `p` using samples from a Bernoulli distribution.

Usually the input comes from `nn.Conv2d` modules.

As described in the paper [Efficient Object Localization Using Convolutional Networks](http://arxiv.org/abs/1411.4280) , if adjacent pixels within feature maps are strongly correlated (as is normally the case in early convolution layers) then i.i.d. dropout will not regularize the activations and will otherwise just result in an effective learning rate decrease.

In this case, `nn.Dropout2d()` will help promote independence between feature maps and should be used instead.

W
wizardforcel 已提交
4643
Parameters: 
W
wizardforcel 已提交
4644 4645 4646 4647

*   **p** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – probability of an element to be zero-ed.
*   **inplace** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – If set to `True`, will do this operation in-place

W
wizardforcel 已提交
4648

W
wizardforcel 已提交
4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668

```py
Shape:
```

*   Input: ![](img/23f8772594b27bd387be708fe9c085e1.jpg)
*   Output: ![](img/23f8772594b27bd387be708fe9c085e1.jpg) (same shape as input)

Examples:

```py
>>> m = nn.Dropout2d(p=0.2)
>>> input = torch.randn(20, 16, 32, 32)
>>> output = m(input)

```

### Dropout3d

```py
W
wizardforcel 已提交
4669
class torch.nn.Dropout3d(p=0.5, inplace=False)
W
wizardforcel 已提交
4670 4671 4672 4673 4674 4675 4676 4677 4678 4679
```

Randomly zero out entire channels (a channel is a 3D feature map, e.g., the ![](img/d8fdd0e28cfb03738fc5227885ee035a.jpg)-th channel of the ![](img/31df9c730e19ca29b59dce64b99d98c1.jpg)-th sample in the batched input is a 3D tensor ![](img/5bc8fbe2fea3359e55846184c5eb123a.jpg)) of the input tensor). Each channel will be zeroed out independently on every forward call. with probability `p` using samples from a Bernoulli distribution.

Usually the input comes from `nn.Conv3d` modules.

As described in the paper [Efficient Object Localization Using Convolutional Networks](http://arxiv.org/abs/1411.4280) , if adjacent pixels within feature maps are strongly correlated (as is normally the case in early convolution layers) then i.i.d. dropout will not regularize the activations and will otherwise just result in an effective learning rate decrease.

In this case, `nn.Dropout3d()` will help promote independence between feature maps and should be used instead.

W
wizardforcel 已提交
4680
Parameters: 
W
wizardforcel 已提交
4681 4682 4683 4684

*   **p** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – probability of an element to be zeroed.
*   **inplace** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – If set to `True`, will do this operation in-place

W
wizardforcel 已提交
4685

W
wizardforcel 已提交
4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705

```py
Shape:
```

*   Input: ![](img/f5a45f7b445db562b21cfcb525637aab.jpg)
*   Output: ![](img/f5a45f7b445db562b21cfcb525637aab.jpg) (same shape as input)

Examples:

```py
>>> m = nn.Dropout3d(p=0.2)
>>> input = torch.randn(20, 16, 4, 32, 32)
>>> output = m(input)

```

### AlphaDropout

```py
W
wizardforcel 已提交
4706
class torch.nn.AlphaDropout(p=0.5, inplace=False)
W
wizardforcel 已提交
4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718
```

Applies Alpha Dropout over the input.

Alpha Dropout is a type of Dropout that maintains the self-normalizing property. For an input with zero mean and unit standard deviation, the output of Alpha Dropout maintains the original mean and standard deviation of the input. Alpha Dropout goes hand-in-hand with SELU activation function, which ensures that the outputs have zero mean and unit standard deviation.

During training, it randomly masks some of the elements of the input tensor with probability _p_ using samples from a bernoulli distribution. The elements to masked are randomized on every forward call, and scaled and shifted to maintain zero mean and unit standard deviation.

During evaluation the module simply computes an identity function.

More details can be found in the paper [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515) .

W
wizardforcel 已提交
4719
Parameters: 
W
wizardforcel 已提交
4720 4721 4722 4723

*   **p** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")) – probability of an element to be dropped. Default: 0.5
*   **inplace** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – If set to `True`, will do this operation in-place

W
wizardforcel 已提交
4724

W
wizardforcel 已提交
4725 4726 4727 4728 4729

```py
Shape:
```

W
wizardforcel 已提交
4730 4731
*   Input: `Any`. Input can be of any shape
*   Output: `Same`. Output is of the same shape as input
W
wizardforcel 已提交
4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746

Examples:

```py
>>> m = nn.AlphaDropout(p=0.2)
>>> input = torch.randn(20, 16)
>>> output = m(input)

```

## Sparse layers

### Embedding

```py
W
wizardforcel 已提交
4747
class torch.nn.Embedding(num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False, _weight=None)
W
wizardforcel 已提交
4748 4749 4750 4751 4752 4753
```

A simple lookup table that stores embeddings of a fixed dictionary and size.

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

W
wizardforcel 已提交
4754
Parameters: 
W
wizardforcel 已提交
4755 4756 4757 4758 4759 4760 4761 4762 4763

*   **num_embeddings** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – size of the dictionary of embeddings
*   **embedding_dim** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – the size of each embedding vector
*   **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`.
*   **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` matrix will be a sparse tensor. See Notes for more details regarding sparse gradients.

W
wizardforcel 已提交
4764

W
wizardforcel 已提交
4765 4766 4767 4768 4769 4770
| Variables: | **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – the learnable weights of the module of shape (num_embeddings, embedding_dim) initialized from ![](img/dd84ddbf2f8040d87fb315eeeba51f6d.jpg) |
| --- | --- |

Shape:

> *   Input: LongTensor of arbitrary shape containing the indices to extract
W
wizardforcel 已提交
4771
> *   Output: `(*, embedding_dim)`, where `*` is the input shape
W
wizardforcel 已提交
4772 4773 4774

Note

W
wizardforcel 已提交
4775
Keep in mind that only a limited number of optimizers support sparse gradients: currently it’s `optim.SGD` (`CUDA` and `CPU`), `optim.SparseAdam` (`CUDA` and `CPU`) and `optim.Adagrad` (`CPU`)
W
wizardforcel 已提交
4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810

Note

With `padding_idx` set, the embedding vector at `padding_idx` is initialized to all zeros. However, note that this vector can be modified afterwards, e.g., using a customized initialization method, and thus changing the vector used to pad the output. The gradient for this vector from [`Embedding`](#torch.nn.Embedding "torch.nn.Embedding") is always zero.

Examples:

```py
>>> # an Embedding module containing 10 tensors of size 3
>>> embedding = nn.Embedding(10, 3)
>>> # a batch of 2 samples of 4 indices each
>>> input = torch.LongTensor([[1,2,4,5],[4,3,2,9]])
>>> embedding(input)
tensor([[[-0.0251, -1.6902,  0.7172],
 [-0.6431,  0.0748,  0.6969],
 [ 1.4970,  1.3448, -0.9685],
 [-0.3677, -2.7265, -0.1685]],

 [[ 1.4970,  1.3448, -0.9685],
 [ 0.4362, -0.4004,  0.9400],
 [-0.6431,  0.0748,  0.6969],
 [ 0.9124, -2.3616,  1.1151]]])

>>> # example with padding_idx
>>> embedding = nn.Embedding(10, 3, padding_idx=0)
>>> input = torch.LongTensor([[0,2,0,5]])
>>> embedding(input)
tensor([[[ 0.0000,  0.0000,  0.0000],
 [ 0.1535, -2.0309,  0.9315],
 [ 0.0000,  0.0000,  0.0000],
 [-0.1655,  0.9897,  0.0635]]])

```

```py
W
wizardforcel 已提交
4811
classmethod from_pretrained(embeddings, freeze=True, sparse=False)
W
wizardforcel 已提交
4812 4813 4814 4815
```

Creates Embedding instance from given 2-dimensional FloatTensor.

W
wizardforcel 已提交
4816
Parameters: 
W
wizardforcel 已提交
4817 4818 4819 4820 4821

*   **embeddings** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – FloatTensor containing weights for the Embedding. First dimension is being passed to Embedding as ‘num_embeddings’, second as ‘embedding_dim’.
*   **freeze** (_boolean__,_ _optional_) – If `True`, the tensor does not get updated in the learning process. Equivalent to `embedding.weight.requires_grad = False`. Default: `True`
*   **sparse** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – if `True`, gradient w.r.t. weight matrix will be a sparse tensor. See Notes for more details regarding sparse gradients.

W
wizardforcel 已提交
4822

W
wizardforcel 已提交
4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839

Examples:

```py
>>> # FloatTensor containing pretrained weights
>>> weight = torch.FloatTensor([[1, 2.3, 3], [4, 5.1, 6.3]])
>>> embedding = nn.Embedding.from_pretrained(weight)
>>> # Get embeddings for index 1
>>> input = torch.LongTensor([1])
>>> embedding(input)
tensor([[ 4.0000,  5.1000,  6.3000]])

```

### EmbeddingBag

```py
W
wizardforcel 已提交
4840
class torch.nn.EmbeddingBag(num_embeddings, embedding_dim, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, mode='mean', sparse=False)
W
wizardforcel 已提交
4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852
```

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

For bags of constant length, this class

> *   with `mode="sum"` is equivalent to [`Embedding`](#torch.nn.Embedding "torch.nn.Embedding") followed by `torch.sum(dim=1)`,
> *   with `mode="mean"` is equivalent to [`Embedding`](#torch.nn.Embedding "torch.nn.Embedding") followed by `torch.mean(dim=1)`,
> *   with `mode="max"` is equivalent to [`Embedding`](#torch.nn.Embedding "torch.nn.Embedding") followed by `torch.max(dim=1)`.

However, [`EmbeddingBag`](#torch.nn.EmbeddingBag "torch.nn.EmbeddingBag") is much more time and memory efficient than using a chain of these operations.

W
wizardforcel 已提交
4853
Parameters: 
W
wizardforcel 已提交
4854 4855 4856 4857 4858 4859 4860 4861 4862

*   **num_embeddings** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – size of the dictionary of embeddings
*   **embedding_dim** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – the size of each embedding vector
*   **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`.
*   **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`. Note: this option is not supported when `mode="max"`.
*   **mode** (_string__,_ _optional_) – `"sum"`, `"mean"` or `"max"`. Specifies the way to reduce the bag. Default: `"mean"`
*   **sparse** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – if `True`, gradient w.r.t. `weight` matrix will be a sparse tensor. See Notes for more details regarding sparse gradients. Note: this option is not supported when `mode="max"`.

W
wizardforcel 已提交
4863

W
wizardforcel 已提交
4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902
| Variables: | **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – the learnable weights of the module of shape `(num_embeddings x embedding_dim)` initialized from ![](img/dd84ddbf2f8040d87fb315eeeba51f6d.jpg). |
| --- | --- |

Inputs: `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.

Output shape: `B x embedding_dim`

Examples:

```py
>>> # an Embedding module containing 10 tensors of size 3
>>> embedding_sum = nn.EmbeddingBag(10, 3, mode='sum')
>>> # a batch of 2 samples of 4 indices each
>>> input = torch.LongTensor([1,2,4,5,4,3,2,9])
>>> offsets = torch.LongTensor([0,4])
>>> embedding_sum(input, offsets)
tensor([[-0.8861, -5.4350, -0.0523],
 [ 1.1306, -2.5798, -1.0044]])

```

## Distance functions

### CosineSimilarity

```py
W
wizardforcel 已提交
4903
class torch.nn.CosineSimilarity(dim=1, eps=1e-08)
W
wizardforcel 已提交
4904 4905 4906 4907 4908 4909
```

Returns cosine similarity between ![](img/abdadb44ea35aecb39004dd7f55d9543.jpg) and ![](img/88fdc6eeb68ef4aacf7cd6bd43fa176e.jpg), computed along dim.

![](img/93f92bee7ec6c9e48618f7c929ab51e3.jpg)

W
wizardforcel 已提交
4910
Parameters: 
W
wizardforcel 已提交
4911 4912 4913 4914

*   **dim** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – Dimension where cosine similarity is computed. Default: 1
*   **eps** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – Small value to avoid division by zero. Default: 1e-8

W
wizardforcel 已提交
4915

W
wizardforcel 已提交
4916 4917 4918 4919 4920

```py
Shape:
```

W
wizardforcel 已提交
4921
*   Input1: ![](img/c2101d997ef86641ad9f92513b080e8a.jpg) where D is at position `dim`
W
wizardforcel 已提交
4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937
*   Input2: ![](img/c2101d997ef86641ad9f92513b080e8a.jpg), same shape as the Input1
*   Output: ![](img/999c5fb65c1a9ba017a0d60c030400c5.jpg)

Examples:

```py
>>> input1 = torch.randn(100, 128)
>>> input2 = torch.randn(100, 128)
>>> cos = nn.CosineSimilarity(dim=1, eps=1e-6)
>>> output = cos(input1, input2)

```

### PairwiseDistance

```py
W
wizardforcel 已提交
4938
class torch.nn.PairwiseDistance(p=2.0, eps=1e-06, keepdim=False)
W
wizardforcel 已提交
4939 4940 4941 4942 4943 4944
```

Computes the batchwise pairwise distance between vectors ![](img/2f0f406e2d42300da1a9891d89381576.jpg), ![](img/60787776d6fd54b3adfd3762b910bd3f.jpg) using the p-norm:

![](img/4206b08d53423c6d6f77c51751d33cae.jpg)

W
wizardforcel 已提交
4945
Parameters: 
W
wizardforcel 已提交
4946 4947 4948 4949 4950

*   **p** (_real_) – the norm degree. Default: 2
*   **eps** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – Small value to avoid division by zero. Default: 1e-6
*   **keepdim** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – Determines whether or not to keep the batch dimension. Default: False

W
wizardforcel 已提交
4951

W
wizardforcel 已提交
4952 4953 4954 4955 4956

```py
Shape:
```

W
wizardforcel 已提交
4957
*   Input1: ![](img/3dc464d2e10c731f17264e33e497c1a8.jpg) where `D = vector dimension`
W
wizardforcel 已提交
4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975
*   Input2: ![](img/3dc464d2e10c731f17264e33e497c1a8.jpg), same shape as the Input1
*   Output: ![](img/2a3e2b832e04fe8d66596083b23da518.jpg). If `keepdim` is `False`, then ![](img/f1b7cdb5b976f1adde1e8b2850a1c127.jpg).

Examples:

```py
>>> pdist = nn.PairwiseDistance(p=2)
>>> input1 = torch.randn(100, 128)
>>> input2 = torch.randn(100, 128)
>>> output = pdist(input1, input2)

```

## Loss functions

### L1Loss

```py
W
wizardforcel 已提交
4976
class torch.nn.L1Loss(size_average=None, reduce=None, reduction='mean')
W
wizardforcel 已提交
4977 4978
```

W
wizardforcel 已提交
4979
Creates a criterion that measures the mean absolute error (MAE) between each element in the input `x` and target `y`.
W
wizardforcel 已提交
4980 4981 4982 4983 4984 4985 4986 4987 4988

The loss can be described as:

![](img/415564bfa6c89ba182a02fe2a3d0ca49.jpg)

where ![](img/9341d9048ac485106d2b2ee8de14876f.jpg) is the batch size. If reduce is `True`, then:

![](img/dd1952e377a9b618cc6538b18165a417.jpg)

W
wizardforcel 已提交
4989
`x` and `y` are tensors of arbitrary shapes with a total of `n` elements each.
W
wizardforcel 已提交
4990

W
wizardforcel 已提交
4991
The sum operation still operates over all the elements, and divides by `n`.
W
wizardforcel 已提交
4992

W
wizardforcel 已提交
4993
The division by `n` can be avoided if one sets the constructor argument `size_average=False`.
W
wizardforcel 已提交
4994

W
wizardforcel 已提交
4995
Parameters: 
W
wizardforcel 已提交
4996 4997 4998 4999 5000

*   **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`. Default: `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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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`. Default: ‘mean’

W
wizardforcel 已提交
5001

W
wizardforcel 已提交
5002 5003 5004 5005 5006

```py
Shape:
```

W
wizardforcel 已提交
5007
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024
*   Target: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input
*   Output: scalar. If reduce is `False`, then ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

Examples:

```py
>>> loss = nn.L1Loss()
>>> input = torch.randn(3, 5, requires_grad=True)
>>> target = torch.randn(3, 5)
>>> output = loss(input, target)
>>> output.backward()

```

### MSELoss

```py
W
wizardforcel 已提交
5025
class torch.nn.MSELoss(size_average=None, reduce=None, reduction='mean')
W
wizardforcel 已提交
5026 5027
```

W
wizardforcel 已提交
5028
Creates a criterion that measures the mean squared error (squared L2 norm) between each element in the input `x` and target `y`.
W
wizardforcel 已提交
5029 5030 5031 5032 5033 5034 5035 5036 5037

The loss can be described as:

![](img/e67b64ef5017709a433d1214a681717e.jpg)

where ![](img/9341d9048ac485106d2b2ee8de14876f.jpg) is the batch size. If reduce is `True`, then:

![](img/f3a00c026a75843dd3a04c64f9cecb47.jpg)

W
wizardforcel 已提交
5038
The sum operation still operates over all the elements, and divides by `n`.
W
wizardforcel 已提交
5039

W
wizardforcel 已提交
5040
The division by `n` can be avoided if one sets `size_average` to `False`.
W
wizardforcel 已提交
5041

W
wizardforcel 已提交
5042
To get a batch of losses, a loss per batch element, set `reduce` to `False`. These losses are not averaged and are not affected by `size_average`.
W
wizardforcel 已提交
5043

W
wizardforcel 已提交
5044
Parameters: 
W
wizardforcel 已提交
5045 5046 5047 5048 5049

*   **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`. Default: `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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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`. Default: ‘mean’

W
wizardforcel 已提交
5050

W
wizardforcel 已提交
5051 5052 5053 5054 5055

```py
Shape:
```

W
wizardforcel 已提交
5056
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072
*   Target: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

Examples:

```py
>>> loss = nn.MSELoss()
>>> input = torch.randn(3, 5, requires_grad=True)
>>> target = torch.randn(3, 5)
>>> output = loss(input, target)
>>> output.backward()

```

### CrossEntropyLoss

```py
W
wizardforcel 已提交
5073
class torch.nn.CrossEntropyLoss(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean')
W
wizardforcel 已提交
5074 5075 5076 5077
```

This criterion combines `nn.LogSoftmax()` and `nn.NLLLoss()` in one single class.

W
wizardforcel 已提交
5078
It is useful when training a classification problem with `C` classes. If provided, the optional argument `weight` should be a 1D `Tensor` assigning weight to each of the classes. This is particularly useful when you have an unbalanced training set.
W
wizardforcel 已提交
5079

W
wizardforcel 已提交
5080
The `input` is expected to contain scores for each class.
W
wizardforcel 已提交
5081

W
wizardforcel 已提交
5082
`input` has to be a Tensor of size either ![](img/cca0c8da541b81bec031e4e52161d2c7.jpg) or ![](img/f30f7531b252dc52c6bb945ebb508cc4.jpg) with ![](img/6573879e7d2cf58e8dfdbf8baa9f7a1a.jpg) for the `K`-dimensional case (described later).
W
wizardforcel 已提交
5083

W
wizardforcel 已提交
5084
This criterion expects a class index (0 to `C-1`) as the `target` for each value of a 1D tensor of size `minibatch`
W
wizardforcel 已提交
5085 5086 5087 5088 5089

The loss can be described as:

![](img/29028e6a28821a298d2a456d6bb175f9.jpg)

W
wizardforcel 已提交
5090
or in the case of the `weight` argument being specified:
W
wizardforcel 已提交
5091 5092 5093 5094 5095 5096 5097

![](img/bc344720164c2bc94ebd3f405b898216.jpg)

The losses are averaged across observations for each minibatch.

Can also be used for higher dimension inputs, such as 2D images, by providing an input of size ![](img/f30f7531b252dc52c6bb945ebb508cc4.jpg) with ![](img/6573879e7d2cf58e8dfdbf8baa9f7a1a.jpg), where ![](img/a5db490cd70a38a0bb9f3de58c51589f.jpg) is the number of dimensions, and a target of appropriate shape (see below).

W
wizardforcel 已提交
5098
Parameters: 
W
wizardforcel 已提交
5099

W
wizardforcel 已提交
5100
*   **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`
W
wizardforcel 已提交
5101
*   **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`. Default: `True`
W
wizardforcel 已提交
5102
*   **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.
W
wizardforcel 已提交
5103 5104 5105
*   **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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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`. Default: ‘mean’

W
wizardforcel 已提交
5106

W
wizardforcel 已提交
5107 5108 5109 5110 5111 5112 5113 5114 5115

```py
Shape:
```

*   ```py
    Input: \((N, C)\) where C = number of classes, or
    ```

W
wizardforcel 已提交
5116
    ![](img/ddeb501040934760370435d1c223e6b6.jpg) with ![](img/6573879e7d2cf58e8dfdbf8baa9f7a1a.jpg) in the case of `K`-dimensional loss.
W
wizardforcel 已提交
5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141
*   ```py
    Target: \((N)\) where each value is \(0 \leq \text{targets}[i] \leq C-1\), or
    ```

    ![](img/5981db74a9cd434c7580e6ba530e21b6.jpg) with ![](img/6573879e7d2cf58e8dfdbf8baa9f7a1a.jpg) in the case of K-dimensional loss.
*   ```py
    Output: scalar. If reduce is False, then the same size
    ```

    as the target: ![](img/2a3e2b832e04fe8d66596083b23da518.jpg), or ![](img/5981db74a9cd434c7580e6ba530e21b6.jpg) with ![](img/6573879e7d2cf58e8dfdbf8baa9f7a1a.jpg) in the case of K-dimensional loss.

Examples:

```py
>>> loss = nn.CrossEntropyLoss()
>>> input = torch.randn(3, 5, requires_grad=True)
>>> target = torch.empty(3, dtype=torch.long).random_(5)
>>> output = loss(input, target)
>>> output.backward()

```

### CTCLoss

```py
W
wizardforcel 已提交
5142
class torch.nn.CTCLoss(blank=0, reduction='mean')
W
wizardforcel 已提交
5143 5144 5145 5146
```

The Connectionist Temporal Classification loss.

W
wizardforcel 已提交
5147
Parameters: 
W
wizardforcel 已提交
5148 5149 5150 5151

*   **blank** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – blank label. Default ![](img/28256dd5af833c877d63bfabfaa7b301.jpg).
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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. Default: ‘mean’

W
wizardforcel 已提交
5152

W
wizardforcel 已提交
5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202

```py
Inputs:
```

```py
log_probs: Tensor of size \((T, N, C)\) where C = number of characters in alphabet including blank,
```

<cite>T = input length</cite>, and <cite>N = batch size</cite>. 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")).

```py
targets: Tensor of size \((N, S)\) or (sum(target_lengths)).
```

Targets (cannot be blank). In the second form, the targets are assumed to be concatenated.

```py
input_lengths: Tuple or tensor of size \((N)\).
```

Lengths of the inputs (must each be ![](img/0063f9a7d145aadc1082a0c4c8712a62.jpg))

```py
target_lengths: Tuple or tensor of size  \((N)\).
```

Lengths of the targets

Example:

```py
>>> ctc_loss = nn.CTCLoss()
>>> 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 = ctc_loss(log_probs, targets, input_lengths, target_lengths)
>>> loss.backward()

```

```py
Reference:
```

A. Graves et al.: Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural Networks: [https://www.cs.toronto.edu/~graves/icml_2006.pdf](https://www.cs.toronto.edu/~graves/icml_2006.pdf)

Note

W
wizardforcel 已提交
5203
In order to use CuDNN, the following must be satisfied: `targets` must be in concatenated format, all `input_lengths` must be `T`. ![](img/e465f6009cd227a31d00f005c2cb1c5b.jpg), `target_lengths` ![](img/3a2535723ad2261fbfc71d099a993883.jpg), the integer arguments must be of dtype `torch.int32`.
W
wizardforcel 已提交
5204

W
wizardforcel 已提交
5205
The regular implementation uses the (more common in PyTorch) `torch.long` dtype.
W
wizardforcel 已提交
5206 5207 5208 5209 5210 5211 5212 5213

Note

In some circumstances when using the CUDA backend with CuDNN, this operator may select a nondeterministic algorithm to increase performance. If this is undesirable, you can try to make the operation deterministic (potentially at a performance cost) by setting `torch.backends.cudnn.deterministic = True`. Please see the notes on [Reproducibility](notes/randomness.html) for background.

### NLLLoss

```py
W
wizardforcel 已提交
5214
class torch.nn.NLLLoss(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean')
W
wizardforcel 已提交
5215 5216
```

W
wizardforcel 已提交
5217
The negative log likelihood loss. It is useful to train a classification problem with `C` classes.
W
wizardforcel 已提交
5218

W
wizardforcel 已提交
5219
If provided, the optional argument `weight` should be a 1D Tensor assigning weight to each of the classes. This is particularly useful when you have an unbalanced training set.
W
wizardforcel 已提交
5220

W
wizardforcel 已提交
5221
The input given through a forward call is expected to contain log-probabilities of each class. `input` has to be a Tensor of size either ![](img/cca0c8da541b81bec031e4e52161d2c7.jpg) or ![](img/f30f7531b252dc52c6bb945ebb508cc4.jpg) with ![](img/6573879e7d2cf58e8dfdbf8baa9f7a1a.jpg) for the `K`-dimensional case (described later).
W
wizardforcel 已提交
5222

W
wizardforcel 已提交
5223
Obtaining log-probabilities in a neural network is easily achieved by adding a `LogSoftmax` layer in the last layer of your network. You may use `CrossEntropyLoss` instead, if you prefer not to add an extra layer.
W
wizardforcel 已提交
5224

W
wizardforcel 已提交
5225
The target that this loss expects is a class index `(0 to C-1, where C = number of classes)`
W
wizardforcel 已提交
5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236

If `reduce` is `False`, the loss can be described as:

![](img/edf1079de0e5df9633d0de83b68250f2.jpg)

where ![](img/9341d9048ac485106d2b2ee8de14876f.jpg) is the batch size. If `reduce` is `True` (default), then

![](img/6eeb4eee2867f6565cb78f3d2e8503f2.jpg)

Can also be used for higher dimension inputs, such as 2D images, by providing an input of size ![](img/f30f7531b252dc52c6bb945ebb508cc4.jpg) with ![](img/6573879e7d2cf58e8dfdbf8baa9f7a1a.jpg), where ![](img/a5db490cd70a38a0bb9f3de58c51589f.jpg) is the number of dimensions, and a target of appropriate shape (see below). In the case of images, it computes NLL loss per-pixel.

W
wizardforcel 已提交
5237
Parameters: 
W
wizardforcel 已提交
5238

W
wizardforcel 已提交
5239
*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_,_ _optional_) – a manual rescaling weight given to each class. If given, it has to be a Tensor of size `C`. Otherwise, it is treated as if having all ones.
W
wizardforcel 已提交
5240 5241 5242 5243 5244
*   **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`. Default: `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.
*   **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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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`. Default: ‘mean’

W
wizardforcel 已提交
5245

W
wizardforcel 已提交
5246 5247 5248 5249 5250 5251 5252 5253 5254

```py
Shape:
```

*   ```py
    Input: \((N, C)\) where C = number of classes, or
    ```

W
wizardforcel 已提交
5255
    ![](img/ddeb501040934760370435d1c223e6b6.jpg) with ![](img/6573879e7d2cf58e8dfdbf8baa9f7a1a.jpg) in the case of `K`-dimensional loss.
W
wizardforcel 已提交
5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296
*   ```py
    Target: \((N)\) where each value is \(0 \leq \text{targets}[i] \leq C-1\), or
    ```

    ![](img/5981db74a9cd434c7580e6ba530e21b6.jpg) with ![](img/6573879e7d2cf58e8dfdbf8baa9f7a1a.jpg) in the case of K-dimensional loss.
*   ```py
    Output: scalar. If reduce is False, then the same size
    ```

    as the target: ![](img/2a3e2b832e04fe8d66596083b23da518.jpg), or ![](img/5981db74a9cd434c7580e6ba530e21b6.jpg) with ![](img/6573879e7d2cf58e8dfdbf8baa9f7a1a.jpg) in the case of K-dimensional loss.

Examples:

```py
>>> m = nn.LogSoftmax()
>>> loss = nn.NLLLoss()
>>> # 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 = loss(m(input), target)
>>> output.backward()
>>>
>>>
>>> # 2D loss example (used, for example, with image inputs)
>>> N, C = 5, 4
>>> loss = nn.NLLLoss()
>>> # input is of size N x C x height x width
>>> data = torch.randn(N, 16, 10, 10)
>>> conv = nn.Conv2d(16, C, (3, 3))
>>> m = nn.LogSoftmax()
>>> # each element in target has to have 0 <= value < C
>>> target = torch.empty(N, 8, 8, dtype=torch.long).random_(0, C)
>>> output = loss(m(conv(data)), target)
>>> output.backward()

```

### PoissonNLLLoss

```py
W
wizardforcel 已提交
5297
class torch.nn.PoissonNLLLoss(log_input=True, full=False, size_average=None, eps=1e-08, reduce=None, reduction='mean')
W
wizardforcel 已提交
5298 5299 5300 5301 5302 5303 5304 5305 5306 5307
```

Negative log likelihood loss with Poisson distribution of target.

The loss can be described as:

![](img/f50aaec015c8f6f2ef26d16a60023ea1.jpg)

The last term can be omitted or approximated with Stirling formula. The approximation is used for target values more than 1\. For targets less or equal to 1 zeros are added to the loss.

W
wizardforcel 已提交
5308
Parameters: 
W
wizardforcel 已提交
5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321

*   **log_input** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – if `True` the loss is computed as ![](img/18729f59c6d4705e1945b3d7b3e09e32.jpg), if `False` the loss is ![](img/036591dc90f1dafaa138920518e2b05b.jpg).
*   **full** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) –

    whether to compute full loss, i. e. to add the Stirling approximation term

    ![](img/b063f11c809ea98839d91fc34d0b4bf0.jpg)

*   **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`. Default: `True`
*   **eps** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – Small value to avoid evaluation of ![](img/f6dcd4f69520c309a6d71002bd330cb8.jpg) when `log_input == False`. Default: 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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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`. Default: ‘mean’

W
wizardforcel 已提交
5322

W
wizardforcel 已提交
5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337

Examples:

```py
>>> loss = nn.PoissonNLLLoss()
>>> log_input = torch.randn(5, 2, requires_grad=True)
>>> target = torch.randn(5, 2)
>>> output = loss(log_input, target)
>>> output.backward()

```

### KLDivLoss

```py
W
wizardforcel 已提交
5338
class torch.nn.KLDivLoss(size_average=None, reduce=None, reduction='mean')
W
wizardforcel 已提交
5339 5340 5341 5342 5343 5344
```

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

KL divergence is a useful distance measure for continuous distributions and is often useful when performing direct regression over the space of (discretely sampled) continuous output distributions.

W
wizardforcel 已提交
5345
As with [`NLLLoss`](#torch.nn.NLLLoss "torch.nn.NLLLoss"), the `input` given is expected to contain _log-probabilities_. However, unlike [`NLLLoss`](#torch.nn.NLLLoss "torch.nn.NLLLoss"), `input` is not restricted to a 2D Tensor. The targets are given as _probabilities_ (i.e. without taking the logarithm).
W
wizardforcel 已提交
5346

W
wizardforcel 已提交
5347
This criterion expects a `target` `Tensor` of the same size as the `input` `Tensor`.
W
wizardforcel 已提交
5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358

The unreduced (i.e. with `reduce` set to `False`) loss can be described as:

![](img/eba993f61a08816ebd5f577851d521f2.jpg)

where the index ![](img/9341d9048ac485106d2b2ee8de14876f.jpg) spans all dimensions of `input` and ![](img/db4a9fef02111450bf98261889de550c.jpg) has the same shape as `input`. If `reduce` is `True` (the default), then:

![](img/d88944e162eff94bddc1b9a94bcaa3a6.jpg)

In default reduction mode ‘mean’, the losses are averaged for each minibatch over observations **as well as** over dimensions. ‘batchmean’ mode gives the correct KL divergence where losses are averaged over batch dimension only. ‘mean’ mode’s behavior will be changed to the same as ‘batchmean’ in the next major release.

W
wizardforcel 已提交
5359
Parameters: 
W
wizardforcel 已提交
5360 5361 5362 5363 5364

*   **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`. Default: `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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘batchmean’ &#124; ‘sum’ &#124; ‘mean’. ‘none’: no reduction will be applied. ‘batchmean’: the sum of the output will be divided by batchsize. ‘sum’: the output will be summed. ‘mean’: the output will be divided by the number of elements in the output. Default: ‘mean’

W
wizardforcel 已提交
5365

W
wizardforcel 已提交
5366

W
wizardforcel 已提交
5367
: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.
W
wizardforcel 已提交
5368 5369 5370 5371 5372 5373 5374

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

```py
Shape:
```

W
wizardforcel 已提交
5375
*   input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
5376 5377 5378 5379 5380 5381 5382 5383 5384 5385
*   target: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input
*   ```py
    output: scalar by default. If reduce is False, then \((N, *)\),
    ```

    the same shape as the input

### BCELoss

```py
W
wizardforcel 已提交
5386
class torch.nn.BCELoss(weight=None, size_average=None, reduce=None, reduction='mean')
W
wizardforcel 已提交
5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398
```

Creates a criterion that measures the Binary Cross Entropy between the target and the output:

The loss can be described as:

![](img/f233882012c0c24fcad1869a163b5b7c.jpg)

where ![](img/9341d9048ac485106d2b2ee8de14876f.jpg) is the batch size. If reduce is `True`, then

![](img/d88944e162eff94bddc1b9a94bcaa3a6.jpg)

W
wizardforcel 已提交
5399
This is used for measuring the error of a reconstruction in for example an auto-encoder. Note that the targets `y` should be numbers between 0 and 1.
W
wizardforcel 已提交
5400

W
wizardforcel 已提交
5401
Parameters: 
W
wizardforcel 已提交
5402 5403 5404 5405 5406 5407

*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_,_ _optional_) – a manual rescaling weight given to the loss of each batch element. If given, has to be a Tensor of size “nbatch”.
*   **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`. Default: `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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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`. Default: ‘mean’

W
wizardforcel 已提交
5408

W
wizardforcel 已提交
5409 5410 5411 5412 5413

```py
Shape:
```

W
wizardforcel 已提交
5414
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
5415
*   Target: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input
W
wizardforcel 已提交
5416
*   Output: scalar. If `reduce` is False, then `(N, *)`, same shape as input.
W
wizardforcel 已提交
5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432

Examples:

```py
>>> m = nn.Sigmoid()
>>> loss = nn.BCELoss()
>>> input = torch.randn(3, requires_grad=True)
>>> target = torch.empty(3).random_(2)
>>> output = loss(m(input), target)
>>> output.backward()

```

### BCEWithLogitsLoss

```py
W
wizardforcel 已提交
5433
class torch.nn.BCEWithLogitsLoss(weight=None, size_average=None, reduce=None, reduction='mean', pos_weight=None)
W
wizardforcel 已提交
5434 5435
```

W
wizardforcel 已提交
5436
This loss combines a `Sigmoid` layer and the `BCELoss` in one single class. This version is more numerically stable than using a plain `Sigmoid` followed by a `BCELoss` as, by combining the operations into one layer, we take advantage of the log-sum-exp trick for numerical stability.
W
wizardforcel 已提交
5437 5438 5439 5440 5441 5442 5443 5444 5445

The loss can be described as:

![](img/0c49aad6f81ec7936e313096f7a53f97.jpg)

where ![](img/9341d9048ac485106d2b2ee8de14876f.jpg) is the batch size. If reduce is `True`, then

![](img/0a16102d9320f70f18d7c8b152000489.jpg)

W
wizardforcel 已提交
5446
This is used for measuring the error of a reconstruction in for example an auto-encoder. Note that the targets `t[i]` should be numbers between 0 and 1.
W
wizardforcel 已提交
5447 5448 5449 5450 5451 5452 5453

It’s possible to trade off recall and precision by adding weights to positive examples. In this case the loss can be described as:

![](img/d5ca42e0ee1490d1dea4d5f38cc120d7.jpg)

where ![](img/76dc369e067e5fa42a4b32b6afd5e570.jpg) is the positive weight of class ![](img/493731e423d5db62086d0b8705dda0c8.jpg). ![](img/65abc7465f8ac5056f8562962f0ae02e.jpg) increases the recall, ![](img/989afd86a6407cf24295ae8d52ff0080.jpg) increases the precision.

W
wizardforcel 已提交
5454
For example, if a dataset contains 100 positive and 300 negative examples of a single class, then `pos_weight` for the class should be equal to ![](img/6a003751ded2d5e5198d93ee7db1ba5d.jpg). The loss would act as if the dataset contains ![](img/fb2ad75ea1ac3ba3ae507a3c8a34db12.jpg) positive examples.
W
wizardforcel 已提交
5455

W
wizardforcel 已提交
5456
Parameters: 
W
wizardforcel 已提交
5457 5458 5459 5460 5461 5462 5463

*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_,_ _optional_) – a manual rescaling weight given to the loss of each batch element. If given, has to be a Tensor of size “nbatch”.
*   **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`. Default: `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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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`. Default: ‘mean’
*   **pos_weight** – a weight of positive examples. Must be a vector with length equal to the number of classes.

W
wizardforcel 已提交
5464

W
wizardforcel 已提交
5465 5466 5467 5468

### MarginRankingLoss

```py
W
wizardforcel 已提交
5469
class torch.nn.MarginRankingLoss(margin=0.0, size_average=None, reduce=None, reduction='mean')
W
wizardforcel 已提交
5470 5471
```

W
wizardforcel 已提交
5472
Creates a criterion that measures the loss given inputs `x1`, `x2`, two 1D mini-batch `Tensor`s, and a label 1D mini-batch tensor `y` with values (`1` or `-1`).
W
wizardforcel 已提交
5473

W
wizardforcel 已提交
5474
If `y == 1` then it assumed the first input should be ranked higher (have a larger value) than the second input, and vice-versa for `y == -1`.
W
wizardforcel 已提交
5475 5476 5477 5478 5479

The loss function for each sample in the mini-batch is:

![](img/1664f71bed4b6591f02c8bbb10f2d389.jpg)

W
wizardforcel 已提交
5480
Parameters: 
W
wizardforcel 已提交
5481

W
wizardforcel 已提交
5482
*   **margin** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – Has a default value of `0`.
W
wizardforcel 已提交
5483 5484 5485 5486
*   **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`. Default: `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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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`. Default: ‘mean’

W
wizardforcel 已提交
5487

W
wizardforcel 已提交
5488 5489 5490 5491 5492

```py
Shape:
```

W
wizardforcel 已提交
5493
*   Input: ![](img/3dc464d2e10c731f17264e33e497c1a8.jpg) where `N` is the batch size and `D` is the size of a sample.
W
wizardforcel 已提交
5494
*   Target: ![](img/2a3e2b832e04fe8d66596083b23da518.jpg)
W
wizardforcel 已提交
5495
*   Output: scalar. If `reduce` is False, then `(N)`.
W
wizardforcel 已提交
5496 5497 5498 5499

### HingeEmbeddingLoss

```py
W
wizardforcel 已提交
5500
class torch.nn.HingeEmbeddingLoss(margin=1.0, size_average=None, reduce=None, reduction='mean')
W
wizardforcel 已提交
5501 5502
```

W
wizardforcel 已提交
5503
Measures the loss given an input tensor `x` and a labels tensor `y` containing values (`1` or `-1`). This is usually used for measuring whether two inputs are similar or dissimilar, e.g. using the L1 pairwise distance as `x`, and is typically used for learning nonlinear embeddings or semi-supervised learning.
W
wizardforcel 已提交
5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514

The loss function for ![](img/493731e423d5db62086d0b8705dda0c8.jpg)-th sample in the mini-batch is

![](img/1e176ed632f1cbc86eb8db4bf6034f24.jpg)

and the total loss functions is

![](img/0a16102d9320f70f18d7c8b152000489.jpg)

where ![](img/97b4908568a8d2f8549d90e683a8efa2.jpg).

W
wizardforcel 已提交
5515
Parameters: 
W
wizardforcel 已提交
5516

W
wizardforcel 已提交
5517
*   **margin** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – Has a default value of `1`.
W
wizardforcel 已提交
5518 5519 5520 5521
*   **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`. Default: `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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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`. Default: ‘mean’

W
wizardforcel 已提交
5522

W
wizardforcel 已提交
5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534

```py
Shape:
```

*   Input: Tensor of arbitrary shape. The sum operation operates over all the elements.
*   Target: Same shape as input.
*   Output: scalar. If reduce is `False`, then same shape as the input

### MultiLabelMarginLoss

```py
W
wizardforcel 已提交
5535
class torch.nn.MultiLabelMarginLoss(size_average=None, reduce=None, reduction='mean')
W
wizardforcel 已提交
5536 5537
```

W
wizardforcel 已提交
5538
Creates a criterion that optimizes a multi-class multi-classification hinge loss (margin-based loss) between input `x` (a 2D mini-batch `Tensor`) and output `y` (which is a 2D `Tensor` of target class indices). For each sample in the mini-batch:
W
wizardforcel 已提交
5539 5540 5541 5542 5543

![](img/f4d7e37a53b15d27b3a25c9dc586cd00.jpg)

where ![](img/b75aa938b45ed55c0aa471218a7224ce.jpg) to ![](img/c915dd214c2340e40ac8e79013465783.jpg), ![](img/4da95e4f78bfe10987f5549ced63a7e6.jpg) to ![](img/ec0f8a278c4b73ccb95d3a4c1d129697.jpg), ![](img/8058aac8e03495c71f75b04169d5baca.jpg), and ![](img/27b5f368a27d1e15b3656796a28a4411.jpg) for all ![](img/31df9c730e19ca29b59dce64b99d98c1.jpg) and ![](img/d8fdd0e28cfb03738fc5227885ee035a.jpg).

W
wizardforcel 已提交
5544
`y` and `x` must have the same size.
W
wizardforcel 已提交
5545 5546 5547 5548 5549

The criterion only considers a contiguous block of non-negative targets that starts at the front.

This allows for different samples to have variable amounts of target classes

W
wizardforcel 已提交
5550
Parameters: 
W
wizardforcel 已提交
5551 5552 5553 5554 5555

*   **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`. Default: `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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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`. Default: ‘mean’

W
wizardforcel 已提交
5556

W
wizardforcel 已提交
5557 5558 5559 5560 5561

```py
Shape:
```

W
wizardforcel 已提交
5562
*   Input: ![](img/861a7d7a604a97f5620afad259a4c26d.jpg) or ![](img/9b9aebaa467ad07dca05b5086bd21ca2.jpg) where `N` is the batch size and `C` is the number of classes.
W
wizardforcel 已提交
5563
*   Target: ![](img/861a7d7a604a97f5620afad259a4c26d.jpg) or ![](img/9b9aebaa467ad07dca05b5086bd21ca2.jpg), same shape as the input.
W
wizardforcel 已提交
5564
*   Output: scalar. If `reduce` is False, then `(N)`.
W
wizardforcel 已提交
5565 5566 5567 5568

### SmoothL1Loss

```py
W
wizardforcel 已提交
5569
class torch.nn.SmoothL1Loss(size_average=None, reduce=None, reduction='mean')
W
wizardforcel 已提交
5570 5571
```

W
wizardforcel 已提交
5572
Creates a criterion that uses a squared term if the absolute element-wise error falls below 1 and an L1 term otherwise. It is less sensitive to outliers than the `MSELoss` and in some cases prevents exploding gradients (e.g. see “Fast R-CNN” paper by Ross Girshick). Also known as the Huber loss:
W
wizardforcel 已提交
5573 5574 5575 5576 5577 5578 5579

![](img/cd503c18d22f0e18a5109f3f13d028b2.jpg)

where ![](img/bbfcb7c1428a33547e15f8853dbe6e4f.jpg) is given by:

![](img/621fa336f1f8b6169430fa6b42a00b6d.jpg)

W
wizardforcel 已提交
5580
`x` and `y` arbitrary shapes with a total of `n` elements each the sum operation still operates over all the elements, and divides by `n`.
W
wizardforcel 已提交
5581

W
wizardforcel 已提交
5582
The division by `n` can be avoided if one sets `size_average` to `False`
W
wizardforcel 已提交
5583

W
wizardforcel 已提交
5584
Parameters: 
W
wizardforcel 已提交
5585 5586 5587 5588 5589

*   **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`. Default: `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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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`. Default: ‘mean’

W
wizardforcel 已提交
5590

W
wizardforcel 已提交
5591 5592 5593 5594 5595

```py
Shape:
```

W
wizardforcel 已提交
5596
*   Input: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg) where `*` means, any number of additional dimensions
W
wizardforcel 已提交
5597 5598 5599 5600 5601 5602
*   Target: ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input
*   Output: scalar. If reduce is `False`, then ![](img/eb7a3f5bc15cc379e78f768e821eb094.jpg), same shape as the input

### SoftMarginLoss

```py
W
wizardforcel 已提交
5603
class torch.nn.SoftMarginLoss(size_average=None, reduce=None, reduction='mean')
W
wizardforcel 已提交
5604 5605
```

W
wizardforcel 已提交
5606
Creates a criterion that optimizes a two-class classification logistic loss between input tensor `x` and target tensor `y` (containing 1 or -1).
W
wizardforcel 已提交
5607 5608 5609

![](img/811f3185227a964c048126484987ef1c.jpg)

W
wizardforcel 已提交
5610
Parameters: 
W
wizardforcel 已提交
5611 5612 5613 5614 5615

*   **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`. Default: `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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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`. Default: ‘mean’

W
wizardforcel 已提交
5616

W
wizardforcel 已提交
5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628

```py
Shape:
```

*   Input: Tensor of arbitrary shape.
*   Target: Same shape as input.
*   Output: scalar. If reduce is `False`, then same shape as the input

### MultiLabelSoftMarginLoss

```py
W
wizardforcel 已提交
5629
class torch.nn.MultiLabelSoftMarginLoss(weight=None, size_average=None, reduce=None, reduction='mean')
W
wizardforcel 已提交
5630 5631
```

W
wizardforcel 已提交
5632
Creates a criterion that optimizes a multi-label one-versus-all loss based on max-entropy, between input `x` and target `y` of size `(N, C)`. For each sample in the minibatch:
W
wizardforcel 已提交
5633 5634 5635

![](img/342414ff43adf5d0fa0b62fcde9538a2.jpg)

W
wizardforcel 已提交
5636
where `i == 0` to `x.nElement()-1`, `y[i] in {0,1}`.
W
wizardforcel 已提交
5637

W
wizardforcel 已提交
5638
Parameters: 
W
wizardforcel 已提交
5639

W
wizardforcel 已提交
5640
*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_,_ _optional_) – a manual rescaling weight given to each class. If given, it has to be a Tensor of size `C`. Otherwise, it is treated as if having all ones.
W
wizardforcel 已提交
5641 5642 5643 5644
*   **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`. Default: `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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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`. Default: ‘mean’

W
wizardforcel 已提交
5645

W
wizardforcel 已提交
5646 5647 5648 5649 5650

```py
Shape:
```

W
wizardforcel 已提交
5651
*   Input: ![](img/9b9aebaa467ad07dca05b5086bd21ca2.jpg) where `N` is the batch size and `C` is the number of classes.
W
wizardforcel 已提交
5652
*   Target: ![](img/9b9aebaa467ad07dca05b5086bd21ca2.jpg), same shape as the input.
W
wizardforcel 已提交
5653
*   Output: scalar. If `reduce` is False, then `(N)`.
W
wizardforcel 已提交
5654 5655 5656 5657

### CosineEmbeddingLoss

```py
W
wizardforcel 已提交
5658
class torch.nn.CosineEmbeddingLoss(margin=0.0, size_average=None, reduce=None, reduction='mean')
W
wizardforcel 已提交
5659 5660
```

W
wizardforcel 已提交
5661
Creates a criterion that measures the loss given input tensors ![](img/abdadb44ea35aecb39004dd7f55d9543.jpg), ![](img/88fdc6eeb68ef4aacf7cd6bd43fa176e.jpg) and a `Tensor` label `y` with values 1 or -1. This is used for measuring whether two inputs are similar or dissimilar, using the cosine distance, and is typically used for learning nonlinear embeddings or semi-supervised learning.
W
wizardforcel 已提交
5662 5663 5664 5665 5666

The loss function for each sample is:

![](img/f894a052d4408e0269216f8b803d074a.jpg)

W
wizardforcel 已提交
5667
Parameters: 
W
wizardforcel 已提交
5668

W
wizardforcel 已提交
5669
*   **margin** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – Should be a number from `-1` to `1`, `0` to `0.5` is suggested. If `margin` is missing, the default value is `0`.
W
wizardforcel 已提交
5670 5671 5672 5673
*   **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`. Default: `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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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`. Default: ‘mean’

W
wizardforcel 已提交
5674

W
wizardforcel 已提交
5675 5676 5677 5678

### MultiMarginLoss

```py
W
wizardforcel 已提交
5679
class torch.nn.MultiMarginLoss(p=1, margin=1.0, weight=None, size_average=None, reduce=None, reduction='mean')
W
wizardforcel 已提交
5680 5681
```

W
wizardforcel 已提交
5682
Creates a criterion that optimizes a multi-class classification hinge loss (margin-based loss) between input `x` (a 2D mini-batch `Tensor`) and output `y` (which is a 1D tensor of target class indices, ![](img/fffe5e09046ebb236f89daa5091946f6.jpg)):
W
wizardforcel 已提交
5683

W
wizardforcel 已提交
5684
For each mini-batch sample, the loss in terms of the 1D input `x` and scalar output `y` is:
W
wizardforcel 已提交
5685 5686 5687

![](img/0f825c52299de2e574d5903469e1af9c.jpg)

W
wizardforcel 已提交
5688
where `i == 0` to `x.size(0)` and ![](img/99e4beebf24a180393aa15ec3740cf3a.jpg).
W
wizardforcel 已提交
5689

W
wizardforcel 已提交
5690
Optionally, you can give non-equal weighting on the classes by passing a 1D `weight` tensor into the constructor.
W
wizardforcel 已提交
5691 5692 5693 5694 5695

The loss function then becomes:

![](img/03b7ccf64bc071a7c2abbeab89f12d08.jpg)

W
wizardforcel 已提交
5696
Parameters: 
W
wizardforcel 已提交
5697

W
wizardforcel 已提交
5698 5699 5700
*   **p** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – Has a default value of `1`. `1` and `2` are the only supported values
*   **margin** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – Has a default value of `1`.
*   **weight** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_,_ _optional_) – a manual rescaling weight given to each class. If given, it has to be a Tensor of size `C`. Otherwise, it is treated as if having all ones.
W
wizardforcel 已提交
5701 5702 5703 5704
*   **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`. Default: `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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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`. Default: ‘mean’

W
wizardforcel 已提交
5705

W
wizardforcel 已提交
5706 5707 5708 5709

### TripletMarginLoss

```py
W
wizardforcel 已提交
5710
class torch.nn.TripletMarginLoss(margin=1.0, p=2.0, eps=1e-06, swap=False, size_average=None, reduce=None, reduction='mean')
W
wizardforcel 已提交
5711 5712
```

W
wizardforcel 已提交
5713
Creates a criterion that measures the triplet loss given an input tensors x1, x2, x3 and a margin with a value greater than 0. This is used for measuring a relative similarity between samples. A triplet is composed by `a`, `p` and `n`: anchor, positive examples and negative example respectively. The shapes of all input tensors should be ![](img/3dc464d2e10c731f17264e33e497c1a8.jpg).
W
wizardforcel 已提交
5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724

The distance swap is described in detail in the paper [Learning shallow convolutional feature descriptors with triplet losses](http://www.iis.ee.ic.ac.uk/%7Evbalnt/shallow_descr/TFeat_paper.pdf) by V. Balntas, E. Riba et al.

The loss function for each sample in the mini-batch is:

![](img/a2c4faa5dd95a547388c1b7f69bbc4db.jpg)

where

![](img/bac339e9cf6ad679fa9ce3ce33c431ab.jpg)

W
wizardforcel 已提交
5725
Parameters: 
W
wizardforcel 已提交
5726

W
wizardforcel 已提交
5727 5728 5729
*   **margin** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – Default: `1`.
*   **p** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – The norm degree for pairwise distance. Default: `2`.
*   **swap** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – The distance swap is described in detail in the paper `Learning shallow convolutional feature descriptors with triplet losses` by V. Balntas, E. Riba et al. Default: `False`.
W
wizardforcel 已提交
5730 5731 5732 5733
*   **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`. Default: `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`. Default: `True`
*   **reduction** (_string__,_ _optional_) – Specifies the reduction to apply to the output: ‘none’ &#124; ‘mean’ &#124; ‘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`. Default: ‘mean’

W
wizardforcel 已提交
5734

W
wizardforcel 已提交
5735 5736 5737 5738 5739

```py
Shape:
```

W
wizardforcel 已提交
5740 5741
*   Input: ![](img/3dc464d2e10c731f17264e33e497c1a8.jpg) where `D` is the vector dimension.
*   Output: scalar. If `reduce` is False, then `(N)`.
W
wizardforcel 已提交
5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757

```py
>>> triplet_loss = nn.TripletMarginLoss(margin=1.0, p=2)
>>> input1 = torch.randn(100, 128, requires_grad=True)
>>> input2 = torch.randn(100, 128, requires_grad=True)
>>> input3 = torch.randn(100, 128, requires_grad=True)
>>> output = triplet_loss(input1, input2, input3)
>>> output.backward()

```

## Vision layers

### PixelShuffle

```py
W
wizardforcel 已提交
5758
class torch.nn.PixelShuffle(upscale_factor)
W
wizardforcel 已提交
5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790
```

Rearranges elements in a tensor of shape ![](img/1bc8a113de558f2e7d966e72ae39cb95.jpg) to a tensor of shape ![](img/d4e6de257f72abc5a96af64211b7f909.jpg).

This is useful for implementing efficient sub-pixel convolution with a stride of ![](img/71c5422a7f21b7096aa6d904d5a4f78d.jpg).

Look at the paper: [Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network](https://arxiv.org/abs/1609.05158) by Shi et. al (2016) for more details.

| Parameters: | **upscale_factor** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – factor to increase spatial resolution by |
| --- | --- |

```py
Shape:
```

*   Input: ![](img/d6770cccc0ae9886c3b91d55efa20b28.jpg)
*   Output: ![](img/a162cf8e9185f67b3f5b084d1031dc7e.jpg)

Examples:

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

```

### Upsample

```py
W
wizardforcel 已提交
5791
class torch.nn.Upsample(size=None, scale_factor=None, mode='nearest', align_corners=None)
W
wizardforcel 已提交
5792 5793 5794 5795
```

Upsamples a given multi-channel 1D (temporal), 2D (spatial) or 3D (volumetric) data.

W
wizardforcel 已提交
5796
The input data is assumed to be of the form `minibatch x channels x [optional depth] x [optional height] x width`. Hence, for spatial inputs, we expect a 4D Tensor and for volumetric inputs, we expect a 5D Tensor.
W
wizardforcel 已提交
5797 5798 5799 5800 5801

The algorithms available for upsampling are nearest neighbor and linear, bilinear and trilinear for 3D, 4D and 5D input Tensor, respectively.

One can either give a `scale_factor` or the target output `size` to calculate the output size. (You cannot give both, as it is ambiguous)

W
wizardforcel 已提交
5802
Parameters: 
W
wizardforcel 已提交
5803

W
wizardforcel 已提交
5804
*   **size** ([_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – a tuple of ints `([optional D_out], [optional H_out], W_out)` output sizes
W
wizardforcel 已提交
5805
*   **scale_factor** (_int / tuple of python:ints__,_ _optional_) – the multiplier for the image height / width / depth
W
wizardforcel 已提交
5806 5807
*   **mode** (_string__,_ _optional_) – the upsampling algorithm: one of `nearest`, `linear`, `bilinear` and `trilinear`. Default: `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`. Default: False
W
wizardforcel 已提交
5808

W
wizardforcel 已提交
5809

W
wizardforcel 已提交
5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825

```py
Shape:
```

*   Input: ![](img/964aa6df63e83f4468aa090441f01972.jpg), ![](img/ff71b16eb10237262566c6907acaaf1f.jpg) or ![](img/c187d190013d0785320e3412fe8cd669.jpg)
*   Output: ![](img/ac2661719f40fc422e2b1590a1e7b4a4.jpg), ![](img/a0ef05f779873fc4dcbf020b1ea14754.jpg) or ![](img/41ca4c8d4c65c979d2d643c6f62ea280.jpg), where

![](img/da11a1265058248a851d6d0331110214.jpg)

![](img/828543b18440713aad6ad023732327ec.jpg)

![](img/5a7c5c22409d4ab3c83641508bf72cb6.jpg)

Warning

W
wizardforcel 已提交
5826
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`. See below for concrete examples on how this affects the outputs.
W
wizardforcel 已提交
5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896

Note

If you want downsampling/general resizing, you should use `interpolate()`.

Examples:

```py
>>> input = torch.arange(1, 5).view(1, 1, 2, 2).float()
>>> input
tensor([[[[ 1.,  2.],
 [ 3.,  4.]]]])

>>> m = nn.Upsample(scale_factor=2, mode='nearest')
>>> m(input)
tensor([[[[ 1.,  1.,  2.,  2.],
 [ 1.,  1.,  2.,  2.],
 [ 3.,  3.,  4.,  4.],
 [ 3.,  3.,  4.,  4.]]]])

>>> m = nn.Upsample(scale_factor=2, mode='bilinear')  # align_corners=False
>>> m(input)
tensor([[[[ 1.0000,  1.2500,  1.7500,  2.0000],
 [ 1.5000,  1.7500,  2.2500,  2.5000],
 [ 2.5000,  2.7500,  3.2500,  3.5000],
 [ 3.0000,  3.2500,  3.7500,  4.0000]]]])

>>> m = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
>>> m(input)
tensor([[[[ 1.0000,  1.3333,  1.6667,  2.0000],
 [ 1.6667,  2.0000,  2.3333,  2.6667],
 [ 2.3333,  2.6667,  3.0000,  3.3333],
 [ 3.0000,  3.3333,  3.6667,  4.0000]]]])

>>> # Try scaling the same data in a larger tensor
>>>
>>> input_3x3 = torch.zeros(3, 3).view(1, 1, 3, 3)
>>> input_3x3[:, :, :2, :2].copy_(input)
tensor([[[[ 1.,  2.],
 [ 3.,  4.]]]])
>>> input_3x3
tensor([[[[ 1.,  2.,  0.],
 [ 3.,  4.,  0.],
 [ 0.,  0.,  0.]]]])

>>> m = nn.Upsample(scale_factor=2, mode='bilinear')  # align_corners=False
>>> # Notice that values in top left corner are the same with the small input (except at boundary)
>>> m(input_3x3)
tensor([[[[ 1.0000,  1.2500,  1.7500,  1.5000,  0.5000,  0.0000],
 [ 1.5000,  1.7500,  2.2500,  1.8750,  0.6250,  0.0000],
 [ 2.5000,  2.7500,  3.2500,  2.6250,  0.8750,  0.0000],
 [ 2.2500,  2.4375,  2.8125,  2.2500,  0.7500,  0.0000],
 [ 0.7500,  0.8125,  0.9375,  0.7500,  0.2500,  0.0000],
 [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000]]]])

>>> m = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
>>> # Notice that values in top left corner are now changed
>>> m(input_3x3)
tensor([[[[ 1.0000,  1.4000,  1.8000,  1.6000,  0.8000,  0.0000],
 [ 1.8000,  2.2000,  2.6000,  2.2400,  1.1200,  0.0000],
 [ 2.6000,  3.0000,  3.4000,  2.8800,  1.4400,  0.0000],
 [ 2.4000,  2.7200,  3.0400,  2.5600,  1.2800,  0.0000],
 [ 1.2000,  1.3600,  1.5200,  1.2800,  0.6400,  0.0000],
 [ 0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000]]]])

```

### UpsamplingNearest2d

```py
W
wizardforcel 已提交
5897
class torch.nn.UpsamplingNearest2d(size=None, scale_factor=None)
W
wizardforcel 已提交
5898 5899 5900 5901 5902 5903
```

Applies a 2D nearest neighbor upsampling to an input signal composed of several input channels.

To specify the scale, it takes either the `size` or the `scale_factor` as it’s constructor argument.

W
wizardforcel 已提交
5904
When `size` is given, it is the output size of the image `(h, w)`.
W
wizardforcel 已提交
5905

W
wizardforcel 已提交
5906
Parameters: 
W
wizardforcel 已提交
5907

W
wizardforcel 已提交
5908
*   **size** ([_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – a tuple of ints `(H_out, W_out)` output sizes
W
wizardforcel 已提交
5909 5910
*   **scale_factor** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – the multiplier for the image height or width

W
wizardforcel 已提交
5911

W
wizardforcel 已提交
5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947

Warning

This class is deprecated in favor of `interpolate()`.

```py
Shape:
```

*   Input: ![](img/ff71b16eb10237262566c6907acaaf1f.jpg)
*   Output: ![](img/a0ef05f779873fc4dcbf020b1ea14754.jpg) where

![](img/682de298a3561bebd964280ba0d59633.jpg)

![](img/2a53007c25abe7f8f65f1a2e958fa146.jpg)

Examples:

```py
>>> input = torch.arange(1, 5).view(1, 1, 2, 2)
>>> input
tensor([[[[ 1.,  2.],
 [ 3.,  4.]]]])

>>> m = nn.UpsamplingNearest2d(scale_factor=2)
>>> m(input)
tensor([[[[ 1.,  1.,  2.,  2.],
 [ 1.,  1.,  2.,  2.],
 [ 3.,  3.,  4.,  4.],
 [ 3.,  3.,  4.,  4.]]]])

```

### UpsamplingBilinear2d

```py
W
wizardforcel 已提交
5948
class torch.nn.UpsamplingBilinear2d(size=None, scale_factor=None)
W
wizardforcel 已提交
5949 5950 5951 5952 5953 5954
```

Applies a 2D bilinear upsampling to an input signal composed of several input channels.

To specify the scale, it takes either the `size` or the `scale_factor` as it’s constructor argument.

W
wizardforcel 已提交
5955
When `size` is given, it is the output size of the image `(h, w)`.
W
wizardforcel 已提交
5956

W
wizardforcel 已提交
5957
Parameters: 
W
wizardforcel 已提交
5958

W
wizardforcel 已提交
5959
*   **size** ([_tuple_](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.7)")_,_ _optional_) – a tuple of ints `(H_out, W_out)` output sizes
W
wizardforcel 已提交
5960 5961
*   **scale_factor** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – the multiplier for the image height or width

W
wizardforcel 已提交
5962

W
wizardforcel 已提交
5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000

Warning

This class is deprecated in favor of `interpolate()`. It is equivalent to `nn.functional.interpolate(..., mode='bilinear', align_corners=True)`.

```py
Shape:
```

*   Input: ![](img/ff71b16eb10237262566c6907acaaf1f.jpg)
*   Output: ![](img/a0ef05f779873fc4dcbf020b1ea14754.jpg) where

![](img/682de298a3561bebd964280ba0d59633.jpg)

![](img/2a53007c25abe7f8f65f1a2e958fa146.jpg)

Examples:

```py
>>> input = torch.arange(1, 5).view(1, 1, 2, 2)
>>> input
tensor([[[[ 1.,  2.],
 [ 3.,  4.]]]])

>>> m = nn.UpsamplingBilinear2d(scale_factor=2)
>>> m(input)
tensor([[[[ 1.0000,  1.3333,  1.6667,  2.0000],
 [ 1.6667,  2.0000,  2.3333,  2.6667],
 [ 2.3333,  2.6667,  3.0000,  3.3333],
 [ 3.0000,  3.3333,  3.6667,  4.0000]]]])

```

## DataParallel layers (multi-GPU, distributed)

### DataParallel

```py
W
wizardforcel 已提交
6001
class torch.nn.DataParallel(module, device_ids=None, output_device=None, dim=0)
W
wizardforcel 已提交
6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021
```

Implements data parallelism at the module level.

This container parallelizes the application of the given `module` by splitting the input across the specified devices by chunking in the batch dimension (other objects will be copied once per device). In the forward pass, the module is replicated on each device, and each replica handles a portion of the input. During the backwards pass, gradients from each replica are summed into the original module.

The batch size should be larger than the number of GPUs used.

See also: [Use nn.DataParallel instead of multiprocessing](notes/cuda.html#cuda-nn-dataparallel-instead)

Arbitrary positional and keyword inputs are allowed to be passed into DataParallel EXCEPT Tensors. All tensors will be scattered on dim specified (default 0). Primitive types will be broadcasted, but all other types will be a shallow copy and can be corrupted if written to in the model’s forward pass.

The parallelized `module` must have its parameters and buffers on `device_ids[0]` before running this [`DataParallel`](#torch.nn.DataParallel "torch.nn.DataParallel") module.

Warning

In each forward, `module` is **replicated** on each device, so any updates to the runing module in `forward` will be lost. For example, if `module` has a counter attribute that is incremented in each `forward`, it will always stay at the initial value becasue the update is done on the replicas which are destroyed after `forward`. However, [`DataParallel`](#torch.nn.DataParallel "torch.nn.DataParallel") guarantees that the replica on `device[0]` will have its parameters and buffers sharing storage with the base parallelized `module`. So **in-place** updates to the parameters or buffers on `device[0]` will be recorded. E.g., [`BatchNorm2d`](#torch.nn.BatchNorm2d "torch.nn.BatchNorm2d") and [`spectral_norm()`](#torch.nn.utils.spectral_norm "torch.nn.utils.spectral_norm") rely on this behavior to update the buffers.

Warning

W
wizardforcel 已提交
6022
Forward and backward hooks defined on `module` and its submodules will be invoked `len(device_ids)` times, each with inputs located on a particular device. Particularly, the hooks are only guaranteed to be executed in correct order with respect to operations on corresponding devices. For example, it is not guaranteed that hooks set via [`register_forward_pre_hook()`](#torch.nn.Module.register_forward_pre_hook "torch.nn.Module.register_forward_pre_hook") be executed before `all` `len(device_ids)` [`forward()`](#torch.nn.Module.forward "torch.nn.Module.forward") calls, but that each such hook be executed before the corresponding [`forward()`](#torch.nn.Module.forward "torch.nn.Module.forward") call of that device.
W
wizardforcel 已提交
6023 6024 6025 6026 6027 6028 6029 6030 6031

Warning

When `module` returns a scalar (i.e., 0-dimensional tensor) in `forward()`, this wrapper will return a vector of length equal to number of devices used in data parallelism, containing the result from each device.

Note

There is a subtlety in using the `pack sequence -&gt; recurrent network -&gt; unpack sequence` pattern in a [`Module`](#torch.nn.Module "torch.nn.Module") wrapped in [`DataParallel`](#torch.nn.DataParallel "torch.nn.DataParallel"). See [My recurrent network doesn’t work with data parallelism](notes/faq.html#pack-rnn-unpack-with-data-parallelism) section in FAQ for details.

W
wizardforcel 已提交
6032
Parameters: 
W
wizardforcel 已提交
6033 6034 6035 6036 6037

*   **module** ([_Module_](#torch.nn.Module "torch.nn.Module")) – module to be parallelized
*   **device_ids** (_list of python:int_ _or_ [_torch.device_](tensor_attributes.html#torch.torch.device "torch.torch.device")) – CUDA devices (default: all devices)
*   **output_device** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_torch.device_](tensor_attributes.html#torch.torch.device "torch.torch.device")) – device location of output (default: device_ids[0])

W
wizardforcel 已提交
6038

W
wizardforcel 已提交
6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052
| Variables: | **module** ([_Module_](#torch.nn.Module "torch.nn.Module")) – the module to be parallelized |
| --- | --- |

Example:

```py
>>> net = torch.nn.DataParallel(model, device_ids=[0, 1, 2])
>>> output = net(input_var)

```

### DistributedDataParallel

```py
W
wizardforcel 已提交
6053
class torch.nn.parallel.DistributedDataParallel(module, device_ids=None, output_device=None, dim=0, broadcast_buffers=True, process_group=None, bucket_cap_mb=25, check_reduction=False)
W
wizardforcel 已提交
6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142
```

Implements distributed data parallelism that is based on torch.distributed package at the module level.

This container parallelizes the application of the given module by splitting the input across the specified devices by chunking in the batch dimension. The module is replicated on each machine and each device, and each such replica handles a portion of the input. During the backwards pass, gradients from each node are averaged.

The batch size should be larger than the number of GPUs used locally. It should also be an integer multiple of the number of GPUs so that each chunk is the same size (so that each GPU processes the same number of samples).

See also: [Basics](distributed.html#distributed-basics) and [Use nn.DataParallel instead of multiprocessing](notes/cuda.html#cuda-nn-dataparallel-instead). The same constraints on input as in [`torch.nn.DataParallel`](#torch.nn.DataParallel "torch.nn.DataParallel") apply.

Creation of this class requires that `torch.distributed` to be already initialized, by calling [`torch.distributed.init_process_group()`](distributed.html#torch.distributed.init_process_group "torch.distributed.init_process_group")

`DistributedDataParallel` can be used in the following two ways:

1.  Single-Process Multi-GPU

In this case, a single process will be spawned on each host/node and each process will operate on all the GPUs of the node where it’s running. To use `DistributedDataParallel` in this way, you can simply construct the model as the following:

```py
>>> torch.distributed.init_process_group(backend="nccl")
>>> model = DistributedDataParallel(model) # device_ids will include all GPU devices be default

```

1.  Multi-Process Single-GPU

This is the highly recommended way to use `DistributedDataParallel`, with multiple processes, each of which operates on a single GPU. This is currently the fastest approach to do data parallel training using PyTorch and applies to both single-node(multi-GPU) and multi-node data parallel training. It is proven to be significantly faster than [`torch.nn.DataParallel`](#torch.nn.DataParallel "torch.nn.DataParallel") for single-node multi-GPU data parallel training.

Here is how to use it: on each host with N GPUs, you should spawn up N processes, while ensuring that each process invidually works on a single GPU from 0 to N-1\. Therefore, it is your job to ensure that your training script operates on a single given GPU by calling:

```py
>>> torch.cuda.set_device(i)

```

where i is from 0 to N-1\. In each process, you should refer the following to construct this module:

```py
>>> torch.distributed.init_process_group(backend='nccl', world_size=4, init_method='...')
>>> model = DistributedDataParallel(model, device_ids=[i], output_device=i)

```

In order to spawn up multiple processes per node, you can use either `torch.distributed.launch` or `torch.multiprocessing.spawn`

Note

`nccl` backend is currently the fastest and highly recommended backend to be used with Multi-Process Single-GPU distributed training and this applies to both single-node and multi-node distributed training

Warning

This module works only with the `gloo` and `nccl` backends.

Warning

Constructor, forward method, and differentiation of the output (or a function of the output of this module) is a distributed synchronization point. Take that into account in case different processes might be executing different code.

Warning

This module assumes all parameters are registered in the model by the time it is created. No parameters should be added nor removed later. Same applies to buffers.

Warning

This module assumes all parameters are registered in the model of each distributed processes are in the same order. The module itself will conduct gradient all-reduction following the reverse order of the registered parameters of the model. In other wise, it is users’ responsibility to ensure that each distributed process has the exact same model and thus the exact parameter registeration order.

Warning

This module assumes all buffers and gradients are dense.

Warning

This module doesn’t work with [`torch.autograd.grad()`](autograd.html#torch.autograd.grad "torch.autograd.grad") (i.e. it will only work if gradients are to be accumulated in `.grad` attributes of parameters).

Warning

If you plan on using this module with a `nccl` backend or a `gloo` backend (that uses Infiniband), together with a DataLoader that uses multiple workers, please change the multiprocessing start method to `forkserver` (Python 3 only) or `spawn`. Unfortunately Gloo (that uses Infiniband) and NCCL2 are not fork safe, and you will likely experience deadlocks if you don’t change this setting.

Warning

Forward and backward hooks defined on `module` and its submodules won’t be invoked anymore, unless the hooks are initialized in the `forward()` method.

Warning

You should never try to change your model’s parameters after wrapping up your model with DistributedDataParallel. In other words, when wrapping up your model with DistributedDataParallel, the constructor of DistributedDataParallel will register the additional gradient reduction functions on all the parameters of the model itself at the time of construction. If you change the model’s parameters after the DistributedDataParallel construction, this is not supported and unexpected behaviors can happen, since some parameters’ gradient reduction functions might not get called.

Note

Parameters are never broadcast between processes. The module performs an all-reduce step on gradients and assumes that they will be modified by the optimizer in all processes in the same way. Buffers (e.g. BatchNorm stats) are broadcast from the module in process of rank 0, to all other replicas in the system in every iteration.

W
wizardforcel 已提交
6143
Parameters: 
W
wizardforcel 已提交
6144 6145 6146 6147 6148 6149 6150 6151 6152

*   **module** ([_Module_](#torch.nn.Module "torch.nn.Module")) – module to be parallelized
*   **device_ids** (_list of python:int_ _or_ [_torch.device_](tensor_attributes.html#torch.torch.device "torch.torch.device")) – CUDA devices (default: all devices)
*   **output_device** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)") _or_ [_torch.device_](tensor_attributes.html#torch.torch.device "torch.torch.device")) – device location of output (default: device_ids[0])
*   **broadcast_buffers** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")) – flag that enables syncing (broadcasting) buffers of the module at beginning of the forward function. (default: True)
*   **process_group** – the process group to be used for distributed data all-reduction. If None, the default process group, which is created by ``torch.distributed.init_process_group``, will be used. (default: None)
*   **bucket_cap_mb** – DistributedDataParallel will bucket parameters into multiple buckets so that gradient reduction of each bucket can potentially overlap with backward computation. bucket_cap_mb controls the bucket size in MegaBytes (MB) (default: 25)
*   **check_reduction** – when setting to True, it enables DistributedDataParallel to automatically check if the previous iteration’s backward reductions were successfully issued at the beginning of every iteration’s forward function. You normally don’t need this option enabled unless you are observing weird behaviors such as different ranks are getting different gradients, which should not happen if DistributedDataParallel is corrected used. (default: False)

W
wizardforcel 已提交
6153

W
wizardforcel 已提交
6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169
| Variables: | **module** ([_Module_](#torch.nn.Module "torch.nn.Module")) – the module to be parallelized |
| --- | --- |

```py
Example::
```

```py
>>> torch.distributed.init_process_group(backend='nccl', world_size=4, init_method='...')
>>> net = torch.nn.DistributedDataParallel(model, pg)

```

### DistributedDataParallelCPU

```py
W
wizardforcel 已提交
6170
class torch.nn.parallel.DistributedDataParallelCPU(module)
W
wizardforcel 已提交
6171 6172 6173 6174 6175 6176 6177 6178
```

Implements distributed data parallelism for CPU at the module level.

This module supports the `mpi` and `gloo` backends.

This container parallelizes the application of the given module by splitting the input across the specified devices by chunking in the batch dimension. The module is replicated on each machine, and each such replica handles a portion of the input. During the backwards pass, gradients from each node are averaged.

W
wizardforcel 已提交
6179
This module could be used in conjunction with the DistributedSampler, (see :class `torch.utils.data.distributed.DistributedSampler`) which will load a subset of the original datset for each node with the same batch size. So strong scaling should be configured like this:
W
wizardforcel 已提交
6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230

n = 1, batch size = 12

n = 2, batch size = 64

n = 4, batch size = 32

n = 8, batch size = 16

Creation of this class requires the distributed package to be already initialized in the process group mode (see [`torch.distributed.init_process_group()`](distributed.html#torch.distributed.init_process_group "torch.distributed.init_process_group")).

Warning

Constructor, forward method, and differentiation of the output (or a function of the output of this module) is a distributed synchronization point. Take that into account in case different node might be executing different code.

Warning

This module assumes all parameters are registered in the model by the time it is created. No parameters should be added nor removed later.

Warning

This module assumes all gradients are dense.

Warning

This module doesn’t work with [`torch.autograd.grad()`](autograd.html#torch.autograd.grad "torch.autograd.grad") (i.e. it will only work if gradients are to be accumulated in `.grad` attributes of parameters).

Warning

Forward and backward hooks defined on `module` and its submodules won’t be invoked anymore, unless the hooks are initialized in the `forward()` method.

Note

Parameters are broadcast between nodes in the __init__() function. The module performs an all-reduce step on gradients and assumes that they will be modified by the optimizer in all nodes in the same way.

| Parameters: | **module** – module to be parallelized |
| --- | --- |

Example:

```py
>>> torch.distributed.init_process_group(world_size=4, init_method='...')
>>> net = torch.nn.DistributedDataParallelCPU(model)

```

## Utilities

### clip_grad_norm_

```py
W
wizardforcel 已提交
6231
torch.nn.utils.clip_grad_norm_(parameters, max_norm, norm_type=2)
W
wizardforcel 已提交
6232 6233 6234 6235 6236 6237
```

Clips gradient norm of an iterable of parameters.

The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place.

W
wizardforcel 已提交
6238
Parameters: 
W
wizardforcel 已提交
6239 6240 6241 6242 6243

*   **parameters** (_Iterable__[_[_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_] or_ [_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – an iterable of Tensors or a single Tensor that will have gradients normalized
*   **max_norm** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)") _or_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – max norm of the gradients
*   **norm_type** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)") _or_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – type of the used p-norm. Can be `'inf'` for infinity norm.

W
wizardforcel 已提交
6244

W
wizardforcel 已提交
6245 6246 6247 6248 6249 6250
| Returns: | Total norm of the parameters (viewed as a single vector). |
| --- | --- |

### clip_grad_value_

```py
W
wizardforcel 已提交
6251
torch.nn.utils.clip_grad_value_(parameters, clip_value)
W
wizardforcel 已提交
6252 6253 6254 6255 6256 6257
```

Clips gradient of an iterable of parameters at specified value.

Gradients are modified in-place.

W
wizardforcel 已提交
6258
Parameters: 
W
wizardforcel 已提交
6259 6260 6261 6262

*   **parameters** (_Iterable__[_[_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_] or_ [_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – an iterable of Tensors or a single Tensor that will have gradients normalized
*   **clip_value** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)") _or_ [_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")) – maximum allowed value of the gradients The gradients are clipped in the range [-clip_value, clip_value]

W
wizardforcel 已提交
6263

W
wizardforcel 已提交
6264 6265 6266 6267

### parameters_to_vector

```py
W
wizardforcel 已提交
6268
torch.nn.utils.parameters_to_vector(parameters)
W
wizardforcel 已提交
6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280
```

Convert parameters to one vector

| Parameters: | **parameters** (_Iterable__[_[_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_]_) – an iterator of Tensors that are the parameters of a model. |
| --- | --- |
| Returns: | The parameters represented by a single vector |
| --- | --- |

### vector_to_parameters

```py
W
wizardforcel 已提交
6281
torch.nn.utils.vector_to_parameters(vec, parameters)
W
wizardforcel 已提交
6282 6283 6284 6285
```

Convert one vector to the parameters

W
wizardforcel 已提交
6286
Parameters: 
W
wizardforcel 已提交
6287 6288 6289 6290

*   **vec** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – a single vector represents the parameters of a model.
*   **parameters** (_Iterable__[_[_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_]_) – an iterator of Tensors that are the parameters of a model.

W
wizardforcel 已提交
6291

W
wizardforcel 已提交
6292 6293 6294 6295

### weight_norm

```py
W
wizardforcel 已提交
6296
torch.nn.utils.weight_norm(module, name='weight', dim=0)
W
wizardforcel 已提交
6297 6298 6299 6300 6301 6302
```

Applies weight normalization to a parameter in the given module.

![](img/06160be4a838f9d6d20cabc64f32670e.jpg)

W
wizardforcel 已提交
6303
Weight normalization is a reparameterization that decouples the magnitude of a weight tensor from its direction. This replaces the parameter specified by `name` (e.g. “weight”) with two parameters: one specifying the magnitude (e.g. “weight_g”) and one specifying the direction (e.g. “weight_v”). Weight normalization is implemented via a hook that recomputes the weight tensor from the magnitude and direction before every `forward()` call.
W
wizardforcel 已提交
6304

W
wizardforcel 已提交
6305
By default, with `dim=0`, the norm is computed independently per output channel/plane. To compute a norm over the entire weight tensor, use `dim=None`.
W
wizardforcel 已提交
6306 6307 6308

See [https://arxiv.org/abs/1602.07868](https://arxiv.org/abs/1602.07868)

W
wizardforcel 已提交
6309
Parameters: 
W
wizardforcel 已提交
6310 6311 6312 6313 6314

*   **module** ([_nn.Module_](#torch.nn.Module "torch.nn.Module")) – containing module
*   **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")_,_ _optional_) – name of weight parameter
*   **dim** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – dimension over which to compute the norm

W
wizardforcel 已提交
6315

W
wizardforcel 已提交
6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333
| Returns: | The original module with the weight norm hook |
| --- | --- |

Example:

```py
>>> m = weight_norm(nn.Linear(20, 40), name='weight')
Linear (20 -> 40)
>>> m.weight_g.size()
torch.Size([40, 1])
>>> m.weight_v.size()
torch.Size([40, 20])

```

### remove_weight_norm

```py
W
wizardforcel 已提交
6334
torch.nn.utils.remove_weight_norm(module, name='weight')
W
wizardforcel 已提交
6335 6336 6337 6338
```

Removes the weight normalization reparameterization from a module.

W
wizardforcel 已提交
6339
Parameters: 
W
wizardforcel 已提交
6340 6341 6342 6343

*   **module** ([_nn.Module_](#torch.nn.Module "torch.nn.Module")) – containing module
*   **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")_,_ _optional_) – name of weight parameter

W
wizardforcel 已提交
6344

W
wizardforcel 已提交
6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356

Example

```py
>>> m = weight_norm(nn.Linear(20, 40))
>>> remove_weight_norm(m)

```

### spectral_norm

```py
W
wizardforcel 已提交
6357
torch.nn.utils.spectral_norm(module, name='weight', n_power_iterations=1, eps=1e-12, dim=None)
W
wizardforcel 已提交
6358 6359 6360 6361 6362 6363 6364 6365 6366 6367
```

Applies spectral normalization to a parameter in the given module.

![](img/1ca46cc2506aac38bf00645f64b1a3e3.jpg)

Spectral normalization stabilizes the training of discriminators (critics) in Generaive Adversarial Networks (GANs) by rescaling the weight tensor with spectral norm ![](img/2469b2bd2a1ab19ebfcee223dcb52bb1.jpg) of the weight matrix calculated using power iteration method. If the dimension of the weight tensor is greater than 2, it is reshaped to 2D in power iteration method to get spectral norm. This is implemented via a hook that calculates spectral norm and rescales weight before every `forward()` call.

See [Spectral Normalization for Generative Adversarial Networks](https://arxiv.org/abs/1802.05957) .

W
wizardforcel 已提交
6368
Parameters: 
W
wizardforcel 已提交
6369 6370 6371 6372 6373 6374 6375

*   **module** ([_nn.Module_](#torch.nn.Module "torch.nn.Module")) – containing module
*   **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")_,_ _optional_) – name of weight parameter
*   **n_power_iterations** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – number of power iterations to calculate spectal norm
*   **eps** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – epsilon for numerical stability in calculating norms
*   **dim** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – dimension corresponding to number of outputs, the default is 0, except for modules that are instances of ConvTranspose1/2/3d, when it is 1

W
wizardforcel 已提交
6376

W
wizardforcel 已提交
6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392
| Returns: | The original module with the spectal norm hook |
| --- | --- |

Example:

```py
>>> m = spectral_norm(nn.Linear(20, 40))
Linear (20 -> 40)
>>> m.weight_u.size()
torch.Size([20])

```

### remove_spectral_norm

```py
W
wizardforcel 已提交
6393
torch.nn.utils.remove_spectral_norm(module, name='weight')
W
wizardforcel 已提交
6394 6395 6396 6397
```

Removes the spectral normalization reparameterization from a module.

W
wizardforcel 已提交
6398
Parameters: 
W
wizardforcel 已提交
6399 6400 6401 6402

*   **module** ([_nn.Module_](#torch.nn.Module "torch.nn.Module")) – containing module
*   **name** ([_str_](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.7)")_,_ _optional_) – name of weight parameter

W
wizardforcel 已提交
6403

W
wizardforcel 已提交
6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415

Example

```py
>>> m = spectral_norm(nn.Linear(40, 10))
>>> remove_spectral_norm(m)

```

### PackedSequence

```py
W
wizardforcel 已提交
6416
torch.nn.utils.rnn.PackedSequence(data, batch_sizes=None)
W
wizardforcel 已提交
6417 6418 6419 6420 6421 6422 6423 6424 6425 6426
```

Holds the data and list of `batch_sizes` of a packed sequence.

All RNN modules accept packed sequences as inputs.

Note

Instances of this class should never be created manually. They are meant to be instantiated by functions like [`pack_padded_sequence()`](#torch.nn.utils.rnn.pack_padded_sequence "torch.nn.utils.rnn.pack_padded_sequence").

W
wizardforcel 已提交
6427
Batch sizes represent the number elements at each sequence step in the batch, not the varying sequence lengths passed to [`pack_padded_sequence()`](#torch.nn.utils.rnn.pack_padded_sequence "torch.nn.utils.rnn.pack_padded_sequence"). For instance, given data `abc` and `x` the [`PackedSequence`](#torch.nn.utils.rnn.PackedSequence "torch.nn.utils.rnn.PackedSequence") would contain data `axbc` with `batch_sizes=[2,1,1]`.
W
wizardforcel 已提交
6428 6429 6430 6431 6432 6433

| Variables: | 

*   **data** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – Tensor containing packed sequence
*   **batch_sizes** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – Tensor of integers holding information about the batch size at each sequence step

W
wizardforcel 已提交
6434

W
wizardforcel 已提交
6435 6436 6437 6438

### pack_padded_sequence

```py
W
wizardforcel 已提交
6439
torch.nn.utils.rnn.pack_padded_sequence(input, lengths, batch_first=False)
W
wizardforcel 已提交
6440 6441 6442 6443
```

Packs a Tensor containing padded sequences of variable length.

W
wizardforcel 已提交
6444
Input can be of size `T x B x *` where `T` is the length of the longest sequence (equal to `lengths[0]`), `B` is the batch size, and `*` is any number of dimensions (including 0). If `batch_first` is True `B x T x *` inputs are expected.
W
wizardforcel 已提交
6445 6446 6447 6448 6449 6450 6451

The sequences should be sorted by length in a decreasing order, i.e. `input[:,0]` should be the longest sequence, and `input[:,B-1]` the shortest one.

Note

This function accepts any input that has at least two dimensions. You can apply it to pack the labels, and use the output of the RNN with them to compute the loss directly. A Tensor can be retrieved from a [`PackedSequence`](#torch.nn.utils.rnn.PackedSequence "torch.nn.utils.rnn.PackedSequence") object by accessing its `.data` attribute.

W
wizardforcel 已提交
6452
Parameters: 
W
wizardforcel 已提交
6453 6454 6455 6456 6457

*   **input** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – padded batch of variable length sequences.
*   **lengths** ([_Tensor_](tensors.html#torch.Tensor "torch.Tensor")) – list of sequences lengths of each batch element.
*   **batch_first** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – if `True`, the input is expected in `B x T x *` format.

W
wizardforcel 已提交
6458

W
wizardforcel 已提交
6459 6460 6461 6462 6463 6464
| Returns: | a [`PackedSequence`](#torch.nn.utils.rnn.PackedSequence "torch.nn.utils.rnn.PackedSequence") object |
| --- | --- |

### pad_packed_sequence

```py
W
wizardforcel 已提交
6465
torch.nn.utils.rnn.pad_packed_sequence(sequence, batch_first=False, padding_value=0.0, total_length=None)
W
wizardforcel 已提交
6466 6467 6468 6469 6470 6471
```

Pads a packed batch of variable length sequences.

It is an inverse operation to [`pack_padded_sequence()`](#torch.nn.utils.rnn.pack_padded_sequence "torch.nn.utils.rnn.pack_padded_sequence").

W
wizardforcel 已提交
6472
The returned Tensor’s data will be of size `T x B x *`, where `T` is the length of the longest sequence and `B` is the batch size. If `batch_first` is True, the data will be transposed into `B x T x *` format.
W
wizardforcel 已提交
6473 6474 6475 6476 6477 6478 6479

Batch elements will be ordered decreasingly by their length.

Note

`total_length` is useful to implement the `pack sequence -&gt; recurrent network -&gt; unpack sequence` pattern in a [`Module`](#torch.nn.Module "torch.nn.Module") wrapped in [`DataParallel`](#torch.nn.DataParallel "torch.nn.DataParallel"). See [this FAQ section](notes/faq.html#pack-rnn-unpack-with-data-parallelism) for details.

W
wizardforcel 已提交
6480
Parameters: 
W
wizardforcel 已提交
6481 6482 6483 6484 6485 6486

*   **sequence** (_PackedSequence_) – batch to pad
*   **batch_first** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – if `True`, the output will be in `B x T x *` format.
*   **padding_value** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – values for padded elements.
*   **total_length** ([_int_](https://docs.python.org/3/library/functions.html#int "(in Python v3.7)")_,_ _optional_) – if not `None`, the output will be padded to have length `total_length`. This method will throw [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.7)") if `total_length` is less than the max sequence length in `sequence`.

W
wizardforcel 已提交
6487

W
wizardforcel 已提交
6488 6489 6490 6491 6492 6493
| Returns: | Tuple of Tensor containing the padded sequence, and a Tensor containing the list of lengths of each sequence in the batch. |
| --- | --- |

### pad_sequence

```py
W
wizardforcel 已提交
6494
torch.nn.utils.rnn.pad_sequence(sequences, batch_first=False, padding_value=0)
W
wizardforcel 已提交
6495 6496 6497 6498 6499 6500
```

Pad a list of variable length Tensors with zero

`pad_sequence` stacks a list of Tensors along a new dimension, and pads them to equal length. For example, if the input is list of sequences with size `L x *` and if batch_first is False, and `T x B x *` otherwise.

W
wizardforcel 已提交
6501
`B` is batch size. It is equal to the number of elements in `sequences`. `T` is length of the longest sequence. `L` is length of the sequence. `*` is any number of trailing dimensions, including none.
W
wizardforcel 已提交
6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516

Example

```py
>>> from torch.nn.utils.rnn import pad_sequence
>>> a = torch.ones(25, 300)
>>> b = torch.ones(22, 300)
>>> c = torch.ones(15, 300)
>>> pad_sequence([a, b, c]).size()
torch.Size([25, 3, 300])

```

Note

W
wizardforcel 已提交
6517
This function returns a Tensor of size `T x B x *` or `B x T x *` where `T` is the length of the longest sequence. This function assumes trailing dimensions and type of all the Tensors in sequences are same.
W
wizardforcel 已提交
6518

W
wizardforcel 已提交
6519
Parameters: 
W
wizardforcel 已提交
6520 6521 6522 6523 6524

*   **sequences** ([_list_](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.7)")_[_[_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_]_) – list of variable length sequences.
*   **batch_first** ([_bool_](https://docs.python.org/3/library/functions.html#bool "(in Python v3.7)")_,_ _optional_) – output will be in `B x T x *` if True, or in `T x B x *` otherwise
*   **padding_value** ([_float_](https://docs.python.org/3/library/functions.html#float "(in Python v3.7)")_,_ _optional_) – value for padded elements. Default: 0.

W
wizardforcel 已提交
6525

W
wizardforcel 已提交
6526 6527 6528 6529 6530 6531
| Returns: | Tensor of size `T x B x *` if `batch_first` is `False`. Tensor of size `B x T x *` otherwise |
| --- | --- |

### pack_sequence

```py
W
wizardforcel 已提交
6532
torch.nn.utils.rnn.pack_sequence(sequences)
W
wizardforcel 已提交
6533 6534 6535 6536
```

Packs a list of variable length Tensors

W
wizardforcel 已提交
6537
`sequences` should be a list of Tensors of size `L x *`, where `L` is the length of a sequence and `*` is any number of trailing dimensions, including zero. They should be sorted in the order of decreasing length.
W
wizardforcel 已提交
6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555

Example

```py
>>> from torch.nn.utils.rnn import pack_sequence
>>> a = torch.tensor([1,2,3])
>>> b = torch.tensor([4,5])
>>> c = torch.tensor([6])
>>> pack_sequence([a, b, c])
PackedSequence(data=tensor([ 1,  4,  6,  2,  5,  3]), batch_sizes=tensor([ 3,  2,  1]))

```

| Parameters: | **sequences** ([_list_](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.7)")_[_[_Tensor_](tensors.html#torch.Tensor "torch.Tensor")_]_) – A list of sequences of decreasing length. |
| --- | --- |
| Returns: | a [`PackedSequence`](#torch.nn.utils.rnn.PackedSequence "torch.nn.utils.rnn.PackedSequence") object |
| --- | --- |