torch.nn

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

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

    参数说明:

    • data (Tensor) – parameter tensor.

    • requires_grad (bool, optional) – 如果需要计算剃度,可以参考从向后排除子图

    Containers:

    class torch.nn.Module

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

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

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

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

    add_module(name, module)

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

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

    输出:

    1. Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1))

    apply(fn)

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

    1. >>> def init_weights(m):
    2. >>> print(m)
    3. >>> if type(m) == nn.Linear:
    4. >>> m.weight.data.fill_(1.0)
    5. >>> print(m.weight)
    6. >>>
    7. >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
    8. >>> net.apply(init_weights)
    9. Linear (2 -> 2)
    10. Parameter containing:
    11. 1 1
    12. 1 1
    13. [torch.FloatTensor of size 2x2]
    14. Linear (2 -> 2)
    15. Parameter containing:
    16. 1 1
    17. 1 1
    18. [torch.FloatTensor of size 2x2]
    19. Sequential (
    20. (0): Linear (2 -> 2)
    21. (1): Linear (2 -> 2)
    22. )

    children()

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

    cpu(device_id=None)

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

    cuda(device_id=None)

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

    参数说明:

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

    double()

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

    eval()

    将模型设置成evaluation模式

    仅仅当模型中有DropoutBatchNorm是才会有影响。

    float()

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

    forward(* input)

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

    half()

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

    load_state_dict(state_dict)

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

    参数说明:

    • state_dict (dict) – 保存parameterspersistent buffersdict

    modules()

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

    1. >>> l = nn.Linear(2, 2)
    2. >>> net = nn.Sequential(l, l)
    3. >>> for idx, m in enumerate(net.modules()):
    4. >>> print(idx, '->', m)
    5. 0 -> Sequential (
    6. (0): Linear (2 -> 2)
    7. (1): Linear (2 -> 2)
    8. )
    9. 1 -> Linear (2 -> 2)

    named_children()

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

    例子:

    1. >>> for name, module in model.named_children():
    2. >>> if name in ['conv4', 'conv5']:
    3. >>> print(module)

    named_modules(memo=None, prefix=’’)

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

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

    1. >> l = nn.Linear(2, 2)
    2. >> net = nn.Sequential(l, l)
    3. >> for idx, m in enumerate(net.named_modules()):
    4. >> print(idx, '->', m)
    5. 0 -> ('', Sequential (
    6. (0): Linear (2 -> 2)
    7. (1): Linear (2 -> 2)
    8. ))
    9. 1 -> ('0', Linear (2 -> 2))

    named_parameters(memo=None, prefix=’’)

    返回模块参数的迭代器,同时产生参数的名称以及参数本身 例如:

    1. >> for name, param in self.named_parameters():
    2. >> if name in ['bias']:
    3. >> print(param.size())

    parameters()

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

    例子:

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

    register_backward_hook(hook)

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

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

    1. hook(module, grad_input, grad_output) -> Variable or None

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

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

    register_buffer(name, tensor)

    module添加一个持久缓冲区。

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

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

    例子:

    1. self.register_buffer('running_mean', torch.zeros(num_features))

    register_forward_hook(hook)

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

    1. hook(module, input, output) -> None

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

    register_parameter(name, param)

    module添加 parameter

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

    state_dict(destination=None, prefix=’’)

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

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

    例子:

    1. module.state_dict().keys()
    2. # ['bias', 'weight']

    train(mode=True)

    将模块设置为训练模式。

    仅仅当模型中有DropoutBatchNorm是才会有影响。

    zero_grad()

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

    class torch.nn.Sequential(* args)

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

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

    1. # Example of using Sequential
    2. model = nn.Sequential(
    3. nn.Conv2d(1,20,5),
    4. nn.ReLU(),
    5. nn.Conv2d(20,64,5),
    6. nn.ReLU()
    7. )
    8. # Example of using Sequential with OrderedDict
    9. model = nn.Sequential(OrderedDict([
    10. ('conv1', nn.Conv2d(1,20,5)),
    11. ('relu1', nn.ReLU()),
    12. ('conv2', nn.Conv2d(20,64,5)),
    13. ('relu2', nn.ReLU())
    14. ]))

    class torch.nn.ModuleList(modules=None)

    submodules保存在一个list中。

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

    参数说明:

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

    例子:

    1. class MyModule(nn.Module):
    2. def __init__(self):
    3. super(MyModule, self).__init__()
    4. self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(10)])
    5. def forward(self, x):
    6. # ModuleList can act as an iterable, or be indexed using ints
    7. for i, l in enumerate(self.linears):
    8. x = self.linears[i // 2](x) + l(x)
    9. 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要添加的列表

    例子:

    1. class MyModule(nn.Module):
    2. def __init__(self):
    3. super(MyModule, self).__init__()
    4. self.params = nn.ParameterList([nn.Parameter(torch.randn(10, 10)) for i in range(10)])
    5. def forward(self, x):
    6. # ModuleList can act as an iterable, or be indexed using ints
    7. for i, p in enumerate(self.params):
    8. x = self.params[i // 2].mm(x) + p.mm(x)
    9. 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(Ni, C{outj})=bias(C {outj})+\sum^{C{in}-1}{k=0}weight(C{out_j},k)\bigotimes input(N_i,k)

    说明

    bigotimes: 表示相关系数计算stride: 控制相关系数的计算步长dilation: 用于控制内核点之间的距离,详细描述在这里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,Cin,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:

    1. >>> m = nn.Conv1d(16, 33, 3, stride=2)
    2. >>> input = autograd.Variable(torch.randn(20, 16, 50))
    3. >>> 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(Ni, C{outj})=bias(C{outj})+\sum^{C{in}-1}{k=0}weight(C{out_j},k)\bigotimes input(N_i,k)

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

    参数kernel_sizestride,paddingdilation也可以是一个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,Cin,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}+2padding[1]-dilation[1](kernerl_size[1]-1)-1)/stride[1]+1)

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

    Examples:

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

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

    三维卷积层, 输入的尺度是(N, Cin,D,H,W),输出尺度(N,C_out,D_out,H_out,W_out)的计算方式:out(N_i, C{outj})=bias(C{outj})+\sum^{C{in}-1}{k=0}weight(C{out_j},k)\bigotimes input(N_i,k)

    说明bigotimes: 表示二维的相关系数计算 stride: 控制相关系数的计算步长dilation: 用于控制内核点之间的距离,详细描述在这里groups: 控制输入和输出之间的连接: group=1,输出是所有的输入的卷积;group=2,此时相当于有并排的两个卷积层,每个卷积层计算输入通道的一半,并且产生的输出是输出通道的一半,随后将这两个输出连接起来。参数kernel_sizestridepaddingdilation可以是一个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] (kernelsize[0] - 1) - 1) / stride[0] + 1)) (H{out} = floor((H{in} + 2 _padding[1] - dilation[1] (kernelsize[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:

    1. >>> # With square kernels and equal stride
    2. >>> m = nn.Conv3d(16, 33, 3, stride=2)
    3. >>> # non-square kernels and unequal stride and with padding
    4. >>> m = nn.Conv3d(16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(4, 2, 0))
    5. >>> input = autograd.Variable(torch.randn(20, 16, 10, 50, 100))
    6. >>> 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( 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)

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

    说明

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

    参数kernel_sizestridepaddingdilation数据类型: 可以是一个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] + kernelsize[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

    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: 用于控制内核点之间的距离,详细描述在这里groups: 控制输入和输出之间的连接: group=1,输出是所有的输入的卷积;group=2,此时相当于有并排的两个卷积层,每个卷积层计算输入通道的一半,并且产生的输出是输出通道的一半,随后将这两个输出连接起来。

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

    参数:

    • 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] + kernelsize[0] + output_padding[0]) (H{out} = (H{in} - 1) _stride[1] - 2 padding[1] + kernelsize[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

    1. >>> # With square kernels and equal stride
    2. >>> m = nn.ConvTranspose3d(16, 33, 3, stride=2)
    3. >>> # non-square kernels and unequal stride and with padding
    4. >>> m = nn.Conv3d(16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(0, 4, 2))
    5. >>> input = autograd.Variable(torch.randn(20, 16, 10, 50, 100))
    6. >>> 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,Lout)的计算方式是:out(N_i, C_j,k)=max^{kernel_size-1}{m=0}input(N_{i},C_j,stride*k+m)

    如果padding不是0,会在输入的每一边添加相应数目0dilation用于控制内核点之间的距离,详细描述在

    参数:

    • 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,Cin,L_in)输出: (N,C_out,L_out)L{out}=floor((L{in} + 2_padding - dilation(kernel_size - 1) - 1)/stride + 1

    example:

    1. >>> # pool of size=3, stride=2
    2. >>> m = nn.MaxPool1d(3, stride=2)
    3. >>> input = autograd.Variable(torch.randn(20, 16, 50))
    4. >>> 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,Hout,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,会在输入的每一边添加相应数目0dilation用于控制内核点之间的距离,详细描述在

    参数kernel_sizestride, paddingdilation数据类型: 可以是一个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} + 2padding[1] - dilation[1](kernel_size[1] - 1) - 1)/stride[1] + 1

    example:

    1. >>> # pool of square window of size=3, stride=2
    2. >>> m = nn.MaxPool2d(3, stride=2)
    3. >>> # pool of non-square window
    4. >>> m = nn.MaxPool2d((3, 2), stride=(2, 1))
    5. >>> input = autograd.Variable(torch.randn(20, 16, 50, 32))
    6. >>> 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,Hout,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,会在输入的每一边添加相应数目0dilation用于控制内核点之间的距离,详细描述在

    参数kernel_sizestride, paddingdilation数据类型: 可以是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,Hin,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} + 2padding[1] - dilation[1](kernel_size[0] - 1) - 1)/stride[1] + 1)

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

    example:

    1. >>> # pool of square window of size=3, stride=2
    2. >>>m = nn.MaxPool3d(3, stride=2)
    3. >>> # pool of non-square window
    4. >>> m = nn.MaxPool3d((3, 2, 2), stride=(2, 1, 2))
    5. >>> input = autograd.Variable(torch.randn(20, 16, 50,44, 31))
    6. >>> 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,Hin)output:(N,C,H_out)H{out}=(H_{in}-1)_stride[0]-2_padding[0]+kernel_size[0]也可以使用output_size指定输出的大小

    Example:

    1. >>> pool = nn.MaxPool1d(2, stride=2, return_indices=True)
    2. >>> unpool = nn.MaxUnpool1d(2, stride=2)
    3. >>> input = Variable(torch.Tensor([[[1, 2, 3, 4, 5, 6, 7, 8]]]))
    4. >>> output, indices = pool(input)
    5. >>> unpool(output, indices)
    6. Variable containing:
    7. (0 ,.,.) =
    8. 0 2 0 4 0 6 0 8
    9. [torch.FloatTensor of size 1x1x8]
    10. >>> # Example showcasing the use of output_size
    11. >>> input = Variable(torch.Tensor([[[1, 2, 3, 4, 5, 6, 7, 8, 9]]]))
    12. >>> output, indices = pool(input)
    13. >>> unpool(output, indices, output_size=input.size())
    14. Variable containing:
    15. (0 ,.,.) =
    16. 0 2 0 4 0 6 0 8 0
    17. [torch.FloatTensor of size 1x1x9]
    18. >>> unpool(output, indices)
    19. Variable containing:
    20. (0 ,.,.) =
    21. 0 2 0 4 0 6 0 8
    22. [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:需要转换的tensorindices: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:

    1. >>> pool = nn.MaxPool2d(2, stride=2, return_indices=True)
    2. >>> unpool = nn.MaxUnpool2d(2, stride=2)
    3. >>> input = Variable(torch.Tensor([[[[ 1, 2, 3, 4],
    4. ... [ 5, 6, 7, 8],
    5. ... [ 9, 10, 11, 12],
    6. ... [13, 14, 15, 16]]]]))
    7. >>> output, indices = pool(input)
    8. >>> unpool(output, indices)
    9. Variable containing:
    10. (0 ,0 ,.,.) =
    11. 0 0 0 0
    12. 0 6 0 8
    13. 0 0 0 0
    14. 0 14 0 16
    15. [torch.FloatTensor of size 1x1x4x4]
    16. >>> # specify a different output size than input size
    17. >>> unpool(output, indices, output_size=torch.Size([1, 1, 5, 5]))
    18. Variable containing:
    19. (0 ,0 ,.,.) =
    20. 0 0 0 0 0
    21. 6 0 8 0 0
    22. 0 0 0 14 0
    23. 0 0 0 0 0
    24. [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:需要转换的tensorindicesMaxpool1d的索引序数output_size:一个指定输出大小的torch.Size

    大小:input: (N,C,Din,H_in,W_in)output:(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:

    1. >>> # pool of square window of size=3, stride=2
    2. >>> pool = nn.MaxPool3d(3, stride=2, return_indices=True)
    3. >>> unpool = nn.MaxUnpool3d(3, stride=2)
    4. >>> output, indices = pool(Variable(torch.randn(20, 16, 51, 33, 15)))
    5. >>> unpooled_output = unpool(output, indices)
    6. >>> unpooled_output.size()
    7. 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,Lout)和池化窗口大小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,Lin)output:(N,C,L_out)L{out}=floor((L_{in}+2*padding-kernel_size)/stride+1)

    Example:

    1. >>> # pool with window of size=3, stride=2
    2. >>> m = nn.AvgPool1d(3, stride=2)
    3. >>> m(Variable(torch.Tensor([[[1,2,3,4,5,6,7]]])))
    4. Variable containing:
    5. (0 ,.,.) =
    6. 2 4 6
    7. [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,Hout,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,Hin,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:

    1. >>> # pool of square window of size=3, stride=2
    2. >>> m = nn.AvgPool2d(3, stride=2)
    3. >>> # pool of non-square window
    4. >>> m = nn.AvgPool2d((3, 2), stride=(2, 1))
    5. >>> input = autograd.Variable(torch.randn(20, 16, 50, 32))
    6. >>> 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(Ni,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,Din,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:

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

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

    对输入的信号,提供2维的分数最大化池化操作 分数最大化池化的细节请阅读 由目标输出大小确定的随机步长,在$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:

    1. >>> # pool of square window of size=3, and target output size 13x12
    2. >>> m = nn.FractionalMaxPool2d(3, output_size=(13, 12))
    3. >>> # pool of square window and target output size being half of input image size
    4. >>> m = nn.FractionalMaxPool2d(3, output_ratio=(0.5, 0.5))
    5. >>> input = autograd.Variable(torch.randn(20, 16, 50, 32))
    6. >>> output = m(input)

    对输入信号提供2维的幂平均池化操作。 输出的计算方式:f(x)=pow(sum(X,p),1/p)

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

    参数kernel_size, stride的数据类型:

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

    参数

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

    shape

    • 输入:(N,C,H_in,W_in)
    • 输出:(N,C,Hout,W_out)$$\begin{aligned} H{out} = floor((H{in}+2_padding[0]-dilation[0](kernelsize[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:

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

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

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

    参数:

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

    Example:

    1. >>> # target output size of 5
    2. >>> m = nn.AdaptiveMaxPool1d(5)
    3. >>> input = autograd.Variable(torch.randn(1, 64, 8))
    4. >>> 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:

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

    class torch.nn.AdaptiveAvgPool1d(output_size)

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

    参数:

    • output_size: 输出信号的尺寸

    Example:

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

    class torch.nn.AdaptiveAvgPool2d(output_size)

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

    参数:

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

    Example:

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

    class torch.nn.ReLU(inplace=False)

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

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

    shape:

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

    例子:

    1. >>> m = nn.ReLU()
    2. >>> input = autograd.Variable(torch.randn(2))
    3. >>> print(input)
    4. >>> print(m(input))

    class torch.nn.ReLU6(inplace=False)

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

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

    shape:

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

    例子:

    1. >>> m = nn.ReLU6()
    2. >>> input = autograd.Variable(torch.randn(2))
    3. >>> print(input)
    4. >>> 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属性

    例子:

    对输入的每一个元素运用函数$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属性

    例子:

    1. >>> m = nn.PReLU()
    2. >>> input = autograd.Variable(torch.randn(2))
    3. >>> print(input)
    4. >>> 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属性

    例子:

    1. >>> m = nn.LeakyReLU(0.1)
    2. >>> input = autograd.Variable(torch.randn(2))
    3. >>> print(input)
    4. >>> print(m(input))

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

    Threshold定义:

    参数:

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

    shape:

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

    例子:

    1. >>> m = nn.Threshold(0.1, 20)
    2. >>> input = Variable(torch.randn(2))
    3. >>> print(input)
    4. >>> 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属性

    例子:

    1. >>> m = nn.Hardtanh()
    2. >>> input = autograd.Variable(torch.randn(2))
    3. >>> print(input)
    4. >>> print(m(input))

    class torch.nn.Sigmoid

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

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

    shape:

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

    例子:

    1. >>> m = nn.Sigmoid()
    2. >>> input = autograd.Variable(torch.randn(2))
    3. >>> print(input)
    4. >>> print(m(input))

    class torch.nn.Tanh

    对输入的每个元素,

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

    shape:

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

    例子:

    1. >>> m = nn.Tanh()
    2. >>> input = autograd.Variable(torch.randn(2))
    3. >>> print(input)
    4. >>> print(m(input))

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

    shape:

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

    例子:

    1. >>> m = nn.LogSigmoid()
    2. >>> input = autograd.Variable(torch.randn(2))
    3. >>> print(input)
    4. >>> 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属性

    例子:

    1. >>> m = nn.Softplus()
    2. >>> input = autograd.Variable(torch.randn(2))
    3. >>> print(input)
    4. >>> 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属性

    例子:

    1. >>> m = nn.Softshrink()
    2. >>> input = autograd.Variable(torch.randn(2))
    3. >>> print(input)
    4. >>> print(m(input))

    class torch.nn.Softsign

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

    shape:

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

    例子:

    1. >>> m = nn.Softsign()
    2. >>> input = autograd.Variable(torch.randn(2))
    3. >>> print(input)
    4. >>> print(m(input))

    class torch.nn.Softshrink(lambd=0.5)

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

    Tanhshrink(x) = x - Tanh(x)

    shape:

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

    例子:

    1. >>> m = nn.Tanhshrink()
    2. >>> input = autograd.Variable(torch.randn(2))
    3. >>> print(input)
    4. >>> 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)

    例子:

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

    对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)区间。

    例子:

    1. >>> m = nn.Softmax()
    2. >>> input = autograd.Variable(torch.randn(2, 3))
    3. >>> print(input)
    4. >>> 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)

    例子:

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

    Normalization layers

    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)(输入输出相同)

    例子

    1. >>> # With Learnable Parameters
    2. >>> m = nn.BatchNorm1d(100)
    3. >>> # Without Learnable Parameters
    4. >>> m = nn.BatchNorm1d(100, affine=False)
    5. >>> input = autograd.Variable(torch.randn(20, 100))
    6. >>> 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)(输入输出相同)

    例子

    1. >>> # With Learnable Parameters
    2. >>> m = nn.BatchNorm2d(100)
    3. >>> # Without Learnable Parameters
    4. >>> m = nn.BatchNorm2d(100, affine=False)
    5. >>> input = autograd.Variable(torch.randn(20, 100, 35, 45))
    6. >>> 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)(输入输出相同)

    例子

    1. >>> # With Learnable Parameters
    2. >>> m = nn.BatchNorm3d(100)
    3. >>> # Without Learnable Parameters
    4. >>> m = nn.BatchNorm3d(100, affine=False)
    5. >>> input = autograd.Variable(torch.randn(20, 100, 35, 45, 10))
    6. >>> output = m(input)

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

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

    对输入序列中每个元素,RNN每层的计算公式为 ht=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): 保存输入序列特征的tensorinput可以是被填充的变长的序列。细节请看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)

    示例:

    1. rnn = nn.RNN(10, 20, 2)
    2. input = Variable(torch.randn(5, 3, 10))
    3. h0 = Variable(torch.randn(2, 3, 20))

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

    对输入序列的每个元素,的每层都会执行以下计算: [\begin{split}\begin{array}{ll} it = \mathrm{sigmoid}(W{ii} xt + b{ii} + W{hi} h{(t-1)} + b{hi}) \ f_t = \mathrm{sigmoid}(W{if} xt + b{if} + W{hf} h{(t-1)} + b{hf}) \ g_t = \tanh(W{ig} xt + b{ig} + W{hc} h{(t-1)} + b{hg}) \ o_t = \mathrm{sigmoid}(W{io} xt + b{io} + W{ho} h{(t-1)} + b{ho}) \ c_t = f_t * c{(t-1)} + it _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$ 分别代表 输入门,遗忘门,细胞

    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} rt = \mathrm{sigmoid}(W{ir} xt + b{ir} + W{hr} h{(t-1)} + b{hr}) \ z_t = \mathrm{sigmoid}(W{iz} xt + b{iz} + W{hz} h{(t-1)} + b{hz}) \ n_t = \tanh(W{in} xt + b{in} + rt * (W{hn} h{(t-1)}+ b{hn})) \ ht = (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