torch.nn

torch.nn

Parameters

CLASS torch.nn.Parameter

一种被视为模块参数的Tensor。 参数是Tensor子类,与Module一起使用时具有非常特殊的属性-当将它们分配为Module属性时,它们会自动添加到其参数列表中,例如在parameters()迭代器中。

  • data (Tensor) – parameter tensor.

  • requires_grad (bool*, *optional) – if the parameter requires gradient. See Excluding subgraphs from backward for more details. Default: <cite style="box-sizing: border-box;">True</cite>
    model中每个parameter都有两个属性,data和requires_grad
    Example:

In [55]: model.conv1.weight.shape
Out[55]: torch.Size([20, 1, 5, 5])

In [56]: model.conv1.bias.shape
Out[56]: torch.Size([20])

In [57]: model.conv1.bias.data
Out[57]:
tensor([ 0.1108, -0.0038, -0.1809,  0.1624, -0.0281,  0.0049, -0.1421, -0.1625,
         0.0212, -0.1995, -0.1207, -0.1948,  0.0134, -0.1771,  0.0689, -0.1327,
         0.0222, -0.1198, -0.0790, -0.1033])

In [58]: model.conv1.bias.requires_grad
Out[58]: True

In [59]: model.conv1.bias
Out[59]:
Parameter containing:
tensor([ 0.1108, -0.0038, -0.1809,  0.1624, -0.0281,  0.0049, -0.1421, -0.1625,
         0.0212, -0.1995, -0.1207, -0.1948,  0.0134, -0.1771,  0.0689, -0.1327,
         0.0222, -0.1198, -0.0790, -0.1033], requires_grad=True)

Containers

Module

CLASS torch.nn.Module

所有神经网络模块的基类。 您的模型也应该继承此类。 模块也可以包含其他模块,从而可以将它们嵌套在树形结构中。您可以将子模块分配为常规属性

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)
        self.conv2 = nn.Conv2d(20, 20, 5)

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

add_module(name, module)

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

apply(fn)

将fn递归应用于每个子模块(由.children()返回)以及self。典型用法包括初始化模型的参数(另请参见torch.nn.init)。
Example:

>>> def init_weights(m):
>>>     print(m)
>>>     if type(m) == nn.Linear:
>>>         m.weight.data.fill_(1.0)
>>>         print(m.weight)
>>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
>>> net.apply(init_weights)
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[ 1.,  1.],
        [ 1.,  1.]])
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[ 1.,  1.],
        [ 1.,  1.]])
Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)

children()

返回children模块上的迭代器。

named_children()

返回直接子模块的迭代器,同时产生模块名称和模块本身。重复的模块仅返回一次

In [103]: for name, module in model.named_children():
     ...:     print(name)
     ...:     print(module)
     ...:
conv1
Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
conv2
Conv2d(20, 20, kernel_size=(5, 5), stride=(1, 1))

modules()

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

>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.modules()):
        print(idx, '->', m)
0 -> Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
1 -> Linear(in_features=2, out_features=2, bias=True)

named_modules(memo=None, prefix='')
在网络中的所有模块上返回一个迭代器,同时产生模块的名称和模块本身。重复的模块仅返回一次

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

0 -> ('', Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
))
1 -> ('0', Linear(in_features=2, out_features=2, bias=True))

parameters(recurse=True)

返回模块参数上的迭代器。 通常将其传递给优化器。

named_parameters(prefix='', recurse=True)

返回模块参数上的迭代器,同时产生参数名称和参数本身。

cpu()

将所有模型parameters和buffers移至CPU。

model.cpu()

cuda(device=None)

将所有模型parameters和buffers移至GPU。

model.cuda()
model.cuda(1)

double()

将所有浮点参数和缓冲区强制转换为double数据类型。

model.double()

float()

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

model.float()

eval()

将模块设置为评估(evaluation)模式。这等同于self.train(False)

forward(*input)

定义每次调用时执行的计算。 应该被所有子类覆盖。

load_state_dict(state_dict, strict=True)

将参数和缓冲区从state_dict复制到此模块及其后代中。如果strictTrue,则state_dict的键必须与该模块的state_dict()函数返回的键model.state_dict().keys()完全匹配。

state_dict(destination=None, prefix='', keep_vars=False)

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

requires_grad_(requires_grad=True)

更改autograd是否应记录此模块中参数的操作。 此方法就地设置参数的require_grad属性。 此方法有助于冻结模块的一部分以分别微调或训练模型的各个部分(例如GAN训练)。

to(device=None, dtype=None, non_blocking=False)
to(dtype, non_blocking=False)
to(tensor, non_blocking=False)

移动和/或强制转换参数和缓冲区。

train(mode=True)

将模块设置为训练模式。 这仅对某些模块有影响。请参阅特定模块的文档,以了解其在培训/评估模式下的行为的详细信息(如果受到影响),例如辍学,BatchNorm等

zero_grad()

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

Sequential

CLASS torch.nn.Sequential(*args)

顺序容器。模块将按照在构造函数中传递的顺序添加到模块中。或者,也可以传递模块的有序字典。

# 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())
        ]))
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容