# torch.nn
# torch.nn
## Parameters
### class torch.nn.Parameter()
`Variable`的一種,常被用于模塊參數(`module parameter`)。
`Parameters` 是 `Variable` 的子類。`Paramenters`和`Modules`一起使用的時候會有一些特殊的屬性,即:當`Paramenters`賦值給`Module`的屬性的時候,他會自動的被加到 `Module`的 參數列表中(即:會出現在 `parameters() 迭代器中`)。將`Varibale`賦值給`Module`屬性則不會有這樣的影響。 這樣做的原因是:我們有時候會需要緩存一些臨時的狀態(`state`), 比如:模型中`RNN`的最后一個隱狀態。如果沒有`Parameter`這個類的話,那么這些臨時變量也會注冊成為模型變量。
`Variable` 與 `Parameter`的另一個不同之處在于,`Parameter`不能被 `volatile`(即:無法設置`volatile=True`)而且默認`requires_grad=True`。`Variable`默認`requires_grad=False`。
參數說明:
- data (Tensor) – parameter tensor.
- requires\_grad (bool, optional) – 默認為`True`,在`BP`的過程中會對其求微分。
## Containers(容器):
### class torch.nn.Module
所有網絡的基類。
你的模型也應該繼承這個類。
`Modules`也可以包含其它`Modules`,允許使用樹結構嵌入他們。你可以將子模塊賦值給模型屬性。
```
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))
```
通過上面方式賦值的`submodule`會被注冊。當調用 `.cuda()` 的時候,`submodule`的參數也會轉換為`cuda Tensor`。
#### add\_module(name, module)
將一個 `child module` 添加到當前 `modle`。 被添加的`module`可以通過 `name`屬性來獲取。 例:
```
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)
```
輸出:
```
Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1))
```
#### children()
Returns an iterator over immediate children modules. 返回當前模型 子模塊的迭代器。
```
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.add_module("conv1", nn.Conv2d(20 ,10, 4))
model = Model()
for sub_module in model.children():
print(sub_module)
```
```
Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1))
Conv2d(20, 10, kernel_size=(4, 4), stride=(1, 1))
```
#### cpu(device\_id=None)
將所有的模型參數(`parameters`)和`buffers`復制到`CPU`
`NOTE`:官方文檔用的move,但我覺著`copy`更合理。
#### cuda(device\_id=None)
將所有的模型參數(`parameters`)和`buffers`賦值`GPU`
參數說明:
- device\_id (int, optional) – 如果指定的話,所有的模型參數都會復制到指定的設備上。
#### double()
將`parameters`和`buffers`的數據類型轉換成`double`。
#### eval()
將模型設置成`evaluation`模式
僅僅當模型中有`Dropout`和`BatchNorm`是才會有影響。
#### float()
將`parameters`和`buffers`的數據類型轉換成`float`。
#### forward(\* input)
定義了每次執行的 計算步驟。 在所有的子類中都需要重寫這個函數。
#### half()
將`parameters`和`buffers`的數據類型轉換成`half`。
#### load\_state\_dict(state\_dict)
將`state_dict`中的`parameters`和`buffers`復制到此`module`和它的后代中。`state_dict`中的`key`必須和 `model.state_dict()`返回的`key`一致。 `NOTE`:用來加載模型參數。
參數說明:
- state\_dict (dict) – 保存`parameters`和`persistent buffers`的字典。
#### modules()
返回一個包含 當前模型 所有模塊的迭代器。
```
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.add_module("conv1", nn.Conv2d(20 ,10, 4))
model = Model()
for module in model.modules():
print(module)
```
```
Model (
(conv): Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1))
(conv1): Conv2d(20, 10, kernel_size=(4, 4), stride=(1, 1))
)
Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1))
Conv2d(20, 10, kernel_size=(4, 4), stride=(1, 1))
```
可以看出,`modules()`返回的`iterator`不止包含 子模塊。這是和`children()`的不同。
**`NOTE:`**重復的模塊只被返回一次(`children()也是`)。 在下面的例子中, `submodule` 只會被返回一次:
```
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
submodule = nn.Conv2d(10, 20, 4)
self.add_module("conv", submodule)
self.add_module("conv1", submodule)
model = Model()
for module in model.modules():
print(module)
```
```
Model (
(conv): Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1))
(conv1): Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1))
)
Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1))
```
#### named\_children()
返回 包含 模型當前子模塊 的迭代器,`yield` 模塊名字和模塊本身。
例子:
```
for name, module in model.named_children():
if name in ['conv4', 'conv5']:
print(module)
```
#### named\_modules(memo=None, prefix='')\[source\]
返回包含網絡中所有模塊的迭代器, `yielding` 模塊名和模塊本身。
**`注意:`**
重復的模塊只被返回一次(`children()也是`)。 在下面的例子中, `submodule` 只會被返回一次。
#### parameters(memo=None)
返回一個 包含模型所有參數 的迭代器。
一般用來當作`optimizer`的參數。
例子:
```
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)
在`module`上注冊一個`bachward hook`。
每次計算`module`的`inputs`的梯度的時候,這個`hook`會被調用。`hook`應該擁有下面的`signature`。
`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`添加一個`persistent buffer`。
`persistent buffer`通常被用在這么一種情況:我們需要保存一個狀態,但是這個狀態不能看作成為模型參數。 例如:, `BatchNorm’s` running\_mean 不是一個 `parameter`, 但是它也是需要保存的狀態之一。
`Buffers`可以通過注冊時候的`name`獲取。
**`NOTE`:我們可以用 buffer 保存 `moving average`**
例子:
```
self.register_buffer('running_mean', torch.zeros(num_features))
self.running_mean
```
#### register\_forward\_hook(hook)
在`module`上注冊一個`forward hook`。 每次調用`forward()`計算輸出的時候,這個`hook`就會被調用。它應該擁有以下簽名:
`hook(module, input, output) -> None`
`hook`不應該修改 `input`和`output`的值。 這個函數返回一個 句柄(`handle`)。它有一個方法 `handle.remove()`,可以用這個方法將`hook`從`module`移除。
#### register\_parameter(name, param)
向`module`添加 `parameter`
`parameter`可以通過注冊時候的`name`獲取。
#### state\_dict(destination=None, prefix='')\[source\]
返回一個字典,保存著`module`的所有狀態(`state`)。
`parameters`和`persistent buffers`都會包含在字典中,字典的`key`就是`parameter`和`buffer`的 `names`。
例子:
```
import torch
from torch.autograd import Variable
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.conv2 = nn.Linear(1, 2)
self.vari = Variable(torch.rand([1]))
self.par = nn.Parameter(torch.rand([1]))
self.register_buffer("buffer", torch.randn([2,3]))
model = Model()
print(model.state_dict().keys())
```
```
odict_keys(['par', 'buffer', 'conv2.weight', 'conv2.bias'])
```
#### train(mode=True)
將`module`設置為 `training mode`。
僅僅當模型中有`Dropout`和`BatchNorm`是才會有影響。
#### zero\_grad()
將`module`中的所有模型參數的梯度設置為0.
### class torch.nn.Sequential(\* args)
一個時序容器。`Modules` 會以他們傳入的順序被添加到容器中。當然,也可以傳入一個`OrderedDict`。
為了更容易的理解如何使用`Sequential`, 下面給出了一個例子:
```
# 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)\[source\]
將`submodules`保存在一個`list`中。
`ModuleList`可以像一般的`Python list`一樣被`索引`。而且`ModuleList`中包含的`modules`已經被正確的注冊,對所有的`module method`可見。
參數說明:
- modules (list, optional) – 將要被添加到`MuduleList`中的 `modules` 列表
例子:
```
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)\[source\]
等價于 list 的 `append()`
參數說明:
- module (nn.Module) – 要 append 的`module`#### extend(modules)\[source\]
等價于 `list` 的 `extend()` 方法
參數說明:
- modules (list) – list of modules to append
### class torch.nn.ParameterList(parameters=None)
將`submodules`保存在一個`list`中。
`ParameterList`可以像一般的`Python list`一樣被`索引`。而且`ParameterList`中包含的`parameters`已經被正確的注冊,對所有的`module method`可見。
參數說明:
- modules (list, optional) – a list of nn.Parameter
例子:
```
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)\[source\]
等價于`python list` 的 `append` 方法。
參數說明:
- parameter (nn.Parameter) – parameter to append#### extend(parameters)\[source\]
等價于`python list` 的 `extend` 方法。
參數說明:
- parameters (list) – list of parameters to append
## 卷積層
### 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:**
```
>>> 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`)
**example:**
```
>>> # 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)
$$D*{out}=floor((D*{in}+2*padding\[0\]-dilation\[0\]*(kernerl\_size\[0\]-1)-1)/stride\[0\]+1)$$
$$H*{out}=floor((H*{in}+2*padding\[1\]-dilation\[2\]*(kernerl\_size\[1\]-1)-1)/stride\[1\]+1)$$
$$W*{out}=floor((W*{in}+2*padding\[2\]-dilation\[2\]*(kernerl\_size\[2\]-1)-1)/stride\[2\]+1)$$
**變量:**
- weight(`tensor`) - 卷積的權重,shape是(`out_channels`, `in_channels`,`kernel_size`)`
- bias(`tensor`) - 卷積的偏置系數,shape是(`out_channel`)
**example:**
```
>>> # 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)
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)
$$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)
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)
$$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**
```
>>> # 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])
```
### torch.nn.ConvTranspose3d(in\_channels, out\_channels, kernel\_size, stride=1, padding=0, output\_padding=0, groups=1, bias=True)
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,H\_in,W\_in)
輸出: (N,C\_out,H\_out,W\_out)
$$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\[0\]$$
$$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**
```
>>> # 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:**
```
>>> # 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:**
```
>>> # 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:**
```
>>> # 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:**
```
>>> 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:**
```
>>> 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:**
```
>>> # 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:**
```
>>> # 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:**
```
>>> # 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:**
```
>>> # 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:**
```
>>> # 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:**
```
>>> # 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:**
```
>>> # 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:**
```
>>> # 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:**
```
>>> # 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:**
```
>>> # 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 [\[source\]](http://pytorch.org/docs/nn.html#non-linear-activations)
> class torch.nn.ReLU(inplace=False) [\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#ReLU)
對輸入運用修正線性單元函數${ReLU}(x)= max(0, x)$,
參數: inplace-選擇是否進行覆蓋運算
shape:
- 輸入:$(N, *)$,*代表任意數目附加維度
- 輸出:$(N, \*)$,與輸入擁有同樣的shape屬性
例子:
```
>>> m = nn.ReLU()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input))
```
> class torch.nn.ReLU6(inplace=False) [\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#ReLU6)
對輸入的每一個元素運用函數${ReLU6}(x) = min(max(0,x), 6)$,
參數: inplace-選擇是否進行覆蓋運算
shape:
- 輸入:$(N, *)$,*代表任意數目附加維度
- 輸出:$(N, \*)$,與輸入擁有同樣的shape屬性
例子:
```
>>> m = nn.ReLU6()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input))
```
> class torch.nn.ELU(alpha=1.0, inplace=False) [\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#ELU)
對輸入的每一個元素運用函數$f(x) = max(0,x) + min(0, alpha \* (e^x - 1))$,
shape:
- 輸入:$(N, \*)$,星號代表任意數目附加維度
- 輸出:$(N, \*)$與輸入擁有同樣的shape屬性
例子:
```
>>> m = nn.ELU()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input))
```
> class torch.nn.PReLU(num\_parameters=1, init=0.25)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#PReLU)
對輸入的每一個元素運用函數$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屬性
例子:
```
>>> m = nn.PReLU()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input))
```
> class torch.nn.LeakyReLU(negative\_slope=0.01, inplace=False) [\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#LeakyReLU)
對輸入的每一個元素運用$f(x) = max(0, x) + {negative\_slope} \* min(0, x)$
參數:
- negative\_slope:控制負斜率的角度,默認等于0.01
- inplace-選擇是否進行覆蓋運算
shape:
- 輸入:$(N, *)$,*代表任意數目附加維度
- 輸出:$(N, \*)$,與輸入擁有同樣的shape屬性
例子:
```
>>> m = nn.LeakyReLU(0.1)
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input))
```
> class torch.nn.Threshold(threshold, value, inplace=False) [\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Threshold)
Threshold定義:
$$ y = x ,if\\ x >= threshold\\ y = value,if\\ x < threshold
$$
參數:
- threshold:閾值
- value:輸入值小于閾值則會被value代替
- inplace:選擇是否進行覆蓋運算
shape:
- 輸入:$(N, *)$,*代表任意數目附加維度
- 輸出:$(N, \*)$,與輸入擁有同樣的shape屬性
例子:
```
>>> 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) [\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Hardtanh)
對每個元素,
$$ 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屬性
例子:
```
>>> m = nn.Hardtanh()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input))
```
> class torch.nn.Sigmoid [\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Sigmoid)
對每個元素運用Sigmoid函數,Sigmoid 定義如下:
$$f(x) = 1 / ( 1 + e^{-x})$$
shape:
- 輸入:(N, \*),\*表示任意維度組合
- 輸出:(N, \*),與輸入有相同的shape屬性
例子:
```
>>> m = nn.Sigmoid()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input))
```
> class torch.nn.Tanh [\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Tanh)
對輸入的每個元素,
$$f(x) = \\frac{e^{x} - e^{-x}} {e^{x} + e^{x}}$$
shape:
- 輸入:(N, \*),\*表示任意維度組合
- 輸出:(N, \*),與輸入有相同的shape屬性
例子:
```
>>> m = nn.Tanh()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input))
```
> class torch.nn.LogSigmoid [\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#LogSigmoid)
對輸入的每個元素,$LogSigmoid(x) = log( 1 / ( 1 + e^{-x}))$
shape:
- 輸入:(N, \*),\*表示任意維度組合
- 輸出:(N, \*),與輸入有相同的shape屬性
例子:
```
>>> m = nn.LogSigmoid()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input))
```
> class torch.nn.Softplus(beta=1, threshold=20)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Softplus)
對每個元素運用Softplus函數,Softplus 定義如下:
$$f(x) = \\frac{1}{beta} *log(1 + e^{(beta* x\_i)})$$
Softplus函數是ReLU函數的平滑逼近,Softplus函數可以使得輸出值限定為正數。
為了保證數值穩定性,線性函數的轉換可以使輸出大于某個值。
參數:
- beta:Softplus函數的beta值
- threshold:閾值
shape:
- 輸入:(N, \*),\*表示任意維度組合
- 輸出:(N, \*),與輸入有相同的shape屬性
例子:
```
>>> m = nn.Softplus()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input))
```
> class torch.nn.Softshrink(lambd=0.5)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Softshrink)
對每個元素運用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屬性
例子:
```
>>> m = nn.Softshrink()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input))
```
> class torch.nn.Softsign [\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Softsign)
$f(x) = x / (1 + |x|)$
shape:
- 輸入:(N, \*),\*表示任意維度組合
- 輸出:(N, \*),與輸入有相同的shape屬性
例子:
```
>>> m = nn.Softsign()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input))
```
> class torch.nn.Softshrink(lambd=0.5)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Softshrink)
對每個元素運用Tanhshrink函數,Tanhshrink函數定義如下:
$$ Tanhshrink(x) = x - Tanh(x)
$$
shape:
- 輸入:(N, \*),\*表示任意維度組合
- 輸出:(N, \*),與輸入有相同的shape屬性
例子:
```
>>> m = nn.Tanhshrink()
>>> input = autograd.Variable(torch.randn(2))
>>> print(input)
>>> print(m(input))
```
> class torch.nn.Softmin [\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#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)
例子:
```
>>> m = nn.Softmin()
>>> input = autograd.Variable(torch.randn(2, 3))
>>> print(input)
>>> print(m(input))
```
- - - - - -
> class torch.nn.Softmax [\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#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)區間。
例子:
```
>>> m = nn.Softmax()
>>> input = autograd.Variable(torch.randn(2, 3))
>>> print(input)
>>> print(m(input))
```
> class torch.nn.LogSoftmax [\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#LogSoftmax)
對n維輸入張量運用LogSoftmax函數,LogSoftmax函數定義如下:
$$f\_i(x) = log \\frac{e^{(x\_i)}} {a}, a = \\sum^j e^{(x\_j)}$$
shape:
- 輸入:(N, L)
- 輸出:(N, L)
例子:
```
>>> m = nn.LogSoftmax()
>>> input = autograd.Variable(torch.randn(2, 3))
>>> print(input)
>>> print(m(input))
```
## Normalization layers [\[source\]](http://pytorch.org/docs/nn.html#normalization-layers)
### class torch.nn.BatchNorm1d(num\_features, eps=1e-05, momentum=0.1, affine=True) [\[source\]](http://pytorch.org/docs/nn.html#torch.nn.BatchNorm1d)
對小批量(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)(輸入輸出相同)
**例子**
```
>>> # 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)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/batchnorm.html#BatchNorm2d)
對小批量(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)(輸入輸出相同)
**例子**
```
>>> # 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)[\[source\]](http://pytorch.org/docs/nn.html#torch.nn.BatchNorm3d)
對小批量(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)(輸入輸出相同)
**例子**
```
>>> # 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)
```
- - - - - -
## Recurrent layers
### class torch.nn.RNN( *args, \** kwargs)\[source\]
將一個多層的 `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)`
示例:
```
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)\[source\]
將一個多層的 `(LSTM)` 應用到輸入序列。
對輸入序列的每個元素,`LSTM`的每層都會執行以下計算:
$$ \\begin{aligned} i*t &= sigmoid(W*{ii}x*t+b*{ii}+W*{hi}h*{t-1}+b*{hi}) \\ f\_t &= sigmoid(W*{if}x*t+b*{if}+W*{hf}h*{t-1}+b*{hf}) \\ o\_t &= sigmoid(W*{io}x*t+b*{io}+W*{ho}h*{t-1}+b*{ho})\\ g\_t &= tanh(W*{ig}x*t+b*{ig}+W*{hg}h*{t-1}+b*{hg})\\ c\_t &= f\_t\*c*{t-1}+i\_t*g\_t\\ h\_t &= o\_t*tanh(c\_t) \\end{aligned}
$$ $h\_t$是時刻$t$的隱狀態,$c\_t$是時刻$t$的細胞狀態,$x\_t$是上一層的在時刻$t$的隱狀態或者是第一層在時刻$t$的輸入。$i\_t, f\_t, g\_t, o\_t$ 分別代表 輸入門,遺忘門,細胞和輸出門。
參數說明:
- input\_size – 輸入的特征維度
- hidden\_size – 隱狀態的特征維度
- num\_layers – 層數(和時序展開要區分開)
- bias – 如果為`False`,那么`LSTM`將不會使用$b*{ih},b*{hh}$,默認為`True`。
- batch\_first – 如果為`True`,那么輸入和輸出`Tensor`的形狀為`(batch, seq, feature)`
- dropout – 如果非零的話,將會在`RNN`的輸出上加個`dropout`,最后一層除外。
- bidirectional – 如果為`True`,將會變成一個雙向`RNN`,默認為`False`。
`LSTM`輸入: input, (h\_0, c\_0)
- input (seq\_len, batch, input\_size): 包含輸入序列特征的`Tensor`。也可以是`packed variable` ,詳見 [pack\_padded\_sequence](#torch.nn.utils.rnn.pack_padded_sequence(input,%20lengths,%20batch_first=False%5Bsource%5D)
- h\_0 (num\_layers \* num\_directions, batch, hidden\_size):保存著`batch`中每個元素的初始化隱狀態的`Tensor`
- c\_0 (num\_layers \* num\_directions, batch, hidden\_size): 保存著`batch`中每個元素的初始化細胞狀態的`Tensor`
`LSTM`輸出 output, (h\_n, c\_n)
- output (seq\_len, batch, hidden\_size \* num\_directions): 保存`RNN`最后一層的輸出的`Tensor`。 如果輸入是`torch.nn.utils.rnn.PackedSequence`,那么輸出也是`torch.nn.utils.rnn.PackedSequence`。
- h\_n (num\_layers \* num\_directions, batch, hidden\_size): `Tensor`,保存著`RNN`最后一個時間步的隱狀態。
- c\_n (num\_layers \* num\_directions, batch, hidden\_size): `Tensor`,保存著`RNN`最后一個時間步的細胞狀態。
`LSTM`模型參數:
- weight*ih\_l\[k\] – 第`k`層可學習的`input-hidden`權重($W*{ii}|W*{if}|W*{ig}|W\_{io}$),形狀為`(input_size x 4*hidden_size)`
- weight*hh\_l\[k\] – 第`k`層可學習的`hidden-hidden`權重($W*{hi}|W*{hf}|W*{hg}|W\_{ho}$),形狀為`(hidden_size x 4*hidden_size)`。
- bias*ih\_l\[k\] – 第`k`層可學習的`input-hidden`偏置($b*{ii}|b*{if}|b*{ig}|b\_{io}$),形狀為`( 4*hidden_size)`
- bias*hh\_l\[k\] – 第`k`層可學習的`hidden-hidden`偏置($b*{hi}|b*{hf}|b*{hg}|b\_{ho}$),形狀為`( 4*hidden_size)`。 示例:
```
lstm = nn.LSTM(10, 20, 2)
input = Variable(torch.randn(5, 3, 10))
h0 = Variable(torch.randn(2, 3, 20))
c0 = Variable(torch.randn(2, 3, 20))
output, hn = lstm(input, (h0, c0))
```
### class torch.nn.GRU( *args, \** kwargs)\[source\]
將一個多層的`GRU`用于輸入序列。
對輸入序列中的每個元素,每層進行了一下計算:
$$ \\begin{aligned} r*t&=sigmoid(W*{ir}x*t+b*{ir}+W*{hr}h*{(t-1)}+b*{hr})\\ i\_t&=sigmoid(W*{ii}x*t+b*{ii}+W*{hi}h*{(t-1)}+b*{hi})\\ n\_t&=tanh(W*{in}x*t+b*{in}+rt*(W*{hn}h*{(t-1)}+b\_{hn}))\\ h\_t&=(1-i\_t)* nt+i\_t\*h(t-1) \\end{aligned}
$$ $h\_t$是是時間$t$的上的隱狀態,$x\_t$是前一層$t$時刻的隱狀態或者是第一層的$t$時刻的輸入,$r\_t, i\_t, n\_t$分別是重置門,輸入門和新門。
參數說明:
- input\_size – 期望的輸入$x$的特征值的維度
- hidden\_size – 隱狀態的維度
- num\_layers – `RNN`的層數。
- bias – 如果為`False`,那么`RNN`層將不會使用`bias`,默認為`True`。
- batch\_first – 如果為`True`的話,那么輸入和輸出的`tensor`的形狀是`(batch, seq, feature)`。
- dropout – 如果非零的話,將會在`RNN`的輸出上加個`dropout`,最后一層除外。
- bidirectional – 如果為`True`,將會變成一個雙向`RNN`,默認為`False`。
輸入: input, h\_0
- input (seq\_len, batch, input\_size): 包含輸入序列特征的`Tensor`。也可以是`packed variable` ,詳見 [pack\_padded\_sequence](#torch.nn.utils.rnn.pack_padded_sequence(input,%20lengths,%20batch_first=False%5Bsource%5D)。
- h\_0 (num\_layers \* num\_directions, batch, hidden\_size):保存著`batch`中每個元素的初始化隱狀態的`Tensor`
輸出: output, h\_n
- output (seq\_len, batch, hidden\_size \* num\_directions): ten保存`RNN`最后一層的輸出的`Tensor`。 如果輸入是`torch.nn.utils.rnn.PackedSequence`,那么輸出也是`torch.nn.utils.rnn.PackedSequence`。
- h\_n (num\_layers \* num\_directions, batch, hidden\_size): `Tensor`,保存著`RNN`最后一個時間步的隱狀態。
變量:
- weight*ih\_l\[k\] – 第`k`層可學習的`input-hidden`權重($W*{ir}|W*{ii}|W*{in}$),形狀為`(input_size x 3*hidden_size)`
- weight*hh\_l\[k\] – 第`k`層可學習的`hidden-hidden`權重($W*{hr}|W*{hi}|W*{hn}$),形狀為`(hidden_size x 3*hidden_size)`。
- bias*ih\_l\[k\] – 第`k`層可學習的`input-hidden`偏置($b*{ir}|b*{ii}|b*{in}$),形狀為`( 3*hidden_size)`
- bias*hh\_l\[k\] – 第`k`層可學習的`hidden-hidden`偏置($b*{hr}|b*{hi}|b*{hn}$),形狀為`( 3*hidden_size)`。
例子:
```
rnn = nn.GRU(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.RNNCell(input\_size, hidden\_size, bias=True, nonlinearity='tanh')\[source\]
一個 `Elan RNN cell`,激活函數是`tanh`或`ReLU`,用于輸入序列。 將一個多層的 `Elman RNNCell`,激活函數為`tanh`或者`ReLU`,用于輸入序列。
$$ h'=tanh(w*{ih}\* x+b*{ih}+w*{hh}\* h+b*{hh})
$$ 如果`nonlinearity=relu`,那么將會使用`ReLU`來代替`tanh`。
參數:
- input\_size – 輸入$x$,特征的維度。
- hidden\_size – 隱狀態特征的維度。
- bias – 如果為`False`,`RNN cell`中將不會加入`bias`,默認為`True`。
- nonlinearity – 用于選擇非線性激活函數 \[`tanh`|`relu`\]. 默認值為: `tanh`
輸入: input, hidden
- input (batch, input\_size): 包含輸入特征的`tensor`。
- hidden (batch, hidden\_size): 保存著初始隱狀態值的`tensor`。
輸出: h’
- h’ (batch, hidden\_size):下一個時刻的隱狀態。
變量:
- weight\_ih – `input-hidden` 權重, 可學習,形狀是`(input_size x hidden_size)`。
- weight\_hh – `hidden-hidden` 權重, 可學習,形狀是`(hidden_size x hidden_size)`
- bias\_ih – `input-hidden` 偏置, 可學習,形狀是`(hidden_size)`
- bias\_hh – `hidden-hidden` 偏置, 可學習,形狀是`(hidden_size)`
例子:
```
rnn = nn.RNNCell(10, 20)
input = Variable(torch.randn(6, 3, 10))
hx = Variable(torch.randn(3, 20))
output = []
for i in range(6):
hx = rnn(input[i], hx)
output.append(hx)
```
### class torch.nn.LSTMCell(input\_size, hidden\_size, bias=True)\[source\]
`LSTM cell`。
$$ \\begin{aligned} i &= sigmoid(W*{ii}x+b*{ii}+W*{hi}h+b*{hi}) \\ f &= sigmoid(W*{if}x+b*{if}+W*{hf}h+b*{hf}) \\ o &= sigmoid(W*{io}x+b*{io}+W*{ho}h+b*{ho})\\ g &= tanh(W*{ig}x+b*{ig}+W*{hg}h+b*{hg})\\ c' &= f*t\*c*{t-1}+i\_t*g\_t\\ h' &= o\_t*tanh(c') \\end{aligned}
$$
參數:
- input\_size – 輸入的特征維度。
- hidden\_size – 隱狀態的維度。
- bias – 如果為`False`,那么將不會使用`bias`。默認為`True`。
`LSTM`輸入: input, (h\_0, c\_0)
- input (seq\_len, batch, input\_size): 包含輸入序列特征的`Tensor`。也可以是`packed variable` ,詳見 [pack\_padded\_sequence](#torch.nn.utils.rnn.pack_padded_sequence(input,%20lengths,%20batch_first=False%5Bsource%5D)
- h\_0 ( batch, hidden\_size):保存著`batch`中每個元素的初始化隱狀態的`Tensor`
- c\_0 (batch, hidden\_size): 保存著`batch`中每個元素的初始化細胞狀態的`Tensor`
輸出: h\_1, c\_1
- h\_1 (batch, hidden\_size): 下一個時刻的隱狀態。
- c\_1 (batch, hidden\_size): 下一個時刻的細胞狀態。
`LSTM`模型參數:
- weight*ih – `input-hidden`權重($W*{ii}|W*{if}|W*{ig}|W\_{io}$),形狀為`(input_size x 4*hidden_size)`
- weight*hh – `hidden-hidden`權重($W*{hi}|W*{hf}|W*{hg}|W\_{ho}$),形狀為`(hidden_size x 4*hidden_size)`。
- bias*ih – `input-hidden`偏置($b*{ii}|b*{if}|b*{ig}|b\_{io}$),形狀為`( 4*hidden_size)`
- bias*hh – `hidden-hidden`偏置($b*{hi}|b*{hf}|b*{hg}|b\_{ho}$),形狀為`( 4*hidden_size)`。
Examples:
```
rnn = nn.LSTMCell(10, 20)
input = Variable(torch.randn(6, 3, 10))
hx = Variable(torch.randn(3, 20))
cx = Variable(torch.randn(3, 20))
output = []
for i in range(6):
hx, cx = rnn(input[i], (hx, cx))
output.append(hx)
```
### class torch.nn.GRUCell(input\_size, hidden\_size, bias=True)\[source\]
一個`GRU cell`。
$$ \\begin{aligned} r&=sigmoid(W*{ir}x+b*{ir}+W*{hr}h+b*{hr})\\ i&=sigmoid(W*{ii}x+b*{ii}+W*{hi}h+b*{hi})\\ n&=tanh(W*{in}x+b*{in}+r*(W*{hn}h+b*{hn}))\\ h'&=(1-i)* n+i\*h \\end{aligned}
$$
參數說明:
- input\_size – 期望的輸入$x$的特征值的維度
- hidden\_size – 隱狀態的維度
- bias – 如果為`False`,那么`RNN`層將不會使用`bias`,默認為`True`。
輸入: input, h\_0
- input (batch, input\_size): 包含輸入特征的`Tensor`
- h\_0 (batch, hidden\_size):保存著`batch`中每個元素的初始化隱狀態的`Tensor`
輸出: h\_1
- h\_1 (batch, hidden\_size): `Tensor`,保存著`RNN`下一個時刻的隱狀態。
變量:
- weight*ih – `input-hidden`權重($W*{ir}|W*{ii}|W*{in}$),形狀為`(input_size x 3*hidden_size)`
- weight*hh – `hidden-hidden`權重($W*{hr}|W*{hi}|W*{hn}$),形狀為`(hidden_size x 3*hidden_size)`。
- bias*ih – `input-hidden`偏置($b*{ir}|b*{ii}|b*{in}$),形狀為`( 3*hidden_size)`
- bias*hh – `hidden-hidden`偏置($b*{hr}|b*{hi}|b*{hn}$),形狀為`( 3*hidden_size)`。
例子:
```
rnn = nn.GRUCell(10, 20)
input = Variable(torch.randn(6, 3, 10))
hx = Variable(torch.randn(3, 20))
output = []
for i in range(6):
hx = rnn(input[i], hx)
output.append(hx)
```
## Linear layers
```
class torch.nn.Linear(in_features, out_features, bias=True)
```
對輸入數據做線性變換:\\(y = Ax + b\\)
**參數:**
- **in\_features** - 每個輸入樣本的大小
- **out\_features** - 每個輸出樣本的大小
- **bias** - 若設置為False,這層不會學習偏置。默認值:True
**形狀:**
- **輸入:** \\((N, in\\\_features)\\)
- **輸出:** \\((N, out\\\_features)\\)
**變量:**
- **weight** -形狀為(out\_features x in\_features)的模塊中可學習的權值
- **bias** -形狀為(out\_features)的模塊中可學習的偏置
**例子:**
```
>>> m = nn.Linear(20, 30)
>>> input = autograd.Variable(torch.randn(128, 20))
>>> output = m(input)
>>> print(output.size())
```
## Dropout layers
```
class torch.nn.Dropout(p=0.5, inplace=False)
```
隨機將輸入張量中部分元素設置為0。對于每次前向調用,被置0的元素都是隨機的。
**參數:**
- **p** - 將元素置0的概率。默認值:0.5
- **in-place** - 若設置為True,會在原地執行操作。默認值:False
**形狀:**
- **輸入:** 任意。輸入可以為任意形狀。
- **輸出:** 相同。輸出和輸入形狀相同。
**例子:**
```
>>> m = nn.Dropout(p=0.2)
>>> input = autograd.Variable(torch.randn(20, 16))
>>> output = m(input)
```
```
class torch.nn.Dropout2d(p=0.5, inplace=False)
```
隨機將輸入張量中整個通道設置為0。對于每次前向調用,被置0的通道都是隨機的。
*通常輸入來自Conv2d模塊。*
像在論文[Efficient Object Localization Using Convolutional Networks](https://arxiv.org/abs/1411.4280),如果特征圖中相鄰像素是強相關的(在前幾層卷積層很常見),那么iid dropout不會歸一化激活,而只會降低學習率。
在這種情形,`nn.Dropout2d()`可以提高特征圖之間的獨立程度,所以應該使用它。
**參數:**
- **p**(*<a class="pcalibre1 pcalibre pcalibre3 pcalibre2" href="">float</a>, optional*) - 將元素置0的概率。
- **in-place**(*<a class="pcalibre1 pcalibre pcalibre3 pcalibre2" href="">bool,</a> optional*) - 若設置為True,會在原地執行操作。
**形狀:**
- **輸入:** \\((N, C, H, W)\\)
- **輸出:** \\((N, C, H, W)\\)(與輸入形狀相同)
**例子:**
```
>>> m = nn.Dropout2d(p=0.2)
>>> input = autograd.Variable(torch.randn(20, 16, 32, 32))
>>> output = m(input)
```
```
class torch.nn.Dropout3d(p=0.5, inplace=False)
```
隨機將輸入張量中整個通道設置為0。對于每次前向調用,被置0的通道都是隨機的。
*通常輸入來自Conv3d模塊。*
像在論文[Efficient Object Localization Using Convolutional Networks](https://arxiv.org/abs/1411.4280),如果特征圖中相鄰像素是強相關的(在前幾層卷積層很常見),那么iid dropout不會歸一化激活,而只會降低學習率。
在這種情形,`nn.Dropout3d()`可以提高特征圖之間的獨立程度,所以應該使用它。
**參數:**
- **p**(*<a class="pcalibre1 pcalibre pcalibre3 pcalibre2" href="">float</a>, optional*) - 將元素置0的概率。
- **in-place**(*<a class="pcalibre1 pcalibre pcalibre3 pcalibre2" href="">bool,</a> optional*) - 若設置為True,會在原地執行操作。
**形狀:**
- **輸入:** \\(N, C, D, H, W)\\)
- **輸出:** \\((N, C, D, H, W)\\)(與輸入形狀相同)
**例子:**
```
>>> m = nn.Dropout3d(p=0.2)
>>> input = autograd.Variable(torch.randn(20, 16, 4, 32, 32))
>>> output = m(input)
```
## Sparse layers
```
class torch.nn.Embedding(num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=2, scale_grad_by_freq=False, sparse=False)
```
一個保存了固定字典和大小的簡單查找表。
這個模塊常用來保存詞嵌入和用下標檢索它們。模塊的輸入是一個下標的列表,輸出是對應的詞嵌入。
**參數:**
- **num\_embeddings** (*<a class="pcalibre1 pcalibre pcalibre3 pcalibre2" href="">int</a>*) - 嵌入字典的大小
- **embedding\_dim** (*<a class="pcalibre1 pcalibre pcalibre3 pcalibre2" href="">int</a>*) - 每個嵌入向量的大小
- **padding\_idx** (*<a class="pcalibre1 pcalibre pcalibre3 pcalibre2" href="">int</a>, optional*) - 如果提供的話,輸出遇到此下標時用零填充
- **max\_norm** (*<a class="pcalibre1 pcalibre pcalibre3 pcalibre2" href="">float</a>, optional*) - 如果提供的話,會重新歸一化詞嵌入,使它們的范數小于提供的值
- **norm\_type** (*<a class="pcalibre1 pcalibre pcalibre3 pcalibre2" href="">float</a>, optional*) - 對于max\_norm選項計算p范數時的p
- **scale\_grad\_by\_freq** (*boolean, optional*) - 如果提供的話,會根據字典中單詞頻率縮放梯度
**變量:**
- **weight (*[Tensor](http://pytorch.org/docs/tensors.html#torch.Tensor)*)** -形狀為(num\_embeddings, embedding\_dim)的模塊中可學習的權值
**形狀:**
- **輸入:** LongTensor *(N, W)*, N = mini-batch, W = 每個mini-batch中提取的下標數
- **輸出:** *(N, W, embedding\_dim)*
**例子:**
```
>>> # an Embedding module containing 10 tensors of size 3
>>> embedding = nn.Embedding(10, 3)
>>> # a batch of 2 samples of 4 indices each
>>> input = Variable(torch.LongTensor([[1,2,4,5],[4,3,2,9]]))
>>> embedding(input)
Variable containing:
(0 ,.,.) =
-1.0822 1.2522 0.2434
0.8393 -0.6062 -0.3348
0.6597 0.0350 0.0837
0.5521 0.9447 0.0498
(1 ,.,.) =
0.6597 0.0350 0.0837
-0.1527 0.0877 0.4260
0.8393 -0.6062 -0.3348
-0.8738 -0.9054 0.4281
[torch.FloatTensor of size 2x4x3]
>>> # example with padding_idx
>>> embedding = nn.Embedding(10, 3, padding_idx=0)
>>> input = Variable(torch.LongTensor([[0,2,0,5]]))
>>> embedding(input)
Variable containing:
(0 ,.,.) =
0.0000 0.0000 0.0000
0.3452 0.4937 -0.9361
0.0000 0.0000 0.0000
0.0706 -2.1962 -0.6276
[torch.FloatTensor of size 1x4x3]
```
## Distance functions
```
class torch.nn.PairwiseDistance(p=2, eps=1e-06)
```
按批計算向量v1, v2之間的距離:
$$\\Vert x \\Vert *p := \\left( \\sum\\*{i=1}^n \\vert x\_i \\vert ^ p \\right) ^ {1/p}$$
**參數:**
- **x** (*Tensor*): 包含兩個輸入batch的張量
- **p** (real): 范數次數,默認值:2
**形狀:**
- **輸入:** \\((N, D)\\),其中D=向量維數
- **輸出:** \\((N, 1)\\)
```
>>> pdist = nn.PairwiseDistance(2)
>>> input1 = autograd.Variable(torch.randn(100, 128))
>>> input2 = autograd.Variable(torch.randn(100, 128))
>>> output = pdist(input1, input2)
```
## Loss functions
基本用法:
```
criterion = LossCriterion() #構造函數有自己的參數
loss = criterion(x, y) #調用標準時也有參數
```
計算出來的結果已經對`mini-batch`取了平均。
### class torch.nn.L1Loss(size\_average=True)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#L1Loss)
創建一個衡量輸入`x`(`模型預測輸出`)和目標`y`之間差的絕對值的平均值的標準。
$$ loss(x,y)=1/n\\sum|x\_i-y\_i|
$$
- `x` 和 `y` 可以是任意形狀,每個包含`n`個元素。
- 對`n`個元素對應的差值的絕對值求和,得出來的結果除以`n`。
- 如果在創建`L1Loss`實例的時候在構造函數中傳入`size_average=False`,那么求出來的絕對值的和將不會除以`n`
### class torch.nn.MSELoss(size\_average=True)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#MSELoss)
創建一個衡量輸入`x`(`模型預測輸出`)和目標`y`之間均方誤差標準。
$$ loss(x,y)=1/n\\sum(x\_i-y\_i)^2
$$
- `x` 和 `y` 可以是任意形狀,每個包含`n`個元素。
- 對`n`個元素對應的差值的絕對值求和,得出來的結果除以`n`。
- 如果在創建`MSELoss`實例的時候在構造函數中傳入`size_average=False`,那么求出來的平方和將不會除以`n`
### class torch.nn.CrossEntropyLoss(weight=None, size\_average=True)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#CrossEntropyLoss)
此標準將`LogSoftMax`和`NLLLoss`集成到一個類中。
當訓練一個多類分類器的時候,這個方法是十分有用的。
- weight(tensor): `1-D` tensor,`n`個元素,分別代表`n`類的權重,如果你的訓練樣本很不均衡的話,是非常有用的。默認值為None。
調用時參數:
- input : 包含每個類的得分,`2-D` tensor,`shape`為 `batch*n`
- target: 大小為 `n` 的 `1—D``tensor`,包含類別的索引(`0到 n-1`)。
Loss可以表述為以下形式:
$$ \\begin{aligned} loss(x, class) &= -\\text{log}\\frac{exp(x\[class\])}{\\sum\_j exp(x\[j\]))}\\ &= -x\[class\] + log(\\sum\_j exp(x\[j\])) \\end{aligned}
$$ 當`weight`參數被指定的時候,`loss`的計算公式變為:
$$ loss(x, class) = weights\[class\] \* (-x\[class\] + log(\\sum\_j exp(x\[j\])))
$$ 計算出的`loss`對`mini-batch`的大小取了平均。
形狀(`shape`):
- Input: (N,C) `C` 是類別的數量
- Target: (N) `N`是`mini-batch`的大小,0 <= targets\[i\] <= C-1
### class torch.nn.NLLLoss(weight=None, size\_average=True)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#NLLLoss)
負的`log likelihood loss`損失。用于訓練一個`n`類分類器。
如果提供的話,`weight`參數應該是一個`1-D`tensor,里面的值對應類別的權重。當你的訓練集樣本不均衡的話,使用這個參數是非常有用的。
輸入是一個包含類別`log-probabilities`的`2-D` tensor,形狀是`(mini-batch, n)`
可以通過在最后一層加`LogSoftmax`來獲得類別的`log-probabilities`。
如果您不想增加一個額外層的話,您可以使用`CrossEntropyLoss`。
此`loss`期望的`target`是類別的索引 (0 to N-1, where N = number of classes)
此`loss`可以被表示如下:
$$ loss(x, class) = -x\[class\]
$$ 如果`weights`參數被指定的話,`loss`可以表示如下:
$$ loss(x, class) = -weights\[class\] \* x\[class\]
$$ 參數說明:
- weight (Tensor, optional) – 手動指定每個類別的權重。如果給定的話,必須是長度為`nclasses`
- size\_average (bool, optional) – 默認情況下,會計算`mini-batch``loss`的平均值。然而,如果`size_average=False`那么將會把`mini-batch`中所有樣本的`loss`累加起來。
形狀:
- Input: (N,C) , `C`是類別的個數
- Target: (N) , `target`中每個值的大小滿足 `0 <= targets[i] <= C-1`
例子:
```
m = nn.LogSoftmax()
loss = nn.NLLLoss()
# input is of size nBatch x nClasses = 3 x 5
input = autograd.Variable(torch.randn(3, 5), requires_grad=True)
# each element in target has to have 0 <= value < nclasses
target = autograd.Variable(torch.LongTensor([1, 0, 4]))
output = loss(m(input), target)
output.backward()
```
### class torch.nn.NLLLoss2d(weight=None, size\_average=True)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#NLLLoss2d)
對于圖片的 `negative log likehood loss`。計算每個像素的 `NLL loss`。
參數說明:
- weight (Tensor, optional) – 用來作為每類的權重,如果提供的話,必須為`1-D`tensor,大小為`C`:類別的個數。
- size\_average – 默認情況下,會計算 `mini-batch` loss均值。如果設置為 `False` 的話,將會累加`mini-batch`中所有樣本的`loss`值。默認值:`True`。
形狀:
- Input: (N,C,H,W) `C` 類的數量
- Target: (N,H,W) where each value is 0 <= targets\[i\] <= C-1
例子:
```
m = nn.Conv2d(16, 32, (3, 3)).float()
loss = nn.NLLLoss2d()
# input is of size nBatch x nClasses x height x width
input = autograd.Variable(torch.randn(3, 16, 10, 10))
# each element in target has to have 0 <= value < nclasses
target = autograd.Variable(torch.LongTensor(3, 8, 8).random_(0, 4))
output = loss(m(input), target)
output.backward()
```
### class torch.nn.KLDivLoss(weight=None, size\_average=True)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#KLDivLoss)
計算 KL 散度損失。
KL散度常用來描述兩個分布的距離,并在輸出分布的空間上執行直接回歸是有用的。
與`NLLLoss`一樣,給定的輸入應該是`log-probabilities`。然而。和`NLLLoss`不同的是,`input`不限于`2-D` tensor,因為此標準是基于`element`的。
`target` 應該和 `input`的形狀相同。
此loss可以表示為:
$$ loss(x,target)=\\frac{1}{n}\\sum\_i(target\_i\*(log(target\_i)-x\_i))
$$ 默認情況下,loss會基于`element`求平均。如果 `size_average=False``loss` 會被累加起來。
### class torch.nn.BCELoss(weight=None, size\_average=True)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#BCELoss)
計算 `target` 與 `output` 之間的二進制交叉熵。
$$ loss(o,t)=-\\frac{1}{n}\\sum\_i(t\[i\] *log(o\[i\])+(1-t\[i\])* log(1-o\[i\]))
$$ 如果`weight`被指定 :
$$ loss(o,t)=-\\frac{1}{n}\\sum\_iweights\[i\] *(t\[i\]* log(o\[i\])+(1-t\[i\])\* log(1-o\[i\]))
$$
這個用于計算 `auto-encoder` 的 `reconstruction error`。注意 0<=target\[i\]<=1。
默認情況下,loss會基于`element`平均,如果`size_average=False`的話,`loss`會被累加。
### class torch.nn.MarginRankingLoss(margin=0, size\_average=True)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#MarginRankingLoss)
創建一個標準,給定輸入 $x1$,$x2$兩個1-D mini-batch Tensor's,和一個$y$(1-D mini-batch tensor) ,$y$里面的值只能是-1或1。
如果 `y=1`,代表第一個輸入的值應該大于第二個輸入的值,如果`y=-1`的話,則相反。
`mini-batch`中每個樣本的loss的計算公式如下:
$$loss(x, y) = max(0, -y \* (x1 - x2) + margin)$$
如果`size_average=True`,那么求出的`loss`將會對`mini-batch`求平均,反之,求出的`loss`會累加。默認情況下,`size_average=True`。
### class torch.nn.HingeEmbeddingLoss(size\_average=True)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#HingeEmbeddingLoss)
給定一個輸入 $x$(2-D mini-batch tensor)和對應的 標簽 $y$ (1-D tensor,1,-1),此函數用來計算之間的損失值。這個`loss`通常用來測量兩個輸入是否相似,即:使用L1 成對距離。典型是用在學習非線性 `embedding`或者半監督學習中:
$$ loss(x,y)=\\frac{1}{n}\\sum\_i \\begin{cases} x\_i, &\\text if~y\_i==1 \\ max(0, margin-x\_i), &if ~y\_i==-1 \\end{cases}
$$ $x$和$y$可以是任意形狀,且都有`n`的元素,`loss`的求和操作作用在所有的元素上,然后除以`n`。如果您不想除以`n`的話,可以通過設置`size_average=False`。
`margin`的默認值為1,可以通過構造函數來設置。
### class torch.nn.MultiLabelMarginLoss(size\_average=True)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#MultiLabelMarginLoss)
計算多標簽分類的 `hinge loss`(`margin-based loss`) ,計算`loss`時需要兩個輸入: input x(`2-D mini-batch Tensor`),和 output y(`2-D tensor`表示mini-batch中樣本類別的索引)。
$$ loss(x, y) = \\frac{1}{x.size(0)}\\sum\_{i=0,j=0}^{I,J}(max(0, 1 - (x\[y\[j\]\] - x\[i\])))
$$ 其中 `I=x.size(0),J=y.size(0)`。對于所有的 `i`和 `j`,滿足 $y\[j\]\\neq0, i \\neq y\[j\]$
`x` 和 `y` 必須具有同樣的 `size`。
這個標準僅考慮了第一個非零 `y[j] targets`此標準允許了,對于每個樣本來說,可以有多個類別。
### class torch.nn.SmoothL1Loss(size\_average=True)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#SmoothL1Loss)
平滑版`L1 loss`。
loss的公式如下:
$$ loss(x, y) = \\frac{1}{n}\\sum\_i \\begin{cases} 0.5\*(x\_i-y\_i)^2, & if~|x\_i - y\_i| < 1\\ |x\_i - y\_i| - 0.5, & otherwise
\\end{cases}
$$ 此loss對于異常點的敏感性不如`MSELoss`,而且,在某些情況下防止了梯度爆炸,(參照 `Fast R-CNN`)。這個`loss`有時也被稱為 `Huber loss`。
x 和 y 可以是任何包含`n`個元素的tensor。默認情況下,求出來的`loss`會除以`n`,可以通過設置`size_average=True`使loss累加。
### class torch.nn.SoftMarginLoss(size\_average=True)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#SoftMarginLoss)
創建一個標準,用來優化2分類的`logistic loss`。輸入為 `x`(一個 2-D mini-batch Tensor)和 目標`y`(一個包含1或-1的Tensor)。
$$ loss(x, y) = \\frac{1}{x.nelement()}\\sum\_i (log(1 + exp(-y\[i\]\* x\[i\])))
$$ 如果求出的`loss`不想被平均可以通過設置`size_average=False`。
### class torch.nn.MultiLabelSoftMarginLoss(weight=None, size\_average=True)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#MultiLabelSoftMarginLoss)
創建一個標準,基于輸入x和目標y的 `max-entropy`,優化多標簽 `one-versus-all` 的損失。`x`:2-D mini-batch Tensor;`y`:binary 2D Tensor。對每個mini-batch中的樣本,對應的loss為:
$$ loss(x, y) = - \\frac{1}{x.nElement()}\\sum\_{i=0}^I y\[i\]\\text{log}\\frac{exp(x\[i\])}{(1 + exp(x\[i\])}
```
+ (1-y[i])\text{log}\frac{1}{1+exp(x[i])}
```
$$ 其中 `I=x.nElement()-1`, $y\[i\] \\in {0,1}$,`y` 和 `x`必須要有同樣`size`。
### class torch.nn.CosineEmbeddingLoss(margin=0, size\_average=True)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#CosineEmbeddingLoss)
給定 輸入 `Tensors`,`x1`, `x2` 和一個標簽Tensor `y`(元素的值為1或-1)。此標準使用`cosine`距離測量兩個輸入是否相似,一般用來用來學習非線性`embedding`或者半監督學習。
`margin`應該是-1到1之間的值,建議使用0到0.5。如果沒有傳入`margin`實參,默認值為0。
每個樣本的loss是:
$$ loss(x, y) = \\begin{cases} 1 - cos(x1, x2), &if~y == 1 \\ max(0, cos(x1, x2) - margin), &if~y == -1 \\end{cases}
$$ 如果`size_average=True` 求出的loss會對batch求均值,如果`size_average=False`的話,則會累加`loss`。默認情況`size_average=True`。
### class torch.nn.MultiMarginLoss(p=1, margin=1, weight=None, size\_average=True)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#MultiMarginLoss)
用來計算multi-class classification的hinge loss(magin-based loss)。輸入是 `x`(2D mini-batch Tensor), `y`(1D Tensor)包含類別的索引, `0 <= y <= x.size(1))`。
對每個mini-batch樣本:
$$ loss(x, y) = \\frac{1}{x.size(0)}\\sum\_{i=0}^I(max(0, margin - x\[y\] + x\[i\])^p)
$$ 其中 `I=x.size(0)` $i\\neq y$。 可選擇的,如果您不想所有的類擁有同樣的權重的話,您可以通過在構造函數中傳入`weights`參數來解決這個問題,`weights`是一個1D權重Tensor。
傳入weights后,loss函數變為:
$$ loss(x, y) = \\frac{1}{x.size(0)}\\sum\_imax(0, w\[y\] \* (margin - x\[y\] - x\[i\]))^p
$$ 默認情況下,求出的loss會對mini-batch取平均,可以通過設置`size_average=False`來取消取平均操作。
## Vision layers
### class torch.nn.PixelShuffle(upscale\_factor)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/pixelshuffle.html#PixelShuffle)
將shape為$\[N, C*r^2, H, W\]$的`Tensor`重新排列為shape為$\[N, C, H*r, W\*r\]$的Tensor。 當使用`stride=1/r` 的sub-pixel卷積的時候,這個方法是非常有用的。
請看paper[Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network by Shi et. al (2016)](https://arxiv.org/abs/1609.05158) 獲取詳細信息。
參數說明:
- upscale\_factor (int) – 增加空間分辨率的因子
Shape:
- Input: $\[N,C\*upscale\_factor^2,H,W$\]
- Output: $\[N,C,H*upscale\_factor,W*upscale\_factor\]$
例子:
```
>>> ps = nn.PixelShuffle(3)
>>> input = autograd.Variable(torch.Tensor(1, 9, 4, 4))
>>> output = ps(input)
>>> print(output.size())
torch.Size([1, 1, 12, 12])
```
### class torch.nn.UpsamplingNearest2d(size=None, scale\_factor=None)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/upsampling.html#UpsamplingNearest2d)
對于多channel 輸入 進行 `2-D` 最近鄰上采樣。
可以通過`size`或者`scale_factor`來指定上采樣后的圖片大小。
當給定`size`時,`size`的值將會是輸出圖片的大小。
參數:
- size (tuple, optional) – 一個包含兩個整數的元組 (H\_out, W\_out)指定了輸出的長寬
- scale\_factor (int, optional) – 長和寬的一個乘子
形狀:
- Input: (N,C,H\_in,W\_in)
- Output: (N,C,H\_out,W\_out) Hout=floor(H\_in?scale\_factor) Wout=floor(W\_in?scale\_factor)
例子:
```
>>> inp
Variable containing:
(0 ,0 ,.,.) =
1 2
3 4
[torch.FloatTensor of size 1x1x2x2]
>>> m = nn.UpsamplingNearest2d(scale_factor=2)
>>> m(inp)
Variable containing:
(0 ,0 ,.,.) =
1 1 2 2
1 1 2 2
3 3 4 4
3 3 4 4
[torch.FloatTensor of size 1x1x4x4]
```
### class torch.nn.UpsamplingBilinear2d(size=None, scale\_factor=None)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/modules/upsampling.html#UpsamplingBilinear2d)
對于多channel 輸入 進行 `2-D``bilinear` 上采樣。
可以通過`size`或者`scale_factor`來指定上采樣后的圖片大小。
當給定`size`時,`size`的值將會是輸出圖片的大小。
參數:
- size (tuple, optional) – 一個包含兩個整數的元組 (H\_out, W\_out)指定了輸出的長寬
- scale\_factor (int, optional) – 長和寬的一個乘子
形狀:
- Input: (N,C,H\_in,W\_in)
- Output: (N,C,H\_out,W\_out) Hout=floor(H\_in?scale\_factor) Wout=floor(W\_in?scale\_factor)
例子:
```
>>> inp
Variable containing:
(0 ,0 ,.,.) =
1 2
3 4
[torch.FloatTensor of size 1x1x2x2]
>>> m = nn.UpsamplingBilinear2d(scale_factor=2)
>>> m(inp)
Variable containing:
(0 ,0 ,.,.) =
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
[torch.FloatTensor of size 1x1x4x4]
```
## Multi-GPU layers
### class torch.nn.DataParallel(module, device\_ids=None, output\_device=None, dim=0)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/parallel/data_parallel.html#DataParallel)
在模塊級別上實現數據并行。
此容器通過將`mini-batch`劃分到不同的設備上來實現給定`module`的并行。在`forward`過程中,`module`會在每個設備上都復制一遍,每個副本都會處理部分輸入。在`backward`過程中,副本上的梯度會累加到原始`module`上。
batch的大小應該大于所使用的GPU的數量。還應當是GPU個數的整數倍,這樣劃分出來的每一塊都會有相同的樣本數量。
請看: <a class="pcalibre1 pcalibre pcalibre3 pcalibre2" href="">Use nn.DataParallel instead of multiprocessing</a>
除了`Tensor`,任何位置參數和關鍵字參數都可以傳到DataParallel中。所有的變量會通過指定的`dim`來劃分(默認值為0)。原始類型將會被廣播,但是所有的其它類型都會被淺復制。所以如果在模型的`forward`過程中寫入的話,將會被損壞。
參數說明:
- module – 要被并行的module
- device\_ids – CUDA設備,默認為所有設備。
- output\_device – 輸出設備(默認為device\_ids\[0\])
例子:
```
net = torch.nn.DataParallel(model, device_ids=[0, 1, 2])
output = net(input_var)
```
## Utilities
工具函數
### torch.nn.utils.clip\_grad\_norm(parameters, max\_norm, norm\_type=2)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/utils/clip_grad.html#clip_grad_norm)
Clips gradient norm of an iterable of parameters.
正則項的值由所有的梯度計算出來,就像他們連成一個向量一樣。梯度被`in-place operation`修改。
參數說明:
- parameters (Iterable\[Variable\]) – 可迭代的`Variables`,它們的梯度即將被標準化。
- max\_norm (float or int) – `clip`后,`gradients` p-norm 值
- norm\_type (float or int) – 標準化的類型,p-norm. 可以是`inf` 代表 infinity norm.
[關于norm](https://rorasa.wordpress.com/2012/05/13/l0-norm-l1-norm-l2-norm-l-infinity-norm/)
返回值:
所有參數的p-norm值。
### torch.nn.utils.rnn.PackedSequence(\_cls, data, batch\_sizes)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/utils/rnn.html#PackedSequence)
Holds the data and list of batch\_sizes of a packed sequence.
All RNN modules accept packed sequences as inputs. 所有的`RNN`模塊都接收這種被包裹后的序列作為它們的輸入。
`NOTE:`這個類的實例不能手動創建。它們只能被 `pack_padded_sequence()` 實例化。
參數說明:
- data (Variable) – 包含打包后序列的`Variable`。
- batch\_sizes (list\[int\]) – 包含 `mini-batch` 中每個序列長度的列表。
### torch.nn.utils.rnn.pack\_padded\_sequence(input, lengths, batch\_first=False)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/utils/rnn.html#PackedSequence)
這里的`pack`,理解成壓緊比較好。 將一個 填充過的變長序列 壓緊。(填充時候,會有冗余,所以壓緊一下)
輸入的形狀可以是(T×B× *)。`T`是最長序列長度,`B`是`batch size`,`*`代表任意維度(可以是0)。如果`batch\_first=True`的話,那么相應的`input size`就是`(B×T×\*)`。
`Variable`中保存的序列,應該按序列長度的長短排序,長的在前,短的在后。即`input[:,0]`代表的是最長的序列,`input[:, B-1]`保存的是最短的序列。
`NOTE:`只要是維度大于等于2的`input`都可以作為這個函數的參數。你可以用它來打包`labels`,然后用`RNN`的輸出和打包后的`labels`來計算`loss`。通過`PackedSequence`對象的`.data`屬性可以獲取 `Variable`。
參數說明:
- input (Variable) – 變長序列 被填充后的 batch
- lengths (list\[int\]) – `Variable` 中 每個序列的長度。
- batch\_first (bool, optional) – 如果是`True`,input的形狀應該是`B*T*size`。
返回值:
一個`PackedSequence` 對象。
### torch.nn.utils.rnn.pad\_packed\_sequence(sequence, batch\_first=False)[\[source\]](http://pytorch.org/docs/_modules/torch/nn/utils/rnn.html#pack_padded_sequence)
填充`packed_sequence`。
上面提到的函數的功能是將一個填充后的變長序列壓緊。 這個操作和pack\_padded\_sequence()是相反的。把壓緊的序列再填充回來。
返回的Varaible的值的`size`是 `T×B×*`, `T` 是最長序列的長度,`B` 是 batch\_size,如果 `batch_first=True`,那么返回值是`B×T×*`。
Batch中的元素將會以它們長度的逆序排列。
參數說明:
- sequence (PackedSequence) – 將要被填充的 batch
- batch\_first (bool, optional) – 如果為True,返回的數據的格式為 `B×T×*`。
返回值: 一個tuple,包含被填充后的序列,和batch中序列的長度列表。
例子:
```
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn import utils as nn_utils
batch_size = 2
max_length = 3
hidden_size = 2
n_layers =1
tensor_in = torch.FloatTensor([[1, 2, 3], [1, 0, 0]]).resize_(2,3,1)
tensor_in = Variable( tensor_in ) #[batch, seq, feature], [2, 3, 1]
seq_lengths = [3,1] # list of integers holding information about the batch size at each sequence step
# pack it
pack = nn_utils.rnn.pack_padded_sequence(tensor_in, seq_lengths, batch_first=True)
# initialize
rnn = nn.RNN(1, hidden_size, n_layers, batch_first=True)
h0 = Variable(torch.randn(n_layers, batch_size, hidden_size))
#forward
out, _ = rnn(pack, h0)
# unpack
unpacked = nn_utils.rnn.pad_packed_sequence(out)
print(unpacked)
```
[關于packed\_sequence](https://discuss.pytorch.org/t/how-can-i-compute-seq2seq-loss-using-mask/861)
- PyTorch 中文文檔
- 主頁
- 自動求導機制
- CUDA語義
- 擴展PyTorch
- 多進程最佳實踐
- 序列化語義
- torch
- torch.Tensor
- torch.Storage
- torch.nn
- torch.nn.functional
- torch.autograd
- torch.optim
- torch.nn.init
- torch.multiprocessing
- torch.legacy
- torch.cuda
- torch.utils.ffi
- torch.utils.data
- torch.utils.model_zoo
- torchvision
- torchvision.datasets
- torchvision.models
- torchvision.transforms
- torchvision.utils
- 致謝