16.md 61.7 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 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 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 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 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 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 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
# torch.nn

*   [Parameters](#parameters)
*   [Containers](#containers)

### class torch.nn.Parameter()

一种`Variable`,被视为一个模块参数。

`Parameters``Variable` 的子类。当与`Module`一起使用时,它们具有非常特殊的属性,当它们被分配为模块属性时,它们被自动添加到其参数列表中,并将出现在例如`parameters()`迭代器中。分配变量没有这样的效果。这是因为人们可能希望在模型中缓存一些临时状态,如`RNN`的最后一个隐藏状态。如果没有这样的班级`Parameter`,这些临时人员也会注册。

另一个区别是,`parameters`不能是`volatile`,他们默认要求梯度。

参数说明:

*   data (Tensor) – parameter tensor.

*   requires_grad (bool, optional) – 如果需要计算剃度,可以参考[从向后排除子图](http://pytorch.org/docs/master/notes/autograd.html#excluding-subgraphs)

### class torch.nn.Module

所有神经网络模块的基类。

你的模型也应该继承这个类。

`Modules`还可以包含其他模块,允许将它们嵌套在树结构中。您可以将子模块分配为常规属性:

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

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)# submodule: Conv2d
        self.conv2 = nn.Conv2d(20, 20, 5)

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

以这种方式分配的子模块将被注册,并且在调用`.cuda()`等时也会转换参数。

#### add_module(name, module)

将一个子模块添加到当前模块。 该模块可以使用给定的名称作为属性访问。 例:

```py
import torch.nn as nn
class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.add_module("conv", nn.Conv2d(10, 20, 4))
        #self.conv = nn.Conv2d(10, 20, 4) 和上面这个增加 module 的方式等价
model = Model()
print(model.conv) 
```

输出:

```py
Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1)) 
```

#### apply(fn)

适用`fn`递归到每个子模块(如返回`.children()`),以及自我。典型用途包括初始化模型的参数(另见`torch-nn-init`)。 例如:

```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))
>>> net.apply(init_weights)
Linear (2 -> 2)
Parameter containing:
 1  1
 1  1
[torch.FloatTensor of size 2x2]
Linear (2 -> 2)
Parameter containing:
 1  1
 1  1
[torch.FloatTensor of size 2x2]
Sequential (
  (0): Linear (2 -> 2)
  (1): Linear (2 -> 2)
) 
```

#### children()

返回直接的子模块的迭代器。

#### cpu(device_id=None)

将所有模型参数和缓冲区移动到 CPU

#### cuda(device_id=None)

将所有模型参数和缓冲区移动到 GPU。

参数说明:

*   device_id (int, 可选) – 如果指定,所有参数将被复制到该设备

#### double()

将所有参数和缓冲区转换为双数据类型。

#### eval()

将模型设置成`evaluation`模式

仅仅当模型中有`Dropout``BatchNorm`是才会有影响。

#### float()

将所有参数和缓冲区转换为 float 数据类型。

#### forward(* input)

定义计算在每一个调用执行。 应该被所有子类重写。

#### half()

将所有参数和缓冲区转换为`half`类型。

#### load_state_dict(state_dict)

将参数和缓冲区复制`state_dict`到此模块及其后代。键`state_dict`必须与此模块`state_dict()`功能返回的键完全相符。

参数说明:

*   state_dict (dict) – 保存`parameters``persistent buffers``dict`

#### modules()

返回网络中所有模块的迭代器。

> NOTE: 重复的模块只返回一次。在以下示例中,`l`将仅返回一次。

```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) 
```

#### named_children()

返回包含子模块的迭代器,同时产生模块的名称以及模块本身。

例子:

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

#### named_modules(memo=None, prefix='')

返回网络中所有模块的迭代器,同时产生模块的名称以及模块本身。

> 注意: 重复的模块只返回一次。在以下示例中,`l`将仅返回一次。
> 
> ```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)) 
> ```
> 
> #### named_parameters(memo=None, prefix='')
> 
> 返回模块参数的迭代器,同时产生参数的名称以及参数本身 例如:
> 
> ```py
> >> for name, param in self.named_parameters():
> >>    if name in ['bias']:
> >>        print(param.size()) 
> ```

#### parameters()

返回模块参数的迭代器。 这通常被传递给优化器。

例子:

```py
for param in model.parameters():
    print(type(param.data), param.size())

<class 'torch.FloatTensor'> (20L,)
<class 'torch.FloatTensor'> (20L, 1L, 5L, 5L) 
```

#### register_backward_hook(hook)

在模块上注册一个向后的钩子。

每当计算相对于模块输入的梯度时,将调用该钩。挂钩应具有以下签名:

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

如果`module`有多个输入输出的话,那么`grad_input` `grad_output`将会是个`tuple``hook`不应该修改它的`arguments`,但是它可以选择性的返回关于输入的梯度,这个返回的梯度在后续的计算中会替代`grad_input`

这个函数返回一个句柄(`handle`)。它有一个方法 `handle.remove()`,可以用这个方法将`hook``module`移除。

#### register_buffer(name, tensor)

`module`添加一个持久缓冲区。

这通常用于注册不应被视为模型参数的缓冲区。例如,BatchNorm running_mean 不是参数,而是持久状态的一部分。

缓冲区可以使用给定的名称作为属性访问。

例子:

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

#### register_forward_hook(hook)

在模块上注册一个`forward hook`。 每次调用`forward()`计算输出的时候,这个`hook`就会被调用。它应该拥有以下签名:

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

`hook`不应该修改 `input``output`的值。 这个函数返回一个有`handle.remove()`方法的句柄(`handle`)。可以用这个方法将`hook``module`移除。

#### register_parameter(name, param)

`module`添加 `parameter`

该参数可以使用给定的名称作为属性访问。

#### state_dict(destination=None, prefix='')

返回包含模块整体状态的字典。

包括参数和持久缓冲区(例如运行平均值)。键是相应的参数和缓冲区名称。

例子:

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

#### train(mode=True)

将模块设置为训练模式。

仅仅当模型中有`Dropout``BatchNorm`是才会有影响。

#### zero_grad()

将所有模型参数的梯度设置为零。

### class torch.nn.Sequential(* args)

一个时序容器。`Modules` 会以他们传入的顺序被添加到容器中。当然,也可以传入一个`OrderedDict`

为了更容易理解,给出的是一个小例子:

```py
# Example of using Sequential

model = nn.Sequential(
          nn.Conv2d(1,20,5),
          nn.ReLU(),
          nn.Conv2d(20,64,5),
          nn.ReLU()
        )
# Example of using Sequential with OrderedDict
model = nn.Sequential(OrderedDict([
          ('conv1', nn.Conv2d(1,20,5)),
          ('relu1', nn.ReLU()),
          ('conv2', nn.Conv2d(20,64,5)),
          ('relu2', nn.ReLU())
        ])) 
```

### class torch.nn.ModuleList(modules=None)

`submodules`保存在一个`list`中。

`ModuleList`可以像一般的`Python list`一样被`索引`。而且`ModuleList`中包含的`modules`已经被正确的注册,对所有的`module method`可见。

参数说明:

*   modules (list, optional) – 要添加的模块列表

例子:

```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):
        # ModuleList can act as an iterable, or be indexed using ints
        for i, l in enumerate(self.linears):
            x = self.linears[i // 2](x) + l(x)
        return x 
```

#### append(module)

在列表末尾附加一个给定的模块。

参数说明:

*   module (nn.Module) – 要追加的模块

#### extend(modules)

最后从 Python 列表中追加模块。

参数说明:

*   modules(list) – 要附加的模块列表

### class torch.nn.ParameterList(parameters=None)

在列表中保存参数。

ParameterList 可以像普通 Python 列表一样进行索引,但是它包含的参数已经被正确注册,并且将被所有的 Module 方法都可见。

参数说明:

*   modules (list, 可选) – nn.Parameter 要添加的列表

例子:

```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):
        # ModuleList can act as an iterable, or be indexed using ints
        for i, p in enumerate(self.params):
            x = self.params[i // 2].mm(x) + p.mm(x)
        return x 
```

#### append(parameter)

在列表末尾添加一个给定的参数。

参数说明:

*   parameter (nn.Parameter) – 要追加的参数

#### extend(parameters)

在 Python 列表中附加参数。

参数说明:

*   parameters (list) – 要追加的参数列表

### class torch.nn.Conv1d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)

一维卷积层,输入的尺度是(N, C_in,L),输出尺度( N,C_out,L_out)的计算方式:

$$ out(N*i, C*{out*j})=bias(C* {out*j})+\sum^{C*{in}-1}*{k=0}weight(C*{out_j},k)\bigotimes input(N_i,k) $$

**说明**

`bigotimes`: 表示相关系数计算 `stride`: 控制相关系数的计算步长 `dilation`: 用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md) `groups`: 控制输入和输出之间的连接, `group=1`,输出是所有的输入的卷积;`group=2`,此时相当于有并排的两个卷积层,每个卷积层计算输入通道的一半,并且产生的输出是输出通道的一半,随后将这两个输出连接起来。

**Parameters:**

*   in_channels(`int`) – 输入信号的通道
*   out_channels(`int`) – 卷积产生的通道
*   kerner_size(`int` or `tuple`) - 卷积核的尺寸
*   stride(`int` or `tuple`, `optional`) - 卷积步长
*   padding (`int` or `tuple`, `optional`)- 输入的每一条边补充 0 的层数
*   dilation(`int` or `tuple`, `optional``) – 卷积核元素之间的间距
*   groups(`int`, `optional`) – 从输入通道到输出通道的阻塞连接数
*   bias(`bool`, `optional`) - 如果`bias=True`,添加偏置

**shape:** 输入: (N,C_in,L_in) 输出: (N,C_out,L_out) 输入输出的计算方式:

$$L*{out}=floor((L*{in}+2*padding-dilation*(kernerl_size-1)-1)/stride+1)$$

**变量:**

*   weight(`tensor`) - 卷积的权重,大小是(`out_channels`, `in_channels`, `kernel_size`)
*   bias(`tensor`) - 卷积的偏置系数,大小是(`out_channel`)

**example:**

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

### class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)

二维卷积层, 输入的尺度是(N, C_in,H,W),输出尺度(N,C_out,H_out,W_out)的计算方式:

$$out(N*i, C*{out*j})=bias(C*{out*j})+\sum^{C*{in}-1}*{k=0}weight(C*{out_j},k)\bigotimes input(N_i,k)$$

**说明** `bigotimes`: 表示二维的相关系数计算 `stride`: 控制相关系数的计算步长 `dilation`: 用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md) `groups`: 控制输入和输出之间的连接: `group=1`,输出是所有的输入的卷积;`group=2`,此时相当于有并排的两个卷积层,每个卷积层计算输入通道的一半,并且产生的输出是输出通道的一半,随后将这两个输出连接起来。

参数`kernel_size`,`stride,padding`,`dilation`也可以是一个`int`的数据,此时卷积 height 和 width 值相同;也可以是一个`tuple`数组,`tuple`的第一维度表示 height 的数值,tuple 的第二维度表示 width 的数值

**Parameters:**

*   in_channels(`int`) – 输入信号的通道
*   out_channels(`int`) – 卷积产生的通道
*   kerner_size(`int` or `tuple`) - 卷积核的尺寸
*   stride(`int` or `tuple`, `optional`) - 卷积步长
*   padding(`int` or `tuple`, `optional`) - 输入的每一条边补充 0 的层数
*   dilation(`int` or `tuple`, `optional`) – 卷积核元素之间的间距
*   groups(`int`, `optional`) – 从输入通道到输出通道的阻塞连接数
*   bias(`bool`, `optional`) - 如果`bias=True`,添加偏置

**shape:** input: (N,C_in,H_in,W_in) output: (N,C_out,H_out,W_out)

$$H*{out}=floor((H*{in}+2*padding[0]-dilation[0]*(kernerl_size[0]-1)-1)/stride[0]+1)$$

$$W*{out}=floor((W*{in}+2*padding[1]-dilation[1]*(kernerl_size[1]-1)-1)/stride[1]+1)$$

**变量:** weight(`tensor`) - 卷积的权重,大小是(`out_channels`, `in_channels`,`kernel_size`) bias(`tensor`) - 卷积的偏置系数,大小是(`out_channel`)

Examples:

```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 = autograd.Variable(torch.randn(20, 16, 50, 100))
>>> output = m(input) 
```

### class torch.nn.Conv3d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)

三维卷积层, 输入的尺度是(N, C_in,D,H,W),输出尺度(N,C_out,D_out,H_out,W_out)的计算方式:

$$out(N*i, C*{out*j})=bias(C*{out*j})+\sum^{C*{in}-1}*{k=0}weight(C*{out_j},k)\bigotimes input(N_i,k)$$

**说明** `bigotimes`: 表示二维的相关系数计算 `stride`: 控制相关系数的计算步长 `dilation`: 用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md) `groups`: 控制输入和输出之间的连接: `group=1`,输出是所有的输入的卷积;`group=2`,此时相当于有并排的两个卷积层,每个卷积层计算输入通道的一半,并且产生的输出是输出通道的一半,随后将这两个输出连接起来。 参数`kernel_size`,`stride`,`padding`,`dilation`可以是一个`int`的数据 - 卷积 height 和 width 值相同,也可以是一个有三个`int`数据的`tuple`数组,`tuple`的第一维度表示 depth 的数值,`tuple`的第二维度表示 height 的数值,`tuple`的第三维度表示 width 的数值

**Parameters:**

*   in_channels(`int`) – 输入信号的通道
*   out_channels(`int`) – 卷积产生的通道
*   kernel_size(`int` or `tuple`) - 卷积核的尺寸
*   stride(`int` or `tuple`, `optional`) - 卷积步长
*   padding(`int` or `tuple`, `optional`) - 输入的每一条边补充 0 的层数
*   dilation(`int` or `tuple`, `optional`) – 卷积核元素之间的间距
*   groups(`int`, `optional`) – 从输入通道到输出通道的阻塞连接数
*   bias(`bool`, `optional`) - 如果`bias=True`,添加偏置

**shape:** `input`: ((N, C*{in}, D*{in}, H*{in}, W*{in})) `output`: ((N, C*{out}, D*{out}, H*{out}, W*{out})) where (D*{out} = floor((D*{in} + 2 *padding[0] - dilation[0]* (kernel*size[0] - 1) - 1) / stride[0] + 1)) (H*{out} = floor((H*{in} + 2 _padding[1] - dilation[1]* (kernel*size[1] - 1) - 1) / stride[1] + 1)) (W*{out} = floor((W*{in} + 2 _padding[2] - dilation[2]* (kernel_size[2] - 1) - 1) / stride[2] + 1))

**变量:**

*   weight(`tensor`) - 卷积的权重,shape 是(`out_channels`, `in_channels`,`kernel_size`)`
*   bias(`tensor`) - 卷积的偏置系数,shape 是(`out_channel`

Examples:

```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 = autograd.Variable(torch.randn(20, 16, 10, 50, 100))
>>> output = m(input) 
```

### class torch.nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True, dilation=1)

1 维的解卷积操作(`transposed convolution operator`,注意改视作操作可视作解卷积操作,但并不是真正的解卷积操作) 该模块可以看作是`Conv1d`相对于其输入的梯度,有时(但不正确地)被称为解卷积操作。

**注意** 由于内核的大小,输入的最后的一些列的数据可能会丢失。因为输入和输出是不是完全的互相关。因此,用户可以进行适当的填充(padding 操作)。

**参数**

*   in_channels(`int`) – 输入信号的通道数
*   out_channels(`int`) – 卷积产生的通道
*   kernel_size(`int` or `tuple`) - 卷积核的大小
*   stride(`int` or `tuple`, `optional`) - 卷积步长
*   padding(`int` or `tuple`, `optional`) - 输入的每一条边补充 0 的层数
*   output_padding(`int` or `tuple`, `optional`) - 输出的每一条边补充 0 的层数
*   dilation(`int` or `tuple`, `optional`) – 卷积核元素之间的间距
*   groups(`int`, `optional`) – 从输入通道到输出通道的阻塞连接数
*   bias(`bool`, `optional`) - 如果`bias=True`,添加偏置

**shape:** 输入: ((N, C*{in}, L*{in})) 输出: ((N, C*{out}, L*{out})) where (L*{out} = (L*{in} - 1) *stride - 2* padding + kernel_size + output_padding)

**变量:**

*   weight(`tensor`) - 卷积的权重,大小是(`in_channels`, `in_channels`,`kernel_size`)
*   bias(`tensor`) - 卷积的偏置系数,大小是(`out_channel`)

### class torch.nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True, dilation=1)

2 维的转置卷积操作(`transposed convolution operator`,注意改视作操作可视作解卷积操作,但并不是真正的解卷积操作) 该模块可以看作是`Conv2d`相对于其输入的梯度,有时(但不正确地)被称为解卷积操作。

**说明**

`stride`: 控制相关系数的计算步长 `dilation`: 用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md) `groups`: 控制输入和输出之间的连接: `group=1`,输出是所有的输入的卷积;`group=2`,此时相当于有并排的两个卷积层,每个卷积层计算输入通道的一半,并且产生的输出是输出通道的一半,随后将这两个输出连接起来。

参数`kernel_size``stride``padding``dilation`数据类型: 可以是一个`int`类型的数据,此时卷积 height 和 width 值相同; 也可以是一个`tuple`数组(包含来两个`int`类型的数据),第一个`int`数据表示`height`的数值,第二个`int`类型的数据表示 width 的数值

> 注意 由于内核的大小,输入的最后的一些列的数据可能会丢失。因为输入和输出是不是完全的互相关。因此,用户可以进行适当的填充(`padding`操作)。

**参数:**

*   in_channels(`int`) – 输入信号的通道数
*   out_channels(`int`) – 卷积产生的通道数
*   kerner_size(`int` or `tuple`) - 卷积核的大小
*   stride(`int` or `tuple`,`optional`) - 卷积步长
*   padding(`int` or `tuple`, `optional`) - 输入的每一条边补充 0 的层数
*   output_padding(`int` or `tuple`, `optional`) - 输出的每一条边补充 0 的层数
*   dilation(`int` or `tuple`, `optional`) – 卷积核元素之间的间距
*   groups(`int`, `optional`) – 从输入通道到输出通道的阻塞连接数
*   bias(`bool`, `optional`) - 如果`bias=True`,添加偏置

**shape:** 输入: ((N, C*{in}, H*{in}, W*{in})) 输出: ((N, C*{out}, H*{out}, W*{out})) where (H*{out} = (H*{in} - 1) *stride[0] - 2* padding[0] + kernel*size[0] + output_padding[0]) (W*{out} = (W*{in} - 1) _stride[1] - 2* padding[1] + kernel_size[1] + output_padding[1])

**变量:**

*   weight(`tensor`) - 卷积的权重,大小是(`in_channels`, `in_channels`,`kernel_size`)
*   bias(`tensor`) - 卷积的偏置系数,大小是(`out_channel`

**Example**

```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 = autograd.Variable(torch.randn(20, 16, 50, 100))
>>> output = m(input)
>>> # exact output size can be also specified as an argument
>>> input = autograd.Variable(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]) 
```

### class torch.nn.ConvTranspose3d(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True, dilation=1)

3 维的转置卷积操作(`transposed convolution operator`,注意改视作操作可视作解卷积操作,但并不是真正的解卷积操作) 转置卷积操作将每个输入值和一个可学习权重的卷积核相乘,输出所有输入通道的求和

该模块可以看作是`Conv3d`相对于其输入的梯度,有时(但不正确地)被称为解卷积操作。

**说明**

`stride`: 控制相关系数的计算步长 `dilation`: 用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md) `groups`: 控制输入和输出之间的连接: `group=1`,输出是所有的输入的卷积;`group=2`,此时相当于有并排的两个卷积层,每个卷积层计算输入通道的一半,并且产生的输出是输出通道的一半,随后将这两个输出连接起来。

参数`kernel\_size``stride`, `padding``dilation`数据类型: 一个`int`类型的数据,此时卷积 height 和 width 值相同; 也可以是一个`tuple`数组(包含来两个`int`类型的数据),第一个`int`数据表示 height 的数值,tuple 的第二个 int 类型的数据表示 width 的数值

**注意** 由于内核的大小,输入的最后的一些列的数据可能会丢失。因为输入和输出是不是完全的互相关。因此,用户可以进行适当的填充(padding 操作)。

**参数:**

*   in_channels(`int`) – 输入信号的通道数
*   out_channels(`int`) – 卷积产生的通道数
*   kernel_size(`int` or `tuple`) - 卷积核的大小
*   stride(`int` or `tuple`, `optional`) - 卷积步长
*   padding(`int` or `tuple`, `optional`) - 输入的每一条边补充 0 的层数
*   output_padding(`int` or `tuple`, `optional`) - 输出的每一条边补充 0 的层数
*   dilation(`int` or `tuple`, `optional`) – 卷积核元素之间的间距
*   groups(`int`, `optional`) – 从输入通道到输出通道的阻塞连接数
*   bias(`bool`, `optional`) - 如果`bias=True`,添加偏置

**shape:** 输入: ((N, C*{in}, D*{in}, H*{in}, W*{in})) 输出: ((N, C*{out}, D*{out}, H*{out}, W*{out})) where (D*{out} = (D*{in} - 1) *stride[0] - 2* padding[0] + kernel*size[0] + output_padding[0]) (H*{out} = (H*{in} - 1) _stride[1] - 2* padding[1] + kernel*size[1] + output_padding[1]) (W*{out} = (W*{in} - 1) _stride[2] - 2* padding[2] + kernel_size[2] + output_padding[2])

**变量:**

*   weight(`tensor`) - 卷积的权重,大小是(`in_channels`, `in_channels`,`kernel_size`)
*   bias(`tensor`) - 卷积的偏置系数,大小是(`out_channel`

**Example**

```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.Conv3d(16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(0, 4, 2))
>>> input = autograd.Variable(torch.randn(20, 16, 10, 50, 100))
>>> output = m(input) 
```

### class torch.nn.MaxPool1d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)

对于输入信号的输入通道,提供 1 维最大池化(`max pooling`)操作

如果输入的大小是(N,C,L),那么输出的大小是(N,C,L_out)的计算方式是:

$$out(N*i, C_j,k)=max^{kernel_size-1}*{m=0}input(N_{i},C_j,stride*k+m)$$

如果`padding`不是 0,会在输入的每一边添加相应数目 0 `dilation`用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md)

**参数:**

*   kernel_size(`int` or `tuple`) - max pooling 的窗口大小
*   stride(`int` or `tuple`, `optional`) - max pooling 的窗口移动的步长。默认值是`kernel_size`
*   padding(`int` or `tuple`, `optional`) - 输入的每一条边补充 0 的层数
*   dilation(`int` or `tuple`, `optional`) – 一个控制窗口中元素步幅的参数
*   return_indices - 如果等于`True`,会返回输出最大值的序号,对于上采样操作会有帮助
*   ceil_mode - 如果等于`True`,计算输出信号大小的时候,会使用向上取整,代替默认的向下取整的操作

**shape:** 输入: (N,C_in,L_in) 输出: (N,C_out,L_out)

$$L*{out}=floor((L*{in} + 2*padding - dilation*(kernel_size - 1) - 1)/stride + 1$$

**example:**

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

### class torch.nn.MaxPool2d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)

对于输入信号的输入通道,提供 2 维最大池化(`max pooling`)操作

如果输入的大小是(N,C,H,W),那么输出的大小是(N,C,H_out,W_out)和池化窗口大小(kH,kW)的关系是:

$$out(N*i, C_j,k)=max^{kH-1}*{m=0}max^{kW-1}*{m=0}input(N*{i},C_j,stride[0]_h+m,stride[1]_w+n)$$

如果`padding`不是 0,会在输入的每一边添加相应数目 0 `dilation`用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md)

参数`kernel_size``stride`, `padding``dilation`数据类型: 可以是一个`int`类型的数据,此时卷积 height 和 width 值相同; 也可以是一个`tuple`数组(包含来两个 int 类型的数据),第一个`int`数据表示 height 的数值,`tuple`的第二个 int 类型的数据表示 width 的数值

**参数:**

*   kernel_size(`int` or `tuple`) - max pooling 的窗口大小
*   stride(`int` or `tuple`, `optional`) - max pooling 的窗口移动的步长。默认值是`kernel_size`
*   padding(`int` or `tuple`, `optional`) - 输入的每一条边补充 0 的层数
*   dilation(`int` or `tuple`, `optional`) – 一个控制窗口中元素步幅的参数
*   return_indices - 如果等于`True`,会返回输出最大值的序号,对于上采样操作会有帮助
*   ceil_mode - 如果等于`True`,计算输出信号大小的时候,会使用向上取整,代替默认的向下取整的操作

**shape:** 输入: (N,C,H_{in},W_in) 输出: (N,C,H_out,W_out)

$$H*{out}=floor((H*{in} + 2*padding[0] - dilation[0]*(kernel_size[0] - 1) - 1)/stride[0] + 1$$

$$W*{out}=floor((W*{in} + 2*padding[1] - dilation[1]*(kernel_size[1] - 1) - 1)/stride[1] + 1$$

**example:**

```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 = autograd.Variable(torch.randn(20, 16, 50, 32))
>>> output = m(input) 
```

### class torch.nn.MaxPool3d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)

对于输入信号的输入通道,提供 3 维最大池化(max pooling)操作

如果输入的大小是(N,C,D,H,W),那么输出的大小是(N,C,D,H_out,W_out)和池化窗口大小(kD,kH,kW)的关系是:

$$out(N*i,C_j,d,h,w)=max^{kD-1}*{m=0}max^{kH-1}*{m=0}max^{kW-1}*{m=0}$$

$$input(N_{i},C_j,stride[0]_k+d,stride[1]_h+m,stride[2]*w+n)$$

如果`padding`不是 0,会在输入的每一边添加相应数目 0 `dilation`用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md)

参数`kernel_size``stride`, `padding``dilation`数据类型: 可以是`int`类型的数据,此时卷积 height 和 width 值相同; 也可以是一个`tuple`数组(包含来两个`int`类型的数据),第一个`int`数据表示 height 的数值,`tuple`的第二个`int`类型的数据表示 width 的数值

**参数:**

*   kernel_size(`int` or `tuple`) - max pooling 的窗口大小
*   stride(`int` or `tuple`, `optional`) - max pooling 的窗口移动的步长。默认值是 kernel_size
*   padding(`int` or `tuple`, `optional`) - 输入的每一条边补充 0 的层数
*   dilation(`int` or `tuple`, `optional`) – 一个控制窗口中元素步幅的参数
*   return_indices - 如果等于`True`,会返回输出最大值的序号,对于上采样操作会有帮助
*   ceil_mode - 如果等于`True`,计算输出信号大小的时候,会使用向上取整,代替默认的向下取整的操作

**shape:** 输入: (N,C,H_in,W_in) 输出: (N,C,H_out,W_out)

$$D*{out}=floor((D*{in} + 2*padding[0] - dilation[0]*(kernel_size[0] - 1) - 1)/stride[0] + 1)$$

$$H*{out}=floor((H*{in} + 2*padding[1] - dilation[1]*(kernel_size[0] - 1) - 1)/stride[1] + 1)$$

$$W*{out}=floor((W*{in} + 2*padding[2] - dilation[2]*(kernel_size[2] - 1) - 1)/stride[2] + 1)$$

**example:**

```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 = autograd.Variable(torch.randn(20, 16, 50,44, 31))  
>>> output = m(input) 
```

#### class torch.nn.MaxUnpool1d(kernel_size, stride=None, padding=0)

`Maxpool1d`的逆过程,不过并不是完全的逆过程,因为在`maxpool1d`的过程中,一些最大值的已经丢失。 `MaxUnpool1d`输入`MaxPool1d`的输出,包括最大值的索引,并计算所有`maxpool1d`过程中非最大值被设置为零的部分的反向。

**注意:** `MaxPool1d`可以将多个输入大小映射到相同的输出大小。因此,反演过程可能会变得模棱两可。 为了适应这一点,可以在调用中将输出大小(`output_size`)作为额外的参数传入。 具体用法,请参阅下面的输入和示例

**参数:**

*   kernel_size(`int` or `tuple`) - max pooling 的窗口大小
*   stride(`int` or `tuple`, `optional`) - max pooling 的窗口移动的步长。默认值是`kernel_size`
*   padding(`int` or `tuple`, `optional`) - 输入的每一条边补充 0 的层数

**输入:** `input`:需要转换的`tensor` `indices`:Maxpool1d 的索引号 `output_size`:一个指定输出大小的`torch.Size`

**shape:** `input`: (N,C,H_in) `output`:(N,C,H_out)

$$H*{out}=(H*{in}-1)_stride[0]-2_padding[0]+kernel_size[0]$$ 也可以使用`output_size`指定输出的大小

**Example:**

```py
>>> pool = nn.MaxPool1d(2, stride=2, return_indices=True)
>>> unpool = nn.MaxUnpool1d(2, stride=2)
>>> input = Variable(torch.Tensor([[[1, 2, 3, 4, 5, 6, 7, 8]]]))
>>> output, indices = pool(input)
>>> unpool(output, indices)
    Variable containing:
    (0 ,.,.) =
       0   2   0   4   0   6   0   8
    [torch.FloatTensor of size 1x1x8]

>>> # Example showcasing the use of output_size
>>> input = Variable(torch.Tensor([[[1, 2, 3, 4, 5, 6, 7, 8, 9]]]))
>>> output, indices = pool(input)
>>> unpool(output, indices, output_size=input.size())
    Variable containing:
    (0 ,.,.) =
       0   2   0   4   0   6   0   8   0
    [torch.FloatTensor of size 1x1x9]
>>> unpool(output, indices)
    Variable containing:
    (0 ,.,.) =
       0   2   0   4   0   6   0   8
    [torch.FloatTensor of size 1x1x8] 
```

#### class torch.nn.MaxUnpool2d(kernel_size, stride=None, padding=0)

`Maxpool2d`的逆过程,不过并不是完全的逆过程,因为在 maxpool2d 的过程中,一些最大值的已经丢失。 `MaxUnpool2d`的输入是`MaxPool2d`的输出,包括最大值的索引,并计算所有`maxpool2d`过程中非最大值被设置为零的部分的反向。

**注意:** `MaxPool2d`可以将多个输入大小映射到相同的输出大小。因此,反演过程可能会变得模棱两可。 为了适应这一点,可以在调用中将输出大小(`output_size`)作为额外的参数传入。具体用法,请参阅下面示例

**参数:**

*   kernel_size(`int` or `tuple`) - max pooling 的窗口大小
*   stride(`int` or `tuple`, `optional`) - max pooling 的窗口移动的步长。默认值是`kernel_size`
*   padding(`int` or `tuple`, `optional`) - 输入的每一条边补充 0 的层数

**输入:** `input`:需要转换的`tensor` `indices`:Maxpool1d 的索引号 `output_size`:一个指定输出大小的`torch.Size`

**大小:** `input`: (N,C,H_in,W_in) `output`:(N,C,H_out,W_out)

$$H*{out}=(H*{in}-1)_stride[0]-2_padding[0]+kernel_size[0]$$

$$W*{out}=(W*{in}-1)_stride[1]-2_padding[1]+kernel_size[1]$$

也可以使用`output_size`指定输出的大小

**Example:**

```py
>>> pool = nn.MaxPool2d(2, stride=2, return_indices=True)
>>> unpool = nn.MaxUnpool2d(2, stride=2)
>>> input = Variable(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)
    Variable containing:
    (0 ,0 ,.,.) =
       0   0   0   0
       0   6   0   8
       0   0   0   0
       0  14   0  16
    [torch.FloatTensor of size 1x1x4x4]

>>> # specify a different output size than input size
>>> unpool(output, indices, output_size=torch.Size([1, 1, 5, 5]))
    Variable containing:
    (0 ,0 ,.,.) =
       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
    [torch.FloatTensor of size 1x1x5x5] 
```

#### class torch.nn.MaxUnpool3d(kernel_size, stride=None, padding=0)

`Maxpool3d`的逆过程,不过并不是完全的逆过程,因为在`maxpool3d`的过程中,一些最大值的已经丢失。 `MaxUnpool3d`的输入就是`MaxPool3d`的输出,包括最大值的索引,并计算所有`maxpool3d`过程中非最大值被设置为零的部分的反向。

**注意:** `MaxPool3d`可以将多个输入大小映射到相同的输出大小。因此,反演过程可能会变得模棱两可。为了适应这一点,可以在调用中将输出大小(`output_size`)作为额外的参数传入。具体用法,请参阅下面的输入和示例

**参数:**

*   kernel_size(`int` or `tuple`) - Maxpooling 窗口大小
*   stride(`int` or `tuple`, `optional`) - max pooling 的窗口移动的步长。默认值是`kernel_size`
*   padding(`int` or `tuple`, `optional`) - 输入的每一条边补充 0 的层数

**输入:** `input`:需要转换的`tensor` `indices``Maxpool1d`的索引序数 `output_size`:一个指定输出大小的`torch.Size`

**大小:** `input`: (N,C,D_in,H_in,W_in) `outpu`t:(N,C,D_out,H_out,W_out)

$$ \begin{aligned} D*{out}=(D*{in}-1)*stride[0]-2_padding[0]+kernel_size[0]\ H*{out}=(H*{in}-1)_stride[1]-2_padding[0]+kernel_size[1]\ W*{out}=(W_{in}-1)_stride[2]-2_padding[2]+kernel_size[2] \end{aligned} $$

也可以使用`output_size`指定输出的大小

**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(Variable(torch.randn(20, 16, 51, 33, 15)))
>>> unpooled_output = unpool(output, indices)
>>> unpooled_output.size()
torch.Size([20, 16, 51, 33, 15]) 
```

### class torch.nn.AvgPool1d(kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True)

对信号的输入通道,提供 1 维平均池化(average pooling ) 输入信号的大小(N,C,L),输出大小(N,C,L_out)和池化窗口大小 k 的关系是:

$$out(N*i,C_j,l)=1/k*\sum^{k}*{m=0}input(N*{i},C*{j},stride*l+m)$$ 如果`padding`不是 0,会在输入的每一边添加相应数目 0

**参数:**

*   kernel_size(`int` or `tuple`) - 池化窗口大小
*   stride(`int` or `tuple`, `optional`) - max pooling 的窗口移动的步长。默认值是`kernel_size`
*   padding(`int` or `tuple`, `optional`) - 输入的每一条边补充 0 的层数
*   dilation(`int` or `tuple`, `optional`) – 一个控制窗口中元素步幅的参数
*   return_indices - 如果等于`True`,会返回输出最大值的序号,对于上采样操作会有帮助
*   ceil_mode - 如果等于`True`,计算输出信号大小的时候,会使用向上取整,代替默认的向下取整的操作

**大小:** `input`:(N,C,L_in) `output`:(N,C,L_out)

$$L*{out}=floor((L*{in}+2*padding-kernel_size)/stride+1)$$

**Example:**

```py
>>> # pool with window of size=3, stride=2
>>> m = nn.AvgPool1d(3, stride=2)
>>> m(Variable(torch.Tensor([[[1,2,3,4,5,6,7]]])))
Variable containing:
    (0 ,.,.) =
    2  4  6
    [torch.FloatTensor of size 1x1x3] 
```

### class torch.nn.AvgPool2d(kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True)

对信号的输入通道,提供 2 维的平均池化(average pooling ) 输入信号的大小(N,C,H,W),输出大小(N,C,H_out,W_out)和池化窗口大小(kH,kW)的关系是:

$$ out(N*i,C_j,h,w)=1/(kH_kW)*\sum^{kH-1}*{m=0}\sum^{kW-1}*{n=0}input(N*{i},C*{j},stride[0]_h+m,stride[1]_w+n)$$

如果`padding`不是 0,会在输入的每一边添加相应数目 0

**参数:**

*   kernel_size(`int` or `tuple`) - 池化窗口大小
*   stride(`int` or `tuple`, `optional`) - max pooling 的窗口移动的步长。默认值是`kernel_size`
*   padding(`int` or `tuple`, `optional`) - 输入的每一条边补充 0 的层数
*   dilation(`int` or `tuple`, `optional`) – 一个控制窗口中元素步幅的参数
*   ceil_mode - 如果等于`True`,计算输出信号大小的时候,会使用向上取整,代替默认的向下取整的操作
*   count_include_pad - 如果等于`True`,计算平均池化时,将包括`padding`填充的 0

**shape:** `input`: (N,C,H_in,W_in) `output`: (N,C,H_out,W_out)

$$\begin{aligned} H*{out}=floor((H*{in}+2*padding[0]-kernel*size[0])/stride[0]+1)\ W*{out}=floor((W_{in}+2*padding[1]-kernel_size[1])/stride[1]+1) \end{aligned} $$

**Example:**

```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 = autograd.Variable(torch.randn(20, 16, 50, 32))
>>> output = m(input) 
```

### class torch.nn.AvgPool3d(kernel_size, stride=None)

对信号的输入通道,提供 3 维的平均池化(`average pooling`) 输入信号的大小(N,C,D,H,W),输出大小(N,C,D_out,H_out,W_out)和池化窗口大小(kD,kH,kW)的关系是:

$$ \begin{aligned} out(N*i,C_j,d,h,w)=1/(kD_kH_kW)*\sum^{kD-1}*{k=0}\sum^{kH-1}*{m=0}\sum^{kW-1}*{n=0}input(N*{i},C*{j},stride[0]_d+k,stride[1]_h+m,stride[2]*w+n) \end{aligned} $$ 如果`padding`不是 0,会在输入的每一边添加相应数目 0

**参数:**

*   kernel_size(`int` or `tuple`) - 池化窗口大小
*   stride(`int` or `tuple`, `optional`) - max `pooling`的窗口移动的步长。默认值是`kernel_size`

**shape:** 输入大小:(N,C,D*in,H_in,W_in) 输出大小:(N,C,D_out,H_out,W_out) $$\begin{aligned} D*{out}=floor((D*{in}+2*padding[0]-kernel_size[0])/stride[0]+1)\ H*{out}=floor((H*{in}+2*padding[1]-kernel_size[1])/stride[1]+1)\ W*{out}=floor((W_{in}+2*padding[2]-kernel_size[2])/stride[2]+1) \end{aligned} $$

**Example:**

```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 = autograd.Variable(torch.randn(20, 16, 50,44, 31))
>>> output = m(input) 
```

### class torch.nn.FractionalMaxPool2d(kernel_size, output_size=None, output_ratio=None, return_indices=False, _random_samples=None)

对输入的信号,提供 2 维的分数最大化池化操作 分数最大化池化的细节请阅读[论文](https://arxiv.org/abs/1412.6071) 由目标输出大小确定的随机步长,在$kH*kW$区域进行最大池化操作。输出特征和输入特征的数量相同。

**参数:**

*   kernel_size(`int` or `tuple`) - 最大池化操作时的窗口大小。可以是一个数字(表示`K*K`的窗口),也可以是一个元组(`kh*kw`
*   output_size - 输出图像的尺寸。可以使用一个`tuple`指定(oH,oW),也可以使用一个数字 oH 指定一个 oH*oH 的输出。
*   output_ratio – 将输入图像的大小的百分比指定为输出图片的大小,使用一个范围在(0,1)之间的数字指定
*   return_indices - 默认值`False`,如果设置为`True`,会返回输出的索引,索引对 `nn.MaxUnpool2d`有用。

**Example:**

```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 = autograd.Variable(torch.randn(20, 16, 50, 32))
>>> output = m(input) 
```

### class torch.nn.LPPool2d(norm_type, kernel_size, stride=None, ceil_mode=False)

对输入信号提供 2 维的幂平均池化操作。 输出的计算方式:

$$f(x)=pow(sum(X,p),1/p)$$

*   当 p 为无穷大的时候时,等价于最大池化操作
*`p=1`时,等价于平均池化操作

参数`kernel_size`, `stride`的数据类型:

*   `int`,池化窗口的宽和高相等
*   `tuple`数组(两个数字的),一个元素是池化窗口的高,另一个是宽

**参数**

*   kernel_size: 池化窗口的大小
*   stride:池化窗口移动的步长。`kernel_size`是默认值
*   ceil_mode: `ceil_mode=True`时,将使用向下取整代替向上取整

**shape**

*   输入:(N,C,H_in,W_in)
*   输出:(N,C,H*out,W_out) $$\begin{aligned} H*{out} = floor((H*{in}+2_padding[0]-dilation[0]*(kernel*size[0]-1)-1)/stride[0]+1)\ W*{out} = floor((W*{in}+2_padding[1]-dilation[1]*(kernel_size[1]-1)-1)/stride[1]+1) \end{aligned} $$

**Example:**

```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 = autograd.Variable(torch.randn(20, 16, 50, 32))
>>> output = m(input) 
```

### class torch.nn.AdaptiveMaxPool1d(output_size, return_indices=False)

对输入信号,提供 1 维的自适应最大池化操作 对于任何输入大小的输入,可以将输出尺寸指定为 H,但是输入和输出特征的数目不会变化。

**参数:**

*   output_size: 输出信号的尺寸
*   return_indices: 如果设置为`True`,会返回输出的索引。对 `nn.MaxUnpool1d`有用,默认值是`False`

**Example:**

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

### class torch.nn.AdaptiveMaxPool2d(output_size, return_indices=False)

对输入信号,提供 2 维的自适应最大池化操作 对于任何输入大小的输入,可以将输出尺寸指定为 H*W,但是输入和输出特征的数目不会变化。

**参数:**

*   output_size: 输出信号的尺寸,可以用(H,W)表示`H*W`的输出,也可以使用数字`H`表示`H*H`大小的输出
*   return_indices: 如果设置为`True`,会返回输出的索引。对 `nn.MaxUnpool2d`有用,默认值是`False`

**Example:**

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

### class torch.nn.AdaptiveAvgPool1d(output_size)

对输入信号,提供 1 维的自适应平均池化操作 对于任何输入大小的输入,可以将输出尺寸指定为 H*W,但是输入和输出特征的数目不会变化。

**参数:**

*   output_size: 输出信号的尺寸

**Example:**

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

### class torch.nn.AdaptiveAvgPool2d(output_size)

对输入信号,提供 2 维的自适应平均池化操作 对于任何输入大小的输入,可以将输出尺寸指定为`H*W`,但是输入和输出特征的数目不会变化。

**参数:**

*   output_size: 输出信号的尺寸,可以用(H,W)表示`H*W`的输出,也可以使用耽搁数字 H 表示 H*H 大小的输出

**Example:**

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

## Non-Linear Activations

> class torch.nn.ReLU(inplace=False)

对输入运用修正线性单元函数${ReLU}(x)= max(0, x)$,

参数: inplace-选择是否进行覆盖运算

shape:

*   输入:$(N, *)$,*代表任意数目附加维度
*   输出:$(N, *)$,与输入拥有同样的 shape 属性

例子:

```py
>>> m = nn.ReLU()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input)) 
```

> class torch.nn.ReLU6(inplace=False)

对输入的每一个元素运用函数${ReLU6}(x) = min(max(0,x), 6)$,

参数: inplace-选择是否进行覆盖运算

shape:

*   输入:$(N, *)$,*代表任意数目附加维度
*   输出:$(N, *)$,与输入拥有同样的 shape 属性

例子:

```py
>>> m = nn.ReLU6()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input)) 
```

> class torch.nn.ELU(alpha=1.0, inplace=False)

对输入的每一个元素运用函数$f(x) = max(0,x) + min(0, alpha * (e^x - 1))$,

shape:

*   输入:$(N, *)$,星号代表任意数目附加维度
*   输出:$(N, *)$与输入拥有同样的 shape 属性

例子:

```py
>>> m = nn.ELU()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input)) 
```

> class torch.nn.PReLU(num_parameters=1, init=0.25)

对输入的每一个元素运用函数$PReLU(x) = max(0,x) + a * min(0,x)$,`a`是一个可学习参数。当没有声明时,`nn.PReLU()`在所有的输入中只有一个参数`a`;如果是`nn.PReLU(nChannels)``a`将应用到每个输入。

注意:当为了表现更佳的模型而学习参数`a`时不要使用权重衰减(weight decay)

参数:

*   num_parameters:需要学习的`a`的个数,默认等于 1
*   init:`a`的初始值,默认等于 0.25

shape:

*   输入:$(N, *)$,*代表任意数目附加维度
*   输出:$(N, *)$,与输入拥有同样的 shape 属性

例子:

```py
>>> m = nn.PReLU()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input)) 
```

> class torch.nn.LeakyReLU(negative_slope=0.01, inplace=False)

对输入的每一个元素运用$f(x) = max(0, x) + {negative_slope} * min(0, x)$

参数:

*   negative_slope:控制负斜率的角度,默认等于 0.01
*   inplace-选择是否进行覆盖运算

shape:

*   输入:$(N, *)$,*代表任意数目附加维度
*   输出:$(N, *)$,与输入拥有同样的 shape 属性

例子:

```py
>>> m = nn.LeakyReLU(0.1)
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input)) 
```

> class torch.nn.Threshold(threshold, value, inplace=False)

Threshold 定义:

$$ y = x ,if\ x >= threshold\ y = value,if\ x < threshold $$

参数:

*   threshold:阈值
*   value:输入值小于阈值则会被 value 代替
*   inplace:选择是否进行覆盖运算

shape:

*   输入:$(N, *)$,*代表任意数目附加维度
*   输出:$(N, *)$,与输入拥有同样的 shape 属性

例子:

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

> class torch.nn.Hardtanh(min_value=-1, max_value=1, inplace=False)

对每个元素,

$$ f(x) = +1, if\ x > 1;\ f(x) = -1, if\ x < -1;\ f(x) = x, otherwise $$

线性区域的范围[-1,1]可以被调整

参数:

*   min_value:线性区域范围最小值
*   max_value:线性区域范围最大值
*   inplace:选择是否进行覆盖运算

shape:

*   输入:(N, *),*表示任意维度组合
*   输出:(N, *),与输入有相同的 shape 属性

例子:

```py
>>> m = nn.Hardtanh()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input)) 
```

> class torch.nn.Sigmoid

对每个元素运用 Sigmoid 函数,Sigmoid 定义如下:

$$f(x) = 1 / ( 1 + e^{-x})$$

shape:

*   输入:(N, *),*表示任意维度组合
*   输出:(N, *),与输入有相同的 shape 属性

例子:

```py
>>> m = nn.Sigmoid()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input)) 
```

> class torch.nn.Tanh

对输入的每个元素,

$$f(x) = \frac{e^{x} - e^{-x}} {e^{x} + e^{x}}$$

shape:

*   输入:(N, *),*表示任意维度组合
*   输出:(N, *),与输入有相同的 shape 属性

例子:

```py
>>> m = nn.Tanh()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input)) 
```

> class torch.nn.LogSigmoid

对输入的每个元素,$LogSigmoid(x) = log( 1 / ( 1 + e^{-x}))$

shape:

*   输入:(N, *),*表示任意维度组合
*   输出:(N, *),与输入有相同的 shape 属性

例子:

```py
>>> m = nn.LogSigmoid()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input)) 
```

> class torch.nn.Softplus(beta=1, threshold=20)

对每个元素运用 Softplus 函数,Softplus 定义如下:

$$f(x) = \frac{1}{beta} *log(1 + e^{(beta* x_i)})$$

Softplus 函数是 ReLU 函数的平滑逼近,Softplus 函数可以使得输出值限定为正数。

为了保证数值稳定性,线性函数的转换可以使输出大于某个值。

参数:

*   beta:Softplus 函数的 beta 值
*   threshold:阈值

shape:

*   输入:(N, *),*表示任意维度组合
*   输出:(N, *),与输入有相同的 shape 属性

例子:

```py
>>> m = nn.Softplus()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input)) 
```

> class torch.nn.Softshrink(lambd=0.5)

对每个元素运用 Softshrink 函数,Softshrink 函数定义如下:

$$ f(x) = x-lambda, if\ x > lambda\ f(x) = x+lambda, if\ x < -lambda\ f(x) = 0, otherwise $$

参数:

lambd:Softshrink 函数的 lambda 值,默认为 0.5

shape:

*   输入:(N, *),*表示任意维度组合
*   输出:(N, *),与输入有相同的 shape 属性

例子:

```py
>>> m = nn.Softshrink()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input)) 
```

> class torch.nn.Softsign

$f(x) = x / (1 + |x|)$

shape:

*   输入:(N, *),*表示任意维度组合
*   输出:(N, *),与输入有相同的 shape 属性

例子:

```py
>>> m = nn.Softsign()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input)) 
```

> class torch.nn.Softshrink(lambd=0.5)

对每个元素运用 Tanhshrink 函数,Tanhshrink 函数定义如下:

$$ Tanhshrink(x) = x - Tanh(x) $$

shape:

*   输入:(N, *),*表示任意维度组合
*   输出:(N, *),与输入有相同的 shape 属性

例子:

```py
>>> m = nn.Tanhshrink()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input)) 
```

> class torch.nn.Softmin

对 n 维输入张量运用 Softmin 函数,将张量的每个元素缩放到(0,1)区间且和为 1。Softmin 函数定义如下:

$$f_i(x) = \frac{e^{(-x_i - shift)}} { \sum^j e^{(-x_j - shift)}},shift = max (x_i)$$

shape:

*   输入:(N, L)
*   输出:(N, L)

例子:

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

* * *

> class torch.nn.Softmax

对 n 维输入张量运用 Softmax 函数,将张量的每个元素缩放到(0,1)区间且和为 1。Softmax 函数定义如下:

$$f_i(x) = \frac{e^{(x_i - shift)}} { \sum^j e^{(x_j - shift)}},shift = max (x_i)$$

shape:

*   输入:(N, L)
*   输出:(N, L)

返回结果是一个与输入维度相同的张量,每个元素的取值范围在(0,1)区间。

例子:

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

> class torch.nn.LogSoftmax

对 n 维输入张量运用 LogSoftmax 函数,LogSoftmax 函数定义如下:

$$f_i(x) = log \frac{e^{(x_i)}} {a}, a = \sum^j e^{(x_j)}$$

shape:

*   输入:(N, L)
*   输出:(N, L)

例子:

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

### class torch.nn.BatchNorm1d(num_features, eps=1e-05, momentum=0.1, affine=True)

对小批量(mini-batch)的 2d 或 3d 输入进行批标准化(Batch Normalization)操作

$$ y = \frac{x - mean[x]}{ \sqrt{Var[x]} + \epsilon} * gamma + beta $$

在每一个小批量(mini-batch)数据中,计算输入各个维度的均值和标准差。gamma 与 beta 是可学习的大小为 C 的参数向量(C 为输入大小)

在训练时,该层计算每次输入的均值与方差,并进行移动平均。移动平均默认的动量值为 0.1。

在验证时,训练求得的均值/方差将用于标准化验证数据。

**参数:**

*   **num_features:** 来自期望输入的特征数,该期望输入的大小为'batch_size x num_features [x width]'
*   **eps:** 为保证数值稳定性(分母不能趋近或取 0),给分母加上的值。默认为 1e-5。
*   **momentum:** 动态均值和动态方差所使用的动量。默认为 0.1。
*   **affine:** 一个布尔值,当设为 true,给该层添加可学习的仿射变换参数。

**Shape:**

*   输入:(N, C)或者(N, C, L)
*   输出:(N, C)或者(N,C,L)(输入输出相同)

**例子**

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

* * *

### class torch.nn.BatchNorm2d(num_features, eps=1e-05, momentum=0.1, affine=True)

对小批量(mini-batch)3d 数据组成的 4d 输入进行批标准化(Batch Normalization)操作

$$ y = \frac{x - mean[x]}{ \sqrt{Var[x]} + \epsilon} * gamma + beta $$

在每一个小批量(mini-batch)数据中,计算输入各个维度的均值和标准差。gamma 与 beta 是可学习的大小为 C 的参数向量(C 为输入大小)

在训练时,该层计算每次输入的均值与方差,并进行移动平均。移动平均默认的动量值为 0.1。

在验证时,训练求得的均值/方差将用于标准化验证数据。

**参数:**

*   **num_features:** 来自期望输入的特征数,该期望输入的大小为'batch_size x num_features x height x width'
*   **eps:** 为保证数值稳定性(分母不能趋近或取 0),给分母加上的值。默认为 1e-5。
*   **momentum:** 动态均值和动态方差所使用的动量。默认为 0.1。
*   **affine:** 一个布尔值,当设为 true,给该层添加可学习的仿射变换参数。

**Shape:**

*   输入:(N, C,H, W)
*   输出:(N, C, H, W)(输入输出相同)

**例子**

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

* * *

### class torch.nn.BatchNorm3d(num_features, eps=1e-05, momentum=0.1, affine=True)

对小批量(mini-batch)4d 数据组成的 5d 输入进行批标准化(Batch Normalization)操作

$$ y = \frac{x - mean[x]}{ \sqrt{Var[x]} + \epsilon} * gamma + beta $$

在每一个小批量(mini-batch)数据中,计算输入各个维度的均值和标准差。gamma 与 beta 是可学习的大小为 C 的参数向量(C 为输入大小)

在训练时,该层计算每次输入的均值与方差,并进行移动平均。移动平均默认的动量值为 0.1。

在验证时,训练求得的均值/方差将用于标准化验证数据。

**参数:**

*   **num_features:** 来自期望输入的特征数,该期望输入的大小为'batch_size x num_features depth x height x width'
*   **eps:** 为保证数值稳定性(分母不能趋近或取 0),给分母加上的值。默认为 1e-5。
*   **momentum:** 动态均值和动态方差所使用的动量。默认为 0.1。
*   **affine:** 一个布尔值,当设为 true,给该层添加可学习的仿射变换参数。

**Shape:**

*   输入:(N, C,D, H, W)
*   输出:(N, C, D, H, W)(输入输出相同)

**例子**

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

* * *

### class torch.nn.RNN( *args, ** kwargs)

将一个多层的 `Elman RNN`,激活函数为`tanh`或者`ReLU`,用于输入序列。

对输入序列中每个元素,`RNN`每层的计算公式为 $$ h*t=tanh(w*{ih} *x_t+b*{ih}+w*{hh}* h*{t-1}+b*{hh}) $$ $h_t$是时刻$t$的隐状态。 $x_t$是上一层时刻$t$的隐状态,或者是第一层在时刻$t$的输入。如果`nonlinearity='relu'`,那么将使用`relu`代替`tanh`作为激活函数。

参数说明:

*   input_size – 输入`x`的特征数量。

*   hidden_size – 隐层的特征数量。

*   num_layers – RNN 的层数。

*   nonlinearity – 指定非线性函数使用`tanh`还是`relu`。默认是`tanh`

*   bias – 如果是`False`,那么 RNN 层就不会使用偏置权重 $b_ih$和$b_hh$,默认是`True`

*   batch_first – 如果`True`的话,那么输入`Tensor`的 shape 应该是[batch_size, time_step, feature],输出也是这样。

*   dropout – 如果值非零,那么除了最后一层外,其它层的输出都会套上一个`dropout`层。

*   bidirectional – 如果`True`,将会变成一个双向`RNN`,默认为`False`

`RNN`的输入: **(input, h_0)**

*   input (seq_len, batch, input_size): 保存输入序列特征的`tensor``input`可以是被填充的变长的序列。细节请看`torch.nn.utils.rnn.pack_padded_sequence()`

*   h_0 (num_layers * num_directions, batch, hidden_size): 保存着初始隐状态的`tensor`

`RNN`的输出: **(output, h_n)**

*   output (seq_len, batch, hidden_size * num_directions): 保存着`RNN`最后一层的输出特征。如果输入是被填充过的序列,那么输出也是被填充的序列。
*   h_n (num_layers * num_directions, batch, hidden_size): 保存着最后一个时刻隐状态。

`RNN`模型参数:

*   weight_ih_l[k] – 第`k`层的 `input-hidden` 权重, 可学习,形状是`(input_size x hidden_size)`

*   weight_hh_l[k] – 第`k`层的 `hidden-hidden` 权重, 可学习,形状是`(hidden_size x hidden_size)`

*   bias_ih_l[k] – 第`k`层的 `input-hidden` 偏置, 可学习,形状是`(hidden_size)`

*   bias_hh_l[k] – 第`k`层的 `hidden-hidden` 偏置, 可学习,形状是`(hidden_size)`

示例:

```py
rnn = nn.RNN(10, 20, 2)
input = Variable(torch.randn(5, 3, 10))
h0 = Variable(torch.randn(2, 3, 20))
output, hn = rnn(input, h0) 
```

### class torch.nn.LSTM( *args, ** kwargs)

将一个多层的 `(LSTM)` 应用到输入序列。

对输入序列的每个元素,`LSTM`的每层都会执行以下计算: [\begin{split}\begin{array}{ll} i*t = \mathrm{sigmoid}(W*{ii} x*t + b*{ii} + W*{hi} h*{(t-1)} + b*{hi}) \ f_t = \mathrm{sigmoid}(W*{if} x*t + b*{if} + W*{hf} h*{(t-1)} + b*{hf}) \ g_t = \tanh(W*{ig} x*t + b*{ig} + W*{hc} h*{(t-1)} + b*{hg}) \ o_t = \mathrm{sigmoid}(W*{io} x*t + b*{io} + W*{ho} h*{(t-1)} + b*{ho}) \ c_t = f_t * c*{(t-1)} + i*t _g_t \ h_t = o_t* \tanh(c_t) \end{array}\end{split}]是时刻$t$的隐状态,$c_t$是时刻$t$的细胞状态,$x_t$是上一层的在时刻$t$的隐状态或者是第一层在时刻$t$的输入。$i_t, f_t, g_t, o_t$ 分别代表 输入门,遗忘门,细胞

*class*`torch.nn.``GRU`(**args*, ***kwargs*)[[source]](http://pytorch.org/docs/master/_modules/torch/nn/modules/rnn.html#GRU)

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:[\begin{split}\begin{array}{ll} r*t = \mathrm{sigmoid}(W*{ir} x*t + b*{ir} + W*{hr} h*{(t-1)} + b*{hr}) \ z_t = \mathrm{sigmoid}(W*{iz} x*t + b*{iz} + W*{hz} h*{(t-1)} + b*{hz}) \ n_t = \tanh(W*{in} x*t + b*{in} + r*t * (W*{hn} h*{(t-1)}+ b*{hn})) \ h*t = (1 - z_t) *n_t + z_t* h*{(t-1)} \ \end{array}\end{split}]where (h_t) is the hidden state at time <cite>t</cite>, (x_t) is the hidden state of the previous layer at time <cite>t</cite> or (input_t) for the first layer, and (r_t), (z_t), (n_t) are the reset, input, and new gates, respectively. | Parameters: | ***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.* **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)* **dropout** – If non-zero, introduc