├── docs ├── torchvision │ ├── torchvision.md │ ├── torchvision-utils.md │ ├── torchvision-transform.md │ ├── torchvision-models.md │ └── torchvision-datasets.md ├── package_references │ ├── legacy.md │ ├── model_zoo.md │ ├── ffi.md │ ├── Storage.md │ ├── data.md │ ├── torch-multiprocessing.md │ ├── torch-cuda.md │ ├── nn_init.md │ ├── torch-autograd.md │ ├── torch-optim.md │ ├── functional.md │ ├── Tensor.md │ └── torch-nn.md ├── notes │ ├── serialization.md │ ├── cuda.md │ ├── multiprocessing.md │ ├── autograd.md │ └── extending.md ├── index.md └── acknowledgement.md ├── mkdocs.yml └── README.md /docs/torchvision/torchvision.md: -------------------------------------------------------------------------------- 1 | # torchvision 2 | `torchvision`包 包含了目前流行的数据集,模型结构和常用的图片转换工具。 3 | -------------------------------------------------------------------------------- /docs/package_references/legacy.md: -------------------------------------------------------------------------------- 1 | # 遗产包 - torch.legacy 2 | 此包中包含从Lua Torch移植来的代码。 3 | 4 | 为了可以使用现有的模型并且方便当前Lua Torch使用者过渡,我们创建了这个包。 可以在`torch.legacy.nn`中找到`nn`代码,并在`torch.legacy.optim`中找到`optim`代码。 API应该完全匹配Lua Torch。 5 | -------------------------------------------------------------------------------- /docs/notes/serialization.md: -------------------------------------------------------------------------------- 1 | # 序列化语义 2 | ## 最佳实践 3 | ### 保存模型的推荐方法 4 | 这主要有两种方法序列化和恢复模型。 5 | 6 | 第一种(推荐)只保存和加载模型参数: 7 | ```python 8 | torch.save(the_model.state_dict(), PATH) 9 | ``` 10 | 然后: 11 | ```python 12 | the_model = TheModelClass(*args, **kwargs) 13 | the_model.load_state_dict(torch.load(PATH)) 14 | ``` 15 | 第二种保存和加载整个模型: 16 | ```python 17 | torch.save(the_model, PATH) 18 | ``` 19 | 然后: 20 | ```python 21 | the_model = torch.load(PATH) 22 | ``` 23 | 然而,在这种情况下,序列化的数据被绑定到特定的类和固定的目录结构,所以当在其他项目中使用时,或者在一些严重的重构器之后它可能会以各种方式break。 24 | -------------------------------------------------------------------------------- /docs/package_references/model_zoo.md: -------------------------------------------------------------------------------- 1 | # torch.utils.model_zoo 2 | 3 | ```python 4 | torch.utils.model_zoo.load_url(url, model_dir=None) 5 | ``` 6 | 7 | 在给定URL上加载Torch序列化对象。 8 | 9 | 如果对象已经存在于 *model_dir* 中,则将被反序列化并返回。URL的文件名部分应遵循命名约定`filename-.ext`,其中``是文件内容的SHA256哈希的前八位或更多位数字。哈希用于确保唯一的名称并验证文件的内容。 10 | 11 | *model_dir* 的默认值为`$TORCH_HOME/models`,其中`$TORCH_HOME`默认为`~/.torch`。可以使用`$TORCH_MODEL_ZOO`环境变量来覆盖默认目录。 12 | 13 | **参数:** 14 | 15 | - **url** (*string*) - 要下载对象的URL 16 | - **model_dir** (*string*, optional) - 保存对象的目录 17 | 18 | **例子:** 19 | ```python 20 | >>> state_dict = torch.utils.model_zoo.load_url('https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth') 21 | ``` 22 | -------------------------------------------------------------------------------- /docs/torchvision/torchvision-utils.md: -------------------------------------------------------------------------------- 1 | # torchvision.utils 2 | 3 | ## torchvision.utils.make_grid(tensor, nrow=8, padding=2, normalize=False, range=None, scale_each=False) 4 | 猜测,用来做 `雪碧图的`(`sprite image`)。 5 | 6 | 给定 `4D mini-batch Tensor`, 形状为 `(B x C x H x W)`,或者一个`a list of image`,做成一个`size`为`(B / nrow, nrow)`的雪碧图。 7 | 8 | - normalize=True ,会将图片的像素值归一化处理 9 | 10 | - 如果 range=(min, max), min和max是数字,那么`min`,`max`用来规范化`image` 11 | 12 | - scale_each=True ,每个图片独立规范化,而不是根据所有图片的像素最大最小值来规范化 13 | 14 | [Example usage is given in this notebook](https://gist.github.com/anonymous/bf16430f7750c023141c562f3e9f2a91) 15 | 16 | ## torchvision.utils.save_image(tensor, filename, nrow=8, padding=2, normalize=False, range=None, scale_each=False) 17 | 18 | 将给定的`Tensor`保存成image文件。如果给定的是`mini-batch tensor`,那就用`make-grid`做成雪碧图,再保存。 19 | -------------------------------------------------------------------------------- /docs/package_references/ffi.md: -------------------------------------------------------------------------------- 1 | # torch.utils.ffi 2 | ```python 3 | torch.utils.ffi.create_extension(name, headers, sources, verbose=True, with_cuda=False, package=False, relative_to='.', **kwargs) 4 | ``` 5 | 创建并配置一个cffi.FFI对象,用于PyTorch的扩展。 6 | 7 | **参数:** 8 | 9 | - **name** (*str*) – 包名。可以是嵌套模块,例如 `.ext.my_lib`。 10 | - **headers** (*str* or List[*str*]) – 只包含导出函数的头文件列表 11 | - **sources** (List[*str*]) – 用于编译的sources列表 12 | - **verbose** (*bool*, optional) – 如果设置为False,则不会打印输出(默认值:`True`)。 13 | - **with_cuda** (*bool*, optional) – 设置为True以使用CUDA头文件进行编译(默认值:`False`)。 14 | - **package** (*bool*, optional) – 设置为True以在程序包模式下构建(对于要作为pip程序包安装的模块)(默认值:`False`)。 15 | - **relative_to** (*str*, optional) –构建文件的路径。`package`为`True`时需要。最好使用`__file__`作为参数。 16 | - **kwargs** – 传递给ffi以声明扩展的附加参数。有关详细信息,请参阅[Extension API reference](https://docs.python.org/3/distutils/apiref.html#distutils.core.Extension)。 17 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | # PyTorch中文文档 2 | PyTorch是使用GPU和CPU优化的深度学习张量库。 3 | 4 | ## 说明 5 | - [自动求导机制](notes/autograd.md) 6 | - [CUDA语义](notes/cuda.md) 7 | - [扩展PyTorch](notes/extending.md) 8 | - [多进程最佳实践](notes/multiprocessing.md) 9 | - [序列化语义](notes/serialization.md) 10 | 11 | ## Package参考 12 | - [torch](package_references/torch.md) 13 | - [torch.Tensor](package_references/Tensor.md) 14 | - [torch.Storage](package_references/Storage.md) 15 | - [torch.nn](package_references/torch-nn.md) 16 | - [torch.nn.functional](package_references/functional.md) 17 | - [torch.nn.init](package_references/nn_init.md) 18 | - [torch.optim](package_references/torch-optim.md) 19 | - [torch.autograd](package_references/torch-autograd.md) 20 | - [torch.multiprocessing](package_references/torch-multiprocessing.md) 21 | - [torch.legacy](package_references/legacy.md) 22 | - [torch.cuda](package_references/torch-cuda.md) 23 | - [torch.utils.ffi](package_references/ffi.md) 24 | - [torch.utils.data](package_references/data.md) 25 | - [torch.utils.model_zoo](package_references/model_zoo.md) 26 | 27 | ## torchvision参考 28 | - [torchvision](torchvision/torchvision.md) 29 | - [torchvision.datasets](torchvision/torchvision-datasets.md) 30 | - [torchvision.models](torchvision/torchvision-models.md) 31 | - [torchvision.transforms](torchvision/torchvision-transform.md) 32 | - [torchvision.utils](torchvision/torchvision-utils.md) 33 | ## 致谢 34 | - [致谢](acknowledgement.md) 35 | -------------------------------------------------------------------------------- /docs/notes/cuda.md: -------------------------------------------------------------------------------- 1 | # CUDA语义 2 | `torch.cuda`会记录当前选择的GPU,并且分配的所有CUDA张量将在上面创建。可以使用`torch.cuda.device`上下文管理器更改所选设备。 3 | 4 | 但是,一旦张量被分配,您可以直接对其进行操作,而不考虑所选择的设备,结果将始终放在与张量相同的设备上。 5 | 6 | 默认情况下,不支持跨GPU操作,唯一的例外是`copy_()`。 除非启用对等存储器访问,否则对分布不同设备上的张量任何启动操作的尝试都将会引发错误。 7 | 8 | 下面你可以找到一个展示如下的小例子: 9 | ```python 10 | x = torch.cuda.FloatTensor(1) 11 | # x.get_device() == 0 12 | y = torch.FloatTensor(1).cuda() 13 | # y.get_device() == 0 14 | 15 | with torch.cuda.device(1): 16 | # allocates a tensor on GPU 1 17 | a = torch.cuda.FloatTensor(1) 18 | 19 | # transfers a tensor from CPU to GPU 1 20 | b = torch.FloatTensor(1).cuda() 21 | # a.get_device() == b.get_device() == 1 22 | 23 | c = a + b 24 | # c.get_device() == 1 25 | 26 | z = x + y 27 | # z.get_device() == 0 28 | 29 | # even within a context, you can give a GPU id to the .cuda call 30 | d = torch.randn(2).cuda(2) 31 | # d.get_device() == 2 32 | ``` 33 | 34 | ## 最佳实践 35 | ### 使用固定的内存缓冲区 36 | 当副本来自固定(页锁)内存时,主机到GPU的复制速度要快很多。CPU张量和存储开放了一个`pin_memory()`方法,它返回该对象的副本,而它的数据放在固定区域中。 37 | 38 | 另外,一旦固定了张量或存储,就可以使用异步的GPU副本。只需传递一个额外的`async=True`参数到`cuda()`的调用。这可以用于将数据传输与计算重叠。 39 | 40 | 通过将`pin_memory=True`传递给其构造函数,可以使`DataLoader`将batch返回到固定内存中。 41 | ### 使用 nn.DataParallel 替代 multiprocessing 42 | 大多数涉及批量输入和多个GPU的情况应默认使用`DataParallel`来使用多个GPU。尽管有GIL的存在,单个python进程也可能使多个GPU饱和。 43 | 44 | 从0.1.9版本开始,大量的GPU(8+)可能未被充分利用。然而,这是一个已知的问题,也正在积极开发。和往常一样,测试你的用例吧。 45 | 46 | 调用`multiprocessing`来利用CUDA模型存在重要的注意事项;使用具有多处理功能的CUDA模型有重要的注意事项; 除非就是需要谨慎地满足数据处理需求,否则您的程序很可能会出现错误或未定义的行为。 47 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: PyTorch中文文档 2 | pages: 3 | - 主页: index.md 4 | - 说明: 5 | - 自动求导机制: notes/autograd.md 6 | - CUDA语义: notes/cuda.md 7 | - 扩展PyTorch: notes/extending.md 8 | - 多进程最佳实践: notes/multiprocessing.md 9 | - 序列化语义: notes/serialization.md 10 | - PACKAGE参考: 11 | - torch: package_references/torch.md 12 | - torch.Tensor: package_references/Tensor.md 13 | - torch.Storage: package_references/Storage.md 14 | - torch.nn: package_references/torch-nn.md 15 | - torch.nn.functional: package_references/functional.md 16 | - torch.autograd: package_references/torch-autograd.md 17 | - torch.optim: package_references/torch-optim.md 18 | - torch.nn.init: package_references/nn_init.md 19 | - torch.multiprocessing: package_references/torch-multiprocessing.md 20 | - torch.legacy: package_references/legacy.md 21 | - torch.cuda: package_references/torch-cuda.md 22 | - torch.utils.ffi: package_references/ffi.md 23 | - torch.utils.data: package_references/data.md 24 | - torch.utils.model_zoo: package_references/model_zoo.md 25 | - TORCHVISION参考: 26 | - torchvision: torchvision/torchvision.md 27 | - torchvision.datasets: torchvision/torchvision-datasets.md 28 | - torchvision.models: torchvision/torchvision-models.md 29 | - torchvision.transforms: torchvision/torchvision-transform.md 30 | - torchvision.utils: torchvision/torchvision-utils.md 31 | - 致谢: acknowledgement.md 32 | 33 | theme: readthedocs 34 | 35 | extra_javascript: ['https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML','js/mathjaxhelper.js'] 36 | -------------------------------------------------------------------------------- /docs/package_references/Storage.md: -------------------------------------------------------------------------------- 1 | # torch.Storage 2 | 3 | 一个`torch.Storage`是一个单一数据类型的连续一维数组。 4 | 5 | 每个`torch.Tensor`都有一个对应的、相同数据类型的存储。 6 | 7 | ```python 8 | class torch.FloatStorage 9 | ``` 10 | 11 | #### byte() 12 | 将此存储转为byte类型 13 | 14 | #### char() 15 | 将此存储转为char类型 16 | 17 | #### clone() 18 | 返回此存储的一个副本 19 | 20 | #### copy_() 21 | 22 | #### cpu() 23 | 如果当前此存储不在CPU上,则返回一个它的CPU副本 24 | 25 | #### cuda(*device=None, async=False*) 26 | 返回此对象在CUDA内存中的一个副本。 27 | 如果此对象已在CUDA内存中且在正确的设备上,那么不会执行复制操作,直接返回原对象。 28 | 29 | **参数:** 30 | 31 | - **device** (*[int]()*) - 目标GPU的id。默认值是当前设备。 32 | - **async** (*[bool]()*) -如果值为True,且源在锁定内存中,则副本相对于宿主是异步的。否则此参数不起效果。 33 | 34 | #### data_ptr() 35 | 36 | #### double() 37 | 将此存储转为double类型 38 | 39 | #### element_size() 40 | 41 | #### fill_() 42 | 43 | #### float() 44 | 将此存储转为float类型 45 | 46 | #### from_buffer() 47 | 48 | #### half() 49 | 将此存储转为half类型 50 | 51 | #### int() 52 | 将此存储转为int类型 53 | 54 | #### is_cuda = *False* 55 | 56 | #### is_pinned() 57 | 58 | #### is_shared() 59 | 60 | #### is_sparse = *False* 61 | 62 | #### long() 63 | 将此存储转为long类型 64 | 65 | #### new() 66 | 67 | #### pin_memory() 68 | 如果此存储当前未被锁定,则将它复制到锁定内存中。 69 | 70 | #### resize_() 71 | 72 | #### share_memory_() 73 | 将此存储移动到共享内存中。 74 | 对于已经在共享内存中的存储或者CUDA存储,这是一条空指令,它们不需要移动就能在进程间共享。共享内存中的存储不能改变大小。 75 | 返回:self 76 | 77 | #### short() 78 | 将此存储转为short类型 79 | 80 | #### size() 81 | 82 | #### tolist() 83 | 返回一个包含此存储中元素的列表 84 | 85 | #### type(*new_type=None, async=False*) 86 | 将此对象转为指定类型。 87 | 如果已经是正确类型,不会执行复制操作,直接返回原对象。 88 | 89 | **参数:** 90 | 91 | - **new_type** (*[type]() or [string]()*) -需要转成的类型 92 | - **async** (*[bool]()*) -如果值为True,且源在锁定内存中而目标在GPU中——或正好相反,则复制操作相对于宿主异步执行。否则此参数不起效果。 -------------------------------------------------------------------------------- /docs/acknowledgement.md: -------------------------------------------------------------------------------- 1 | # 致谢 2 | 本项目贡献者如下: 3 | 4 | ## 文档翻译 5 | 6 | | 贡献者 | 页面 | 章节 | 7 | |:----:|:----:|:----:| 8 | |ycszen|主页|| 9 | |ycszen|说明|自动求导机制| 10 | |ycszen|说明|CUDA语义| 11 | |KeithYin|说明|扩展PyTorch| 12 | |ycszen|说明|多进程最佳实践| 13 | |ycszen|说明|序列化语义| 14 | |koshinryuu|package参考|torch| 15 | |weigp|package参考|torch.Tensor| 16 | |kophy|package参考|torch.Storage| 17 | |KeithYin|package参考|torch.nn/Parameters| 18 | |KeithYin|package参考|torch.nn/Containers| 19 | |yichuan9527|package参考|torch.nn/Convolution Layers| 20 | |yichuan9527|package参考|torch.nn/Pooling Layers| 21 | |swordspoet|package参考|torch.nn/Non-linear Activations| 22 | |XavierLin|package参考|torch.nn/Normalization layers| 23 | |KeithYin|package参考|torch.nn/Recurrent layers| 24 | ||package参考|torch.nn/Linear layers| 25 | ||package参考|torch.nn/Dropout layers| 26 | ||package参考|torch.nn/Distance functions| 27 | |KeithYin|package参考|torch.nn/Loss functions| 28 | |KeithYin|package参考|torch.nn/Vision layers| 29 | |KeithYin|package参考|torch.nn/Multi-GPU layers| 30 | |KeithYin|package参考|torch.nn/Utilities| 31 | |ycszen|package参考|torch.nn.functional/Convolution functions| 32 | |ycszen|package参考|torch.nn.functional/Pooling function| 33 | |ycszen|package参考|torch.nn.functional/Non-linear activations functions| 34 | |ycszen|package参考|torch.nn.functional/Normalization functions| 35 | |dyl745001196|package参考|torch.nn.functional/Linear functions| 36 | |dyl745001196|package参考|torch.nn.functional/Dropout functions| 37 | |dyl745001196|package参考|torch.nn.functional/Distance functions| 38 | |tfygg|package参考|torch.nn.functinal/Loss functions| 39 | |KeithYin|package参考|torch.nn.functional/Vision functions| 40 | |kophy|package参考|torch.nn.init| 41 | |KeithYin|package参考|torch.autograd| 42 | |songbo.han|package参考|torch.multiprocessing| 43 | |ZijunDeng|package参考|torch.optim| 44 | |ycszen|pacakge参考|torch.legacy| 45 | |ycszen|package参考|torch.cuda| 46 | |ycszen|pacakge参考|torch.utils.ffi| 47 | |ycszen|package参考|torch.utils.model_zoo| 48 | |ycszen|package参考|torch.utils.data| 49 | |KeithYin|torchvision参考|torchvision| 50 | |KeithYin|torchvision参考|torchvision.datasets| 51 | |KeithYin|torchvision参考|torchvision.models| 52 | |KeithYin|torchvision参考|torchvision.transforms| 53 | |KeithYin|torchvision参考|torchvision.utils| 54 | |ycszen|致谢|| 55 | -------------------------------------------------------------------------------- /docs/package_references/data.md: -------------------------------------------------------------------------------- 1 | # torch.utils.data 2 | ```python 3 | class torch.utils.data.Dataset 4 | ``` 5 | 6 | 表示Dataset的抽象类。 7 | 8 | 所有其他数据集都应该进行子类化。所有子类应该override`__len__`和`__getitem__`,前者提供了数据集的大小,后者支持整数索引,范围从0到len(self)。 9 | 10 | ```python 11 | class torch.utils.data.TensorDataset(data_tensor, target_tensor) 12 | ``` 13 | 包装数据和目标张量的数据集。 14 | 15 | 通过沿着第一个维度索引两个张量来恢复每个样本。 16 | 17 | **参数:** 18 | 19 | - **data_tensor** (*Tensor*) - 包含样本数据 20 | - **target_tensor** (*Tensor*) - 包含样本目标(标签) 21 | 22 | ```python 23 | class torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=False, sampler=None, num_workers=0, collate_fn=, pin_memory=False, drop_last=False) 24 | ``` 25 | 数据加载器。组合数据集和采样器,并在数据集上提供单进程或多进程迭代器。 26 | 27 | **参数:** 28 | 29 | - **dataset** (*Dataset*) – 加载数据的数据集。 30 | - **batch_size** (*int*, optional) – 每个batch加载多少个样本(默认: 1)。 31 | - **shuffle** (*bool*, optional) – 设置为`True`时会在每个epoch重新打乱数据(默认: False). 32 | - **sampler** (*Sampler*, optional) – 定义从数据集中提取样本的策略。如果指定,则忽略`shuffle`参数。 33 | - **num_workers** (*int*, optional) – 用多少个子进程加载数据。0表示数据将在主进程中加载(默认: 0) 34 | - **collate_fn** (*callable*, optional) – 35 | - **pin_memory** (*bool*, optional) – 36 | - **drop_last** (*bool*, optional) – 如果数据集大小不能被batch size整除,则设置为True后可删除最后一个不完整的batch。如果设为False并且数据集的大小不能被batch size整除,则最后一个batch将更小。(默认: False) 37 | 38 | ```python 39 | class torch.utils.data.sampler.Sampler(data_source) 40 | ``` 41 | 所有采样器的基础类。 42 | 43 | 每个采样器子类必须提供一个`__iter__`方法,提供一种迭代数据集元素的索引的方法,以及返回迭代器长度的`__len__`方法。 44 | 45 | ```python 46 | class torch.utils.data.sampler.SequentialSampler(data_source) 47 | ``` 48 | 样本元素顺序排列,始终以相同的顺序。 49 | 50 | **参数:** 51 | - **data_source** (*Dataset*) – 采样的数据集。 52 | 53 | ```python 54 | class torch.utils.data.sampler.RandomSampler(data_source) 55 | ``` 56 | 样本元素随机,没有替换。 57 | 58 | **参数:** 59 | - **data_source** (*Dataset*) – 采样的数据集。 60 | 61 | 62 | ```python 63 | class torch.utils.data.sampler.SubsetRandomSampler(indices) 64 | ``` 65 | 样本元素从指定的索引列表中随机抽取,没有替换。 66 | 67 | **参数:** 68 | - **indices** (*list*) – 索引的列表 69 | 70 | ```python 71 | class torch.utils.data.sampler.WeightedRandomSampler(weights, num_samples, replacement=True) 72 | ``` 73 | 样本元素来自于[0,..,len(weights)-1],给定概率(weights)。 74 | 75 | **参数:** 76 | - **weights** (*list*) – 权重列表。没必要加起来为1 77 | - **num_samples** (*int*) – 抽样数量 78 | -------------------------------------------------------------------------------- /docs/package_references/torch-multiprocessing.md: -------------------------------------------------------------------------------- 1 | # torch.multiprocessing 2 | 封装了`multiprocessing`模块。用于在相同数据的不同进程中共享视图。 3 | 4 | 一旦张量或者存储被移动到共享单元(见`share_memory_()`),它可以不需要任何其他复制操作的发送到其他的进程中。 5 | 6 | 这个API与原始模型完全兼容,为了让张量通过队列或者其他机制共享,移动到内存中,我们可以 7 | 8 | 由原来的`import multiprocessing`改为`import torch.multiprocessing`。 9 | 10 | 由于API的相似性,我们没有记录这个软件包的大部分内容,我们建议您参考原始模块的非常好的文档。 11 | 12 | **`warning:`** 13 | 如果主要的进程突然退出(例如,因为输入信号),Python中的`multiprocessing`有时会不能清理他的子节点。 14 | 15 | 这是一个已知的警告,所以如果您在中断解释器后看到任何资源泄漏,这可能意味着这刚刚发生在您身上。 16 | 17 | ## Strategy management 18 | ```python 19 | torch.multiprocessing.get_all_sharing_strategies() 20 | ``` 21 | 返回一组由当前系统所支持的共享策略 22 | 23 | ```python 24 | torch.multiprocessing.get_sharing_strategy() 25 | ``` 26 | 返回当前策略共享CPU中的张量。 27 | 28 | ```python 29 | torch.multiprocessing.set_sharing_strategy(new_strategy) 30 | ``` 31 | 设置共享CPU张量的策略 32 | 33 | 参数: new_strategy(str)-被选中策略的名字。应当是`get_all_sharing_strategies()`中值当中的一个。 34 | 35 | ## Sharing CUDA tensors 36 | 共享CUDA张量进程只支持Python3,使用`spawn`或者`forkserver`开始方法。 37 | 38 | Python2中的`multiprocessing`只能使用`fork`创建子进程,并且不被CUDA支持。 39 | 40 | **`warning:`** 41 | CUDA API要求导出到其他进程的分配一直保持有效,只要它们被使用。 42 | 43 | 你应该小心,确保您共享的CUDA张量不要超出范围。 44 | 45 | 这不应该是共享模型参数的问题,但传递其他类型的数据应该小心。请注意,此限制不适用于共享CPU内存。 46 | 47 | ## Sharing strategies 48 | 本节简要概述了不同的共享策略如何工作。 49 | 50 | 请注意,它仅适用于CPU张量 - CUDA张量将始终使用CUDA API,因为它们是唯一的共享方式。 51 | 52 | ### File descriptor-`file_descripor` 53 | **`NOTE:`** 54 | 这是默认策略(除了不支持的MacOS和OS X)。 55 | 56 | 此策略将使用文件描述符作为共享内存句柄。当存储被移动到共享内存中,一个由`shm_open`获得的文件描述符被缓存, 57 | 58 | 并且当它将被发送到其他进程时,文件描述符将被传送(例如通过UNIX套接字)。 59 | 60 | 接收者也将缓存文件描述符,并且`mmap`它,以获得对存储数据的共享视图。 61 | 62 | 请注意,如果要共享很多张量,则此策略将保留大量文件描述符。 63 | 64 | 如果你的系统对打开的文件描述符数量有限制,并且无法提高,你应该使用`file_system`策略。 65 | 66 | ### File system -file_system 67 | 这个策略将提供文件名称给`shm_open`去定义共享内存区域。 68 | 69 | 该策略不需要缓存从其获得的文件描述符的优点,但是容易发生共享内存泄漏。 70 | 71 | 该文件创建后不能被删除,因为其他进程需要访问它以打开其视图。 72 | 73 | 如果进程崩溃或死机,并且不能调用存储析构函数,则文件将保留在系统中。 74 | 75 | 这是非常严重的,因为它们在系统重新启动之前不断使用内存,或者手动释放它们。 76 | 77 | 为了记录共享内存文件泄露数量,`torch.multiprocessing`将产生一个守护进程叫做`torch_shm_manager` 78 | 79 | 将自己与当前进程组隔离,并且将跟踪所有共享内存分配。一旦连接到它的所有进程退出, 80 | 81 | 它将等待一会儿,以确保不会有新的连接,并且将遍历该组分配的所有共享内存文件。 82 | 83 | 如果发现它们中的任何一个仍然存在,它们将被释放。我们已经测试了这种方法,并且它已被证明对于各种故障都是稳健的。 84 | 85 | 如果你的系统有足够高的限制,并且`file_descriptor`是被支持的策略,我们不建议切换到这个。 86 | -------------------------------------------------------------------------------- /docs/notes/multiprocessing.md: -------------------------------------------------------------------------------- 1 | # 多进程最佳实践 2 | `torch.multiprocessing`是Python`multiprocessing`的替代品。它支持完全相同的操作,但扩展了它以便通过`multiprocessing.Queue`发送的所有张量将其数据移动到共享内存中,并且只会向其他进程发送一个句柄。 3 | 4 | > **Note** 5 | > 6 | > 当`Variable`发送到另一个进程时,`Variable.data`和`Variable.grad.data`都将被共享。 7 | 8 | 这允许实现各种训练方法,如Hogwild,A3C或需要异步操作的任何其他方法。 9 | 10 | ## 共享CUDA张量 11 | 仅在Python 3中使用`spawn`或`forkserver`启动方法才支持在进程之间共享CUDA张量。Python 2中的`multiprocessing`只能使用`fork`创建子进程,并且不被CUDA运行时所支持。 12 | 13 | >**Warning** 14 | > 15 | >CUDA API要求导出到其他进程的分配,只要它们被使用就要一直保持有效。您应该小心,确保您共享的CUDA张量只要有必要就不要超出范围。这不是共享模型参数的问题,但传递其他类型的数据应该小心。注意,此限制不适用于共享CPU内存。 16 | 17 | 参考:[使用 nn.DataParallel 替代 multiprocessing](cuda.md) 18 | 19 | ## 最佳实践和提示 20 | ### 避免和抵制死锁 21 | 当一个新进程被产生时,有很多事情可能会出错,最常见的死锁原因是后台线程。如果有任何线程持有锁或导入模块,并且`fork`被调用,则子进程很可能处于损坏的状态,并以不同的方式死锁或失败。注意,即使您没有,Python内置的库也可能会这样做 —— 不需要看得比`multiprocessing`更远。`multiprocessing.Queue`实际上是一个非常复杂的类,它产生用于序列化,发送和接收对象的多个线程,它们也可能引起上述问题。如果您发现自己处于这种情况,请尝试使用`multiprocessing.queues.SimpleQueue`,这不会使用任何其他线程。 22 | 23 | 我们正在竭尽全力把它设计得更简单,并确保这些死锁不会发生,但有些事情无法控制。如果有任何问题您无法一时无法解决,请尝试在论坛上提出,我们将看看是否可以解决问题。 24 | 25 | ### 重用经过队列的缓冲区 26 | 记住每次将`Tensor`放入`multiprocessing.Queue`时,必须将其移动到共享内存中。如果它已经被共享,它是一个无效的操作,否则会产生一个额外的内存副本,这会减缓整个进程。即使你有一个进程池来发送数据到一个进程,使它返回缓冲区 —— 这几乎是免费的,并且允许你在发送下一个batch时避免产生副本。 27 | 28 | ### 异步多进程训练(例如Hogwild) 29 | 使用`torch.multiprocessing`,可以异步地训练模型,参数可以一直共享,也可以定期同步。在第一种情况下,我们建议发送整个模型对象,而在后者中,我们建议只发送`state_dict()`。 30 | 31 | 我们建议使用`multiprocessing.Queue`来在进程之间传递各种PyTorch对象。例如, 当使用fork启动方法时,可能会继承共享内存中的张量和存储器,但这是非常容易出错的,应谨慎使用,而且只能由高级用户使用。队列虽然有时是一个较不优雅的解决方案,但基本上能在所有情况下正常工作。 32 | 33 | > **Warning** 34 | > 你应该注意有关全局语句,它们没有被`if __name__ == '__main__'`保护。如果使用与`fork`不同的启动方法,则它们将在所有子进程中执行。 35 | 36 | #### Hogwild 37 | 在[examples repository](https://github.com/pytorch/examples/tree/master/mnist_hogwild)中可以找到具体的Hogwild实现,可以展示代码的整体结构。下面也有一个小例子: 38 | ```Python 39 | import torch.multiprocessing as mp 40 | from model import MyModel 41 | 42 | def train(model): 43 | # Construct data_loader, optimizer, etc. 44 | for data, labels in data_loader: 45 | optimizer.zero_grad() 46 | loss_fn(model(data), labels).backward() 47 | optimizer.step() # This will update the shared parameters 48 | 49 | if __name__ == '__main__': 50 | num_processes = 4 51 | model = MyModel() 52 | # NOTE: this is required for the ``fork`` method to work 53 | model.share_memory() 54 | processes = [] 55 | for rank in range(num_processes): 56 | p = mp.Process(target=train, args=(model,)) 57 | p.start() 58 | processes.append(p) 59 | for p in processes: 60 | p.join() 61 | ``` 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pytorch-cn 2 | 3 | --- 4 | 5 | 本项目由[awfssv](https://github.com/awfssv), [ycszen](https://github.com/ycszen), [KeithYin](https://github.com/KeithYin), [kophy](https://github.com/kophy), [swordspoet](https://github.com/swordspoet), [dyl745001196](https://github.com/dyl745001196), [koshinryuu](https://github.com/koshinryuu), [tfygg](https://github.com/tfygg), [weigp](https://github.com/weigq), [ZijunDeng](https://github.com/ZijunDeng), [yichuan9527](https://github.com/yichuan9527)等PyTorch爱好者发起,并已获得PyTorch官方授权。我们目的是建立[PyTorch](http://pytorch.org/docs/)的中文文档,并力所能及地提供更多的帮助和建议。 6 | 7 | 本项目网址为[pytorch-cn](http://pytorch-cn.readthedocs.io/zh/latest/),文档翻译QQ群:628478868 8 | 9 | 如果你在使用pytorch和pytorch-cn的过程中有任何问题,欢迎在issue中讨论,可能你的问题也是别人的问题。 10 | 11 | ## 翻译进度 12 | 现在正在进行审阅任务(大家赶紧认领吧~) 13 | 第一个名字代表翻译人,第二个代表审阅人 14 | ### Notes 15 | - [x] Autograd mechanics (*ycszen*)(DL-ljw) 16 | - [x] CUDA semantics (*ycszen*) 17 | - [x] Extending PyTorch (*KeithYin*) 18 | - [x] Multiprocessing best practices (*ycszen*) 19 | - [x] Serialization semantics (*ycszen*) 20 | 21 | ### Package Reference 22 | - [x] torch(*koshinryuu*)(飞彦) 23 | - [x] torch.Tensor(*weigp*)(飞彦) 24 | - [x] torch.Storage(*kophy*) 25 | - [ ] **torch.nn** 26 | - [x] Parameters(*KeithYin*) 27 | - [x] Containers(*KeithYin*) 28 | - [x] Convolution Layers(*yichuan9527*) 29 | - [x] Pooling Layers(*yichuan9527*) 30 | - [x] Non-linear Activations(*swordspoet*) 31 | - [x] Normalization layers(*XavierLin*) 32 | - [x] Recurrent layers(*KeithYin*)(Mosout) 33 | - [x] Linear layers( )(Mosout) 34 | - [x] Dropout layers( )(Mosout) 35 | - [x] Sparse layers(Mosout) 36 | - [x] Distance functions 37 | - [x] Loss functions(*KeithYin*)(DL-ljw) 38 | - [x] Vision layers(*KeithYin*) 39 | - [x] Multi-GPU layers(*KeithYin*) 40 | - [x] Utilities(*KeithYin*) 41 | - [x] torch.nn.functional 42 | - [x] Convolution functions(*ycszen*)(铁血丹心) 43 | - [x] Pooling functions(*ycszen*)(铁血丹心) 44 | - [x] Non-linear activations functions(*ycszen*) 45 | - [x] Normalization functions(*ycszen*) 46 | - [x] Linear functions(*dyl745001196*) 47 | - [x] Dropout functions(*dyl745001196*) 48 | - [x] Distance functions(*dyl745001196*) 49 | - [x] Loss functions(*tfygg*)(DL-ljw) 50 | - [x] Vision functions(*KeithYin*) 51 | - [x] torch.nn.init(*kophy*)(luc) 52 | - [x] torch.optim(*ZijunDeng*)(祁杰) 53 | - [x] torch.autograd(*KeithYin*)(祁杰) 54 | - [x] torch.multiprocessing(*songbo.han*) 55 | - [x] torch.legacy(*ycszen*) 56 | - [x] torch.cuda(*ycszen*) 57 | - [x] torch.utils.ffi(*ycszen*) 58 | - [x] torch.utils.data(*ycszen*) 59 | - [x] torch.utils.model_zoo(*ycszen*) 60 | 61 | ### torchvision Reference 62 | - [x] torchvision (*KeithYin*) 63 | - [x] torchvision.datasets (*KeithYin*)(loop) 64 | - [x] torchvision.models (*KeithYin*) 65 | - [x] torchvision.transforms (*KeithYin*)(loop) 66 | - [x] torchvision.utils (*KeithYin*) 67 | -------------------------------------------------------------------------------- /docs/torchvision/torchvision-transform.md: -------------------------------------------------------------------------------- 1 | # pytorch torchvision transform 2 | 3 | ## 对PIL.Image进行变换 4 | ### class torchvision.transforms.Compose(transforms) 5 | 将多个`transform`组合起来使用。 6 | 7 | `transforms`: 由`transform`构成的列表. 8 | 例子: 9 | ```python 10 | transforms.Compose([ 11 | transforms.CenterCrop(10), 12 | transforms.ToTensor(), 13 | ]) 14 | ``` 15 | 16 | 17 | ### class torchvision.transforms.Scale(size, interpolation=2) 18 | 19 | 将输入的`PIL.Image`重新改变大小成给定的`size`,`size`是最小边的边长。举个例子,如果原图的`height>width`,那么改变大小后的图片大小是`(size*height/width, size)`。 20 | **用例:** 21 | ```python 22 | from torchvision import transforms 23 | from PIL import Image 24 | crop = transforms.Scale(12) 25 | img = Image.open('test.jpg') 26 | 27 | print(type(img)) 28 | print(img.size) 29 | 30 | croped_img=crop(img) 31 | print(type(croped_img)) 32 | print(croped_img.size) 33 | ``` 34 | ``` 35 | 36 | (10, 10) 37 | 38 | (12, 12) 39 | ``` 40 | 41 | ### class torchvision.transforms.CenterCrop(size) 42 | 将给定的`PIL.Image`进行中心切割,得到给定的`size`,`size`可以是`tuple`,`(target_height, target_width)`。`size`也可以是一个`Integer`,在这种情况下,切出来的图片的形状是正方形。 43 | 44 | ### class torchvision.transforms.RandomCrop(size, padding=0) 45 | 切割中心点的位置随机选取。`size`可以是`tuple`也可以是`Integer`。 46 | 47 | ### class torchvision.transforms.RandomHorizontalFlip 48 | 随机水平翻转给定的`PIL.Image`,概率为`0.5`。即:一半的概率翻转,一半的概率不翻转。 49 | 50 | ### class torchvision.transforms.RandomSizedCrop(size, interpolation=2) 51 | 先将给定的`PIL.Image`随机切,然后再`resize`成给定的`size`大小。 52 | ### class torchvision.transforms.Pad(padding, fill=0) 53 | 将给定的`PIL.Image`的所有边用给定的`pad value`填充。 54 | `padding:`要填充多少像素 55 | `fill:`用什么值填充 56 | 例子: 57 | ```python 58 | from torchvision import transforms 59 | from PIL import Image 60 | padding_img = transforms.Pad(padding=10, fill=0) 61 | img = Image.open('test.jpg') 62 | 63 | print(type(img)) 64 | print(img.size) 65 | 66 | padded_img=padding(img) 67 | print(type(padded_img)) 68 | print(padded_img.size) 69 | ``` 70 | ``` 71 | 72 | (10, 10) 73 | 74 | (30, 30) #由于上下左右都要填充10个像素,所以填充后的size是(30,30) 75 | ``` 76 | 77 | ## 对Tensor进行变换 78 | ### class torchvision.transforms.Normalize(mean, std) 79 | 给定均值:`(R,G,B)` 方差:`(R,G,B)`,将会把`Tensor`正则化。即:`Normalized_image=(image-mean)/std`。 80 | 81 | ## Conversion Transforms 82 | 83 | ### class torchvision.transforms.ToTensor 84 | 把一个取值范围是`[0,255]`的`PIL.Image`或者`shape`为`(H,W,C)`的`numpy.ndarray`,转换成形状为`[C,H,W]`,取值范围是`[0,1.0]`的`torch.FloadTensor` 85 | ```python 86 | data = np.random.randint(0, 255, size=300) 87 | img = data.reshape(10,10,3) 88 | print(img.shape) 89 | img_tensor = transforms.ToTensor()(img) # 转换成tensor 90 | print(img_tensor) 91 | ``` 92 | 93 | ### class torchvision.transforms.ToPILImage 94 | 将`shape`为`(C,H,W)`的`Tensor`或`shape`为`(H,W,C)`的`numpy.ndarray`转换成`PIL.Image`,值不变。 95 | 96 | ## 通用变换 97 | ### class torchvision.transforms.Lambda(lambd) 98 | 使用`lambd`作为转换器。 99 | -------------------------------------------------------------------------------- /docs/notes/autograd.md: -------------------------------------------------------------------------------- 1 | # 自动求导机制 2 | 3 | 本说明将概述Autograd如何工作并记录操作。了解这些并不是绝对必要的,但我们建议您熟悉它,因为它将帮助您编写更高效,更简洁的程序,并可帮助您进行调试。 4 | 5 | ## 从后向中排除子图 6 | 每个变量都有两个标志:`requires_grad`和`volatile`。它们都允许从梯度计算中精细地排除子图,并可以提高效率。 7 | 8 | ### `requires_grad` 9 | 如果有一个单一的输入操作需要梯度,它的输出也需要梯度。相反,只有所有输入都不需要梯度,输出才不需要。如果其中所有的变量都不需要梯度进行,后向计算不会在子图中执行。 10 | 11 | ```python 12 | >>> x = Variable(torch.randn(5, 5)) 13 | >>> y = Variable(torch.randn(5, 5)) 14 | >>> z = Variable(torch.randn(5, 5), requires_grad=True) 15 | >>> a = x + y 16 | >>> a.requires_grad 17 | False 18 | >>> b = a + z 19 | >>> b.requires_grad 20 | True 21 | ``` 22 | 这个标志特别有用,当您想要冻结部分模型时,或者您事先知道不会使用某些参数的梯度。例如,如果要对预先训练的CNN进行优化,只要切换冻结模型中的`requires_grad`标志就足够了,直到计算到最后一层才会保存中间缓冲区,其中的仿射变换将使用需要梯度的权重并且网络的输出也将需要它们。 23 | 24 | ```python 25 | model = torchvision.models.resnet18(pretrained=True) 26 | for param in model.parameters(): 27 | param.requires_grad = False 28 | # Replace the last fully-connected layer 29 | # Parameters of newly constructed modules have requires_grad=True by default 30 | model.fc = nn.Linear(512, 100) 31 | 32 | # Optimize only the classifier 33 | optimizer = optim.SGD(model.fc.parameters(), lr=1e-2, momentum=0.9) 34 | ``` 35 | 36 | ### `volatile` 37 | 纯粹的inference模式下推荐使用`volatile`,当你确定你甚至不会调用`.backward()`时。它比任何其他自动求导的设置更有效——它将使用绝对最小的内存来评估模型。`volatile`也决定了`require_grad is False`。 38 | 39 | `volatile`不同于`require_grad`的传递。如果一个操作甚至只有有一个`volatile`的输入,它的输出也将是`volatile`。`Volatility`比“不需要梯度”更容易传递——只需要一个`volatile`的输入即可得到一个`volatile`的输出,相对的,需要所有的输入“不需要梯度”才能得到不需要梯度的输出。使用volatile标志,您不需要更改模型参数的任何设置来用于inference。创建一个`volatile`的输入就够了,这将保证不会保存中间状态。 40 | ```python 41 | >>> regular_input = Variable(torch.randn(5, 5)) 42 | >>> volatile_input = Variable(torch.randn(5, 5), volatile=True) 43 | >>> model = torchvision.models.resnet18(pretrained=True) 44 | >>> model(regular_input).requires_grad 45 | True 46 | >>> model(volatile_input).requires_grad 47 | False 48 | >>> model(volatile_input).volatile 49 | True 50 | >>> model(volatile_input).creator is None 51 | True 52 | ``` 53 | 54 | ## 自动求导如何编码历史信息 55 | 每个变量都有一个`.creator`属性,它指向把它作为输出的函数。这是一个由`Function`对象作为节点组成的有向无环图(DAG)的入口点,它们之间的引用就是图的边。每次执行一个操作时,一个表示它的新`Function`就被实例化,它的`forward()`方法被调用,并且它输出的`Variable`的创建者被设置为这个`Function`。然后,通过跟踪从任何变量到叶节点的路径,可以重建创建数据的操作序列,并自动计算梯度。 56 | 57 | 需要注意的一点是,整个图在每次迭代时都是从头开始重新创建的,这就允许使用任意的Python控制流语句,这样可以在每次迭代时改变图的整体形状和大小。在启动训练之前不必对所有可能的路径进行编码—— what you run is what you differentiate. 58 | 59 | ## Variable上的In-place操作 60 | 在自动求导中支持in-place操作是一件很困难的事情,我们在大多数情况下都不鼓励使用它们。Autograd的缓冲区释放和重用非常高效,并且很少场合下in-place操作能实际上明显降低内存的使用量。除非您在内存压力很大的情况下,否则您可能永远不需要使用它们。 61 | 62 | 限制in-place操作适用性主要有两个原因: 63 | 64 | 1.覆盖梯度计算所需的值。这就是为什么变量不支持`log_`。它的梯度公式需要原始输入,而虽然通过计算反向操作可以重新创建它,但在数值上是不稳定的,并且需要额外的工作,这往往会与使用这些功能的目的相悖。 65 | 66 | 2.每个in-place操作实际上需要实现重写计算图。不合适的版本只需分配新对象并保留对旧图的引用,而in-place操作则需要将所有输入的`creator`更改为表示此操作的`Function`。这就比较棘手,特别是如果有许多变量引用相同的存储(例如通过索引或转置创建的),并且如果被修改输入的存储被任何其他`Variable`引用,则in-place函数实际上会抛出错误。 67 | 68 | ## In-place正确性检查 69 | 每个变量保留有version counter,它每次都会递增,当在任何操作中被使用时。当`Function`保存任何用于后向的tensor时,还会保存其包含变量的version counter。一旦访问`self.saved_tensors`,它将被检查,如果它大于保存的值,则会引起错误。 70 | -------------------------------------------------------------------------------- /docs/torchvision/torchvision-models.md: -------------------------------------------------------------------------------- 1 | # torchvision.models 2 | `torchvision.models`模块的 子模块中包含以下模型结构。 3 | 4 | - AlexNet 5 | - VGG 6 | - ResNet 7 | - SqueezeNet 8 | - DenseNet 9 | You can construct a model with random weights by calling its constructor: 10 | 11 | 你可以使用随机初始化的权重来创建这些模型。 12 | ```python 13 | import torchvision.models as models 14 | resnet18 = models.resnet18() 15 | alexnet = models.alexnet() 16 | squeezenet = models.squeezenet1_0() 17 | densenet = models.densenet_161() 18 | ``` 19 | We provide pre-trained models for the ResNet variants and AlexNet, using the PyTorch torch.utils.model_zoo. These can constructed by passing pretrained=True: 20 | 对于`ResNet variants`和`AlexNet`,我们也提供了预训练(`pre-trained`)的模型。 21 | ```python 22 | import torchvision.models as models 23 | #pretrained=True就可以使用预训练的模型 24 | resnet18 = models.resnet18(pretrained=True) 25 | alexnet = models.alexnet(pretrained=True) 26 | ``` 27 | ImageNet 1-crop error rates (224x224) 28 | 29 | |Network |Top-1 error |Top-5 error| 30 | |------|------|------| 31 | |ResNet-18| 30.24| 10.92| 32 | |ResNet-34| 26.70| 8.58| 33 | |ResNet-50 |23.85 |7.13| 34 | |ResNet-101| 22.63| 6.44| 35 | |ResNet-152 |21.69 |5.94| 36 | |Inception v3| 22.55| 6.44| 37 | |AlexNet |43.45 |20.91| 38 | |VGG-11| 30.98| 11.37| 39 | |VGG-13 |30.07 |10.75| 40 | |VGG-16| 28.41| 9.62| 41 | |VGG-19 |27.62 |9.12| 42 | |SqueezeNet 1.0| 41.90| 19.58| 43 | |SqueezeNet 1.1 |41.81 |19.38| 44 | |Densenet-121| 25.35| 7.83| 45 | |Densenet-169 |24.00 |7.00| 46 | |Densenet-201| 22.80| 6.43| 47 | |Densenet-161| 22.35 |6.20| 48 | 49 | ## torchvision.models.alexnet(pretrained=False, ** kwargs) 50 | `AlexNet` 模型结构 [paper地址](https://arxiv.org/abs/1404.5997) 51 | 52 | - pretrained (bool) – `True`, 返回在ImageNet上训练好的模型。 53 | 54 | ## torchvision.models.resnet18(pretrained=False, ** kwargs) 55 | 构建一个`resnet18`模型 56 | 57 | - pretrained (bool) – `True`, 返回在ImageNet上训练好的模型。 58 | 59 | ## torchvision.models.resnet34(pretrained=False, ** kwargs) 60 | 构建一个`ResNet-34` 模型. 61 | 62 | Parameters: pretrained (bool) – `True`, 返回在ImageNet上训练好的模型。 63 | 64 | ## torchvision.models.resnet50(pretrained=False, ** kwargs) 65 | 构建一个`ResNet-50`模型 66 | 67 | - pretrained (bool) – `True`, 返回在ImageNet上训练好的模型。 68 | 69 | ## torchvision.models.resnet101(pretrained=False, ** kwargs) 70 | Constructs a ResNet-101 model. 71 | 72 | - pretrained (bool) – `True`, 返回在ImageNet上训练好的模型。 73 | 74 | ## torchvision.models.resnet152(pretrained=False, ** kwargs) 75 | Constructs a ResNet-152 model. 76 | 77 | - pretrained (bool) – `True`, 返回在ImageNet上训练好的模型。 78 | 79 | ## torchvision.models.vgg11(pretrained=False, ** kwargs) 80 | VGG 11-layer model (configuration “A”) 81 | - pretrained (bool) – `True`, 返回在ImageNet上训练好的模型。 82 | 83 | ## torchvision.models.vgg11_bn(** kwargs) 84 | VGG 11-layer model (configuration “A”) with batch normalization 85 | 86 | ## torchvision.models.vgg13(pretrained=False, ** kwargs) 87 | VGG 13-layer model (configuration “B”) 88 | 89 | - pretrained (bool) – `True`, 返回在ImageNet上训练好的模型。 90 | 91 | ## torchvision.models.vgg13_bn(** kwargs) 92 | VGG 13-layer model (configuration “B”) with batch normalization 93 | 94 | ## torchvision.models.vgg16(pretrained=False, ** kwargs) 95 | VGG 16-layer model (configuration “D”) 96 | 97 | Parameters: pretrained (bool) – If True, returns a model pre-trained on ImageNet 98 | ## torchvision.models.vgg16_bn(** kwargs) 99 | VGG 16-layer model (configuration “D”) with batch normalization 100 | 101 | ## torchvision.models.vgg19(pretrained=False, ** kwargs) 102 | VGG 19-layer model (configuration “E”) 103 | 104 | - pretrained (bool) – `True`, 返回在ImageNet上训练好的模型。 105 | ## torchvision.models.vgg19_bn(** kwargs) 106 | VGG 19-layer model (configuration ‘E’) with batch normalization 107 | -------------------------------------------------------------------------------- /docs/torchvision/torchvision-datasets.md: -------------------------------------------------------------------------------- 1 | # torchvision.datasets 2 | `torchvision.datasets`中包含了以下数据集 3 | 4 | - MNIST 5 | - COCO(用于图像标注和目标检测)(Captioning and Detection) 6 | - LSUN Classification 7 | - ImageFolder 8 | - Imagenet-12 9 | - CIFAR10 and CIFAR100 10 | - STL10 11 | 12 | `Datasets` 拥有以下`API`: 13 | 14 | `__getitem__` 15 | `__len__` 16 | 17 | 由于以上`Datasets`都是 `torch.utils.data.Dataset`的子类,所以,他们也可以通过`torch.utils.data.DataLoader`使用多线程(python的多进程)。 18 | 19 | 举例说明: 20 | `torch.utils.data.DataLoader(coco_cap, batch_size=args.batchSize, shuffle=True, num_workers=args.nThreads)` 21 | 22 | 在构造函数中,不同的数据集直接的构造函数会有些许不同,但是他们共同拥有 `keyword` 参数。 23 | In the constructor, each dataset has a slightly different API as needed, but they all take the keyword args: 24 | - `transform`: 一个函数,原始图片作为输入,返回一个转换后的图片。(详情请看下面关于`torchvision-tranform`的部分) 25 | 26 | - `target_transform` - 一个函数,输入为`target`,输出对其的转换。例子,输入的是图片标注的`string`,输出为`word`的索引。 27 | ## MNIST 28 | ```python 29 | dset.MNIST(root, train=True, transform=None, target_transform=None, download=False) 30 | ``` 31 | 参数说明: 32 | - root : `processed/training.pt` 和 `processed/test.pt` 的主目录 33 | - train : `True` = 训练集, `False` = 测试集 34 | - download : `True` = 从互联网上下载数据集,并把数据集放在`root`目录下. 如果数据集之前下载过,将处理过的数据(minist.py中有相关函数)放在`processed`文件夹下。 35 | 36 | ## COCO 37 | 需要安装[COCO API](https://github.com/pdollar/coco/tree/master/PythonAPI) 38 | 39 | ### 图像标注: 40 | ```python 41 | dset.CocoCaptions(root="dir where images are", annFile="json annotation file", [transform, target_transform]) 42 | ``` 43 | 例子: 44 | ```python 45 | import torchvision.datasets as dset 46 | import torchvision.transforms as transforms 47 | cap = dset.CocoCaptions(root = 'dir where images are', 48 | annFile = 'json annotation file', 49 | transform=transforms.ToTensor()) 50 | 51 | print('Number of samples: ', len(cap)) 52 | img, target = cap[3] # load 4th sample 53 | 54 | print("Image Size: ", img.size()) 55 | print(target) 56 | ``` 57 | 输出: 58 | ``` 59 | Number of samples: 82783 60 | Image Size: (3L, 427L, 640L) 61 | [u'A plane emitting smoke stream flying over a mountain.', 62 | u'A plane darts across a bright blue sky behind a mountain covered in snow', 63 | u'A plane leaves a contrail above the snowy mountain top.', 64 | u'A mountain that has a plane flying overheard in the distance.', 65 | u'A mountain view with a plume of smoke in the background'] 66 | ``` 67 | ### 检测: 68 | ``` 69 | dset.CocoDetection(root="dir where images are", annFile="json annotation file", [transform, target_transform]) 70 | ``` 71 | ## LSUN 72 | ```python 73 | dset.LSUN(db_path, classes='train', [transform, target_transform]) 74 | ``` 75 | 参数说明: 76 | - db_path = 数据集文件的根目录 77 | - classes = ‘train’ (所有类别, 训练集), ‘val’ (所有类别, 验证集), ‘test’ (所有类别, 测试集) 78 | [‘bedroom\_train’, ‘church\_train’, …] : a list of categories to load 79 | ## ImageFolder 80 | 一个通用的数据加载器,数据集中的数据以以下方式组织 81 | ``` 82 | root/dog/xxx.png 83 | root/dog/xxy.png 84 | root/dog/xxz.png 85 | 86 | root/cat/123.png 87 | root/cat/nsdf3.png 88 | root/cat/asd932_.png 89 | ``` 90 | ```python 91 | dset.ImageFolder(root="root folder path", [transform, target_transform]) 92 | ``` 93 | 他有以下成员变量: 94 | 95 | - self.classes - 用一个list保存 类名 96 | - self.class_to_idx - 类名对应的 索引 97 | - self.imgs - 保存(img-path, class) tuple的list 98 | 99 | ## Imagenet-12 100 | This is simply implemented with an ImageFolder dataset. 101 | 102 | The data is preprocessed [as described here](https://github.com/facebook/fb.resnet.torch/blob/master/INSTALL.md#download-the-imagenet-dataset) 103 | 104 | [Here is an example](https://github.com/pytorch/examples/blob/27e2a46c1d1505324032b1d94fc6ce24d5b67e97/imagenet/main.py#L48-L62) 105 | 106 | ## CIFAR 107 | ```python 108 | dset.CIFAR10(root, train=True, transform=None, target_transform=None, download=False) 109 | 110 | dset.CIFAR100(root, train=True, transform=None, target_transform=None, download=False) 111 | ``` 112 | 参数说明: 113 | - root : `cifar-10-batches-py` 的根目录 114 | - train : `True` = 训练集, `False` = 测试集 115 | - download : `True` = 从互联上下载数据,并将其放在`root`目录下。如果数据集已经下载,什么都不干。 116 | ## STL10 117 | ```python 118 | dset.STL10(root, split='train', transform=None, target_transform=None, download=False) 119 | ``` 120 | 参数说明: 121 | - root : `stl10_binary`的根目录 122 | - split : 'train' = 训练集, 'test' = 测试集, 'unlabeled' = 无标签数据集, 'train+unlabeled' = 训练 + 无标签数据集 (没有标签的标记为-1) 123 | - download : `True` = 从互联上下载数据,并将其放在`root`目录下。如果数据集已经下载,什么都不干。 124 | -------------------------------------------------------------------------------- /docs/package_references/torch-cuda.md: -------------------------------------------------------------------------------- 1 | # torch.cuda 2 | 该包增加了对CUDA张量类型的支持,实现了与CPU张量相同的功能,但使用GPU进行计算。 3 | 4 | 它是懒惰的初始化,所以你可以随时导入它,并使用`is_available()`来确定系统是否支持CUDA。 5 | 6 | [CUDA语义](../notes/cuda.md)中有关于使用CUDA的更多细节。 7 | 8 | ```python 9 | torch.cuda.current_blas_handle() 10 | ``` 11 | 返回cublasHandle_t指针,指向当前cuBLAS句柄 12 | 13 | ```python 14 | torch.cuda.current_device() 15 | ``` 16 | 返回当前所选设备的索引。 17 | 18 | ```python 19 | torch.cuda.current_stream() 20 | ``` 21 | 返回一个当前所选的`Stream` 22 | 23 | ```python 24 | class torch.cuda.device(idx) 25 | ``` 26 | 上下文管理器,可以更改所选设备。 27 | 28 | **参数:** 29 | - **idx** (*int*) – 设备索引选择。如果这个参数是负的,则是无效操作。 30 | 31 | ```python 32 | torch.cuda.device_count() 33 | ``` 34 | 返回可得到的GPU数量。 35 | 36 | ```python 37 | class torch.cuda.device_of(obj) 38 | ``` 39 | 40 | 将当前设备更改为给定对象的上下文管理器。 41 | 42 | 可以使用张量和存储作为参数。如果给定的对象不是在GPU上分配的,这是一个无效操作。 43 | 44 | **参数:** 45 | - **obj** (*Tensor* or *Storage*) – 在选定设备上分配的对象。 46 | 47 | ```python 48 | torch.cuda.is_available() 49 | ``` 50 | 返回一个bool值,指示CUDA当前是否可用。 51 | 52 | ```python 53 | torch.cuda.set_device(device) 54 | ``` 55 | 设置当前设备。 56 | 57 | 不鼓励使用此函数来设置。在大多数情况下,最好使用`CUDA_VISIBLE_DEVICES`环境变量。 58 | 59 | **参数:** 60 | - **device** (*int*) – 所选设备。如果此参数为负,则此函数是无效操作。 61 | 62 | ```python 63 | torch.cuda.stream(stream) 64 | ``` 65 | 选择给定流的上下文管理器。 66 | 67 | 在其上下文中排队的所有CUDA核心将在所选流上入队。 68 | 69 | **参数:** 70 | - **stream** (*Stream*) – 所选流。如果是`None`,则这个管理器是无效的。 71 | 72 | ```python 73 | torch.cuda.synchronize() 74 | ``` 75 | 等待当前设备上所有流中的所有核心完成。 76 | 77 | ## 交流集 78 | ```python 79 | torch.cuda.comm.broadcast(tensor, devices) 80 | ``` 81 | 向一些GPU广播张量。 82 | 83 | **参数:** 84 | - **tensor** (*Tensor*) – 将要广播的张量 85 | - **devices** (*Iterable*) – 一个可以广播的设备的迭代。注意,它的形式应该像(src,dst1,dst2,...),其第一个元素是广播来源的设备。 86 | 87 | **返回:** 一个包含张量副本的元组,放置在与设备的索引相对应的设备上。 88 | 89 | ```python 90 | torch.cuda.comm.reduce_add(inputs, destination=None) 91 | ``` 92 | 将来自多个GPU的张量相加。 93 | 94 | 所有输入应具有匹配的形状。 95 | 96 | **参数:** 97 | - **inputs** (*Iterable[Tensor]*) – 要相加张量的迭代 98 | - **destination** (*int*, optional) – 将放置输出的设备(默认值:当前设备)。 99 | 100 | **返回:** 一个包含放置在`destination`设备上的所有输入的元素总和的张量。 101 | 102 | ```python 103 | torch.cuda.comm.scatter(tensor, devices, chunk_sizes=None, dim=0, streams=None) 104 | ``` 105 | 打散横跨多个GPU的张量。 106 | 107 | **参数:** 108 | - **tensor** (*Tensor*) – 要分散的张量 109 | - **devices** (*Iterable[int]*) – int的迭代,指定哪些设备应该分散张量。 110 | - **chunk_sizes** (*Iterable[int]*, optional) – 要放置在每个设备上的块大小。它应该匹配`devices`的长度并且总和为`tensor.size(dim)`。 如果没有指定,张量将被分成相等的块。 111 | - **dim** (*int*, optional) – 沿着这个维度来chunk张量 112 | 113 | **返回:** 包含`tensor`块的元组,分布在给定的`devices`上。 114 | 115 | ```python 116 | torch.cuda.comm.gather(tensors, dim=0, destination=None) 117 | ``` 118 | 从多个GPU收集张量。 119 | 120 | 张量尺寸在不同于`dim`的所有维度上都应该匹配。 121 | 122 | **参数:** 123 | - **tensors** (*Iterable[Tensor]*) – 要收集的张量的迭代。 124 | - **dim** (*int*) – 沿着此维度张量将被连接。 125 | - **destination** (*int*, optional) – 输出设备(-1表示CPU,默认值:当前设备)。 126 | 127 | **返回:** 一个张量位于`destination`设备上,这是沿着`dim`连接`tensors`的结果。 128 | 129 | ## 流和事件 130 | ```python 131 | class torch.cuda.Stream 132 | ``` 133 | CUDA流的包装。 134 | 135 | **参数:** 136 | - **device** (*int*, optional) – 分配流的设备。 137 | - **priority** (*int*, optional) – 流的优先级。较低的数字代表较高的优先级。 138 | 139 | > query() 140 | 141 | 检查所有提交的工作是否已经完成。 142 | 143 | **返回:** 一个布尔值,表示此流中的所有核心是否完成。 144 | 145 | > record_event(event=None) 146 | 147 | 记录一个事件。 148 | 149 | **参数:** **event** (*Event*, optional) – 要记录的事件。如果没有给出,将分配一个新的。 150 | **返回:** 记录的事件。 151 | 152 | > synchronize() 153 | 154 | 等待此流中的所有核心完成。 155 | 156 | > wait_event(event) 157 | 158 | 将所有未来的工作提交到流等待事件。 159 | 160 | **参数:** **event** (*Event*) – 等待的事件 161 | 162 | > wait_stream(stream) 163 | 164 | 与另一个流同步。 165 | 166 | 提交到此流的所有未来工作将等待直到所有核心在调用完成时提交给给定的流。 167 | 168 | ```python 169 | class torch.cuda.Event(enable_timing=False, blocking=False, interprocess=False, _handle=None) 170 | ``` 171 | 172 | CUDA事件的包装。 173 | 174 | **参数:** 175 | - **enable_timing** (*bool*) – 指示事件是否应该测量时间(默认值:False) 176 | - **blocking** (*bool*) – 如果为true,`wait()`将被阻塞(默认值:False) 177 | - **interprocess** (*bool*) – 如果为true,则可以在进程之间共享事件(默认值:False) 178 | 179 | > elapsed_time(end_event) 180 | 181 | 返回事件记录之前经过的时间。 182 | 183 | > ipc_handle() 184 | 185 | 返回此事件的IPC句柄。 186 | 187 | > query() 188 | 189 | 检查事件是否已被记录。 190 | 191 | **返回:** 一个布尔值,指示事件是否已被记录。 192 | 193 | > record(stream=None) 194 | 195 | 记录给定流的事件。 196 | 197 | > synchronize() 198 | 199 | 与事件同步。 200 | 201 | > wait(stream=None) 202 | 203 | 使给定的流等待事件。 204 | -------------------------------------------------------------------------------- /docs/package_references/nn_init.md: -------------------------------------------------------------------------------- 1 | # torch.nn.init 2 | 3 | ```python 4 | torch.nn.init.calculate_gain(nonlinearity,param=None) 5 | ``` 6 | 7 | 对于给定的非线性函数,返回推荐的增益值。这些值如下所示: 8 | 9 | 10 | | nonlinearity | gain | 11 | | ------------ | ---------------------------- | 12 | | linear | 1 | 13 | | conv{1,2,3}d | 1 | 14 | | sigmoid | 1 | 15 | | tanh | 5/3 | 16 | | relu | sqrt(2) | 17 | | leaky_relu | sqrt(2/(1+negative_slope^2)) | 18 | 19 | **参数:** 20 | 21 | - **nonlinearity** - 非线性函数(`nn.functional`名称) 22 | - **param** - 非线性函数的可选参数 23 | 24 | **例子:** 25 | 26 | ```python 27 | >>> gain = nn.init.gain('leaky_relu') 28 | ``` 29 | 30 | ```python 31 | torch.nn.init.uniform(tensor, a=0, b=1) 32 | ``` 33 | 34 | 从均匀分布U(a, b)中生成值,填充输入的张量或变量 35 | 36 | **参数:** 37 | 38 | - **tensor** - n维的torch.Tensor 39 | - **a** - 均匀分布的下界 40 | - **b** - 均匀分布的上界 41 | 42 | **例子** 43 | 44 | ```python 45 | >>> w = torch.Tensor(3, 5) 46 | >>> nn.init.uniform(w) 47 | ``` 48 | 49 | ```python 50 | torch.nn.init.normal(tensor, mean=0, std=1) 51 | ``` 52 | 53 | 从给定均值和标准差的正态分布N(mean, std)中生成值,填充输入的张量或变量 54 | 55 | **参数:** 56 | 57 | - **tensor** – n维的torch.Tensor 58 | - **mean** – 正态分布的均值 59 | - **std** – 正态分布的标准差 60 | 61 | **例子** 62 | 63 | ```python 64 | >>> w = torch.Tensor(3, 5) 65 | >>> nn.init.normal(w) 66 | ``` 67 | 68 | ```python 69 | torch.nn.init.constant(tensor, val) 70 | ``` 71 | 72 | 用*val*的值填充输入的张量或变量 73 | 74 | **参数:** 75 | 76 | - **tensor** – n维的torch.Tensor或autograd.Variable 77 | - **val** – 用来填充张量的值 78 | 79 | **例子:** 80 | 81 | ```python 82 | >>> w = torch.Tensor(3, 5) 83 | >>> nn.init.constant(w) 84 | ``` 85 | 86 | ```python 87 | torch.nn.init.eye(tensor) 88 | ``` 89 | 90 | 用单位矩阵来填充2维输入张量或变量。在线性层尽可能多的保存输入特性。 91 | 92 | **参数:** 93 | 94 | - **tensor** – 2维的torch.Tensor或autograd.Variable 95 | 96 | **例子:** 97 | 98 | ```python 99 | >>> w = torch.Tensor(3, 5) 100 | >>> nn.init.eye(w) 101 | ``` 102 | 103 | ```python 104 | torch.nn.init.dirac(tensor) 105 | ``` 106 | 107 | 用Dirac $\delta$ 函数来填充{3, 4, 5}维输入张量或变量。在卷积层尽可能多的保存输入通道特性。 108 | 109 | **参数:** 110 | 111 | - **tensor** – {3, 4, 5}维的torch.Tensor或autograd.Variable 112 | 113 | **例子:** 114 | 115 | ```python 116 | >>> w = torch.Tensor(3, 16, 5, 5) 117 | >>> nn.init.dirac(w) 118 | ``` 119 | 120 | ```python 121 | torch.nn.init.xavier_uniform(tensor, gain=1) 122 | ``` 123 | 124 | 根据Glorot, X.和Bengio, Y.在“Understanding the difficulty of training deep feedforward neural networks”中描述的方法,用一个均匀分布生成值,填充输入的张量或变量。结果张量中的值采样自U(-a, a),其中a= gain * sqrt( 2/(fan_in + fan_out))* sqrt(3). 该方法也被称为Glorot initialisation 125 | 126 | **参数:** 127 | 128 | - **tensor** – n维的torch.Tensor 129 | - **gain** - 可选的缩放因子 130 | 131 | **例子:** 132 | 133 | ```python 134 | >>> w = torch.Tensor(3, 5) 135 | >>> nn.init.xavier_uniform(w, gain=math.sqrt(2.0)) 136 | ``` 137 | 138 | ```python 139 | torch.nn.init.xavier_normal(tensor, gain=1) 140 | ``` 141 | 142 | 根据Glorot, X.和Bengio, Y. 于2010年在“Understanding the difficulty of training deep feedforward neural networks”中描述的方法,用一个正态分布生成值,填充输入的张量或变量。结果张量中的值采样自均值为0,标准差为gain * sqrt(2/(fan_in + fan_out))的正态分布。也被称为Glorot initialisation. 143 | 144 | **参数:** 145 | 146 | - **tensor** – n维的torch.Tensor 147 | - **gain** - 可选的缩放因子 148 | 149 | **例子:** 150 | 151 | ```python 152 | >>> w = torch.Tensor(3, 5) 153 | >>> nn.init.xavier_normal(w) 154 | ``` 155 | 156 | ```python 157 | torch.nn.init.kaiming_uniform(tensor, a=0, mode='fan_in') 158 | ``` 159 | 160 | 根据He, K等人于2015年在“Delving deep into rectifiers: Surpassing human-level performance on ImageNet classification”中描述的方法,用一个均匀分布生成值,填充输入的张量或变量。结果张量中的值采样自U(-bound, bound),其中bound = sqrt(2/((1 + a^2) * fan_in)) * sqrt(3)。也被称为He initialisation. 161 | 162 | **参数:** 163 | 164 | - **tensor** – n维的torch.Tensor或autograd.Variable 165 | - **a** -这层之后使用的rectifier的斜率系数(ReLU的默认值为0) 166 | - **mode** -可以为“fan_in”(默认)或“fan_out”。“fan_in”保留前向传播时权值方差的量级,“fan_out”保留反向传播时的量级。 167 | 168 | **例子:** 169 | 170 | ```python 171 | >>> w = torch.Tensor(3, 5) 172 | >>> nn.init.kaiming_uniform(w, mode='fan_in') 173 | ``` 174 | 175 | ```python 176 | torch.nn.init.kaiming_normal(tensor, a=0, mode='fan_in') 177 | ``` 178 | 179 | 根据He, K等人在“Delving deep into rectifiers: Surpassing human-level performance on ImageNet classification”中描述的方法,用一个正态分布生成值,填充输入的张量或变量。结果张量中的值采样自均值为0,标准差为sqrt(2/((1 + a^2) * fan_in))的正态分布。 180 | 181 | **参数:** 182 | 183 | - **tensor** – n维的torch.Tensor或 autograd.Variable 184 | - **a** -这层之后使用的rectifier的斜率系数(ReLU的默认值为0) 185 | - **mode** -可以为“fan_in”(默认)或“fan_out”。“fan_in”保留前向传播时权值方差的量级,“fan_out”保留反向传播时的量级。 186 | 187 | **例子:** 188 | 189 | ```python 190 | >>> w = torch.Tensor(3, 5) 191 | >>> nn.init.kaiming_normal(w, mode='fan_out') 192 | ``` 193 | 194 | ```python 195 | torch.nn.init.orthogonal(tensor, gain=1) 196 | ``` 197 | 198 | 用(半)正交矩阵填充输入的张量或变量。输入张量必须至少是2维的,对于更高维度的张量,超出的维度会被展平,视作行等于第一个维度,列等于稀疏矩阵乘积的2维表示。其中非零元素生成自均值为0,标准差为std的正态分布。 199 | 200 | 参考:Saxe, A等人(2013)的“Exact solutions to the nonlinear dynamics of learning in deep linear neural networks” 201 | 202 | **参数:** 203 | 204 | - **tensor** – n维的torch.Tensor或 autograd.Variable,其中n>=2 205 | - **gain** -可选 206 | 207 | **例子:** 208 | 209 | ```python 210 | >>> w = torch.Tensor(3, 5) 211 | >>> nn.init.orthogonal(w) 212 | ``` 213 | 214 | ```python 215 | torch.nn.init.sparse(tensor, sparsity, std=0.01) 216 | ``` 217 | 218 | 将2维的输入张量或变量当做稀疏矩阵填充,其中非零元素根据一个均值为0,标准差为std的正态分布生成。 219 | 参考Martens, J.(2010)的 “Deep learning via Hessian-free optimization”. 220 | 221 | **参数:** 222 | 223 | - **tensor** – n维的torch.Tensor或autograd.Variable 224 | - **sparsity** - 每列中需要被设置成零的元素比例 225 | - **std** - 用于生成非零值的正态分布的标准差 226 | 227 | **例子:** 228 | ```python 229 | >>> w = torch.Tensor(3, 5) 230 | >>> nn.init.sparse(w, sparsity=0.1) 231 | ``` -------------------------------------------------------------------------------- /docs/notes/extending.md: -------------------------------------------------------------------------------- 1 | # 扩展PyTorch 2 | 本篇文章中包含如何扩展 `torch.nn`, `torch.autograd`和 使用我们的 `C 库`编写自定义的`C`扩展。 3 | 4 | 5 | ## 扩展 torch.autograd 6 | 如果你想要添加一个新的 `Operation` 到`autograd`的话,你的`Operation`需要继承 `class Function`。`autograd`使用`Function`计算结果和梯度,同时编码 `operation`的历史。每个新的 `operation(function)` 都需要实现三个方法: 7 | 8 | - `__init__ (optional)` - 如果你的`operation`包含非`Variable`参数,那么就将其作为`__init__`的参数传入到`operation`中。例如:`AddConstant Function`加一个常数,`Transpose Function`需要指定哪两个维度需要交换。如果你的`operation`不需要额外的参数,你可以忽略`__init__`。 9 | 10 | - `forward()` - 在里面写执行此`operation`的代码。可以有任意数量的参数。如果你对某些参数指定了默认值,则这些参数是可传可不传的。记住:`forward()`的参数只能是`Variable`。函数的返回值既可以是 `Variable`也可以是`Variables`的`tuple`。同时,请参考 `Function`[function]的 `doc`,查阅有哪些 方法是只能在`forward`中调用的。 11 | - `backward()` - 梯度计算公式。 参数的个数和`forward`返回值的个数一样,每个参数代表传回到此`operation`的梯度. `backward()`的返回值的个数应该和此`operation`输入的个数一样,每个返回值对应了输入值的梯度。如果`operation`的输入不需要梯度,或者不可导,你可以返回`None`。 如果`forward()`存在可选参数,你可以返回比输入更多的梯度,只是返回的是`None`。 12 | 13 | 下面是 `Linear` 的实现代码: 14 | 15 | ```python 16 | # Inherit from Function 17 | class Linear(Function): 18 | 19 | # bias is an optional argument 20 | def forward(self, input, weight, bias=None): 21 | self.save_for_backward(input, weight, bias) 22 | output = input.mm(weight.t()) 23 | if bias is not None: 24 | output += bias.unsqueeze(0).expand_as(output) 25 | return output 26 | 27 | # This function has only a single output, so it gets only one gradient 28 | def backward(self, grad_output): 29 | # This is a pattern that is very convenient - at the top of backward 30 | # unpack saved_tensors and initialize all gradients w.r.t. inputs to 31 | # None. Thanks to the fact that additional trailing Nones are 32 | # ignored, the return statement is simple even when the function has 33 | # optional inputs. 34 | input, weight, bias = self.saved_tensors 35 | grad_input = grad_weight = grad_bias = None 36 | 37 | # These needs_input_grad checks are optional and there only to 38 | # improve efficiency. If you want to make your code simpler, you can 39 | # skip them. Returning gradients for inputs that don't require it is 40 | # not an error. 41 | if self.needs_input_grad[0]: 42 | grad_input = grad_output.mm(weight) 43 | if self.needs_input_grad[1]: 44 | grad_weight = grad_output.t().mm(input) 45 | if bias is not None and self.needs_input_grad[2]: 46 | grad_bias = grad_output.sum(0).squeeze(0) 47 | 48 | return grad_input, grad_weight, grad_bias 49 | ``` 50 | 现在,为了可以更简单的使用自定义的`operation`,我们建议将其用一个简单的 `helper function` 包装起来。 functions: 51 | 52 | ```python 53 | def linear(input, weight, bias=None): 54 | # First braces create a Function object. Any arguments given here 55 | # will be passed to __init__. Second braces will invoke the __call__ 56 | # operator, that will then use forward() to compute the result and 57 | # return it. 58 | return Linear()(input, weight, bias) 59 | ``` 60 | 61 | 你可能想知道你刚刚实现的 `backward`方法是否正确的计算了梯度。你可以使用 小的有限的差分进行数值估计。 62 | 63 | ```python 64 | from torch.autograd import gradcheck 65 | 66 | # gradchek takes a tuple of tensor as input, check if your gradient 67 | # evaluated with these tensors are close enough to numerical 68 | # approximations and returns True if they all verify this condition. 69 | input = (Variable(torch.randn(20,20).double(), requires_grad=True),) 70 | test = gradcheck.gradcheck(Linear(), input, eps=1e-6, atol=1e-4) 71 | print(test) 72 | ``` 73 | 74 | ## 扩展 torch.nn 75 | 76 | `nn` 包含两种接口 - `modules`和他们的`functional`版本。通过这两个接口,你都可以扩展`nn`。但是我们建议,在扩展`layer`的时候,使用`modules`, 因为`modules`保存着参数和`buffer`。如果不需要参数的话,那么建议使用`functional`(激活函数,pooling,这些都不需要参数)。 77 | 78 | 增加一个`operation`的 `functional`版本已经在上面一节介绍完毕。 79 | 80 | 增加一个模块(`module`)。 81 | 由于`nn`重度使用`autograd`。所以,添加一个新`module`需要实现一个 用来执行 计算 和 计算梯度 的`Function`。从现在开始,假定我们想要实现一个`Linear module`,记得之前我们已经实现了一个`Linear Funciton`。 只需要很少的代码就可以完成这个工作。 现在,我们需要实现两个方法: 82 | 83 | - `__init__ (optional)` - 输入参数,例如`kernel sizes`, `numbers of features`, 等等。同时初始化 `parameters`和`buffers`。 84 | 85 | - `forward()` - 实例化一个执行`operation`的`Function`,使用它执行`operation`。和`functional wrapper(上面实现的那个简单的wrapper)`十分类似。 86 | 87 | `Linear module`实现代码: 88 | ```python 89 | class Linear(nn.Module): 90 | def __init__(self, input_features, output_features, bias=True): 91 | self.input_features = input_features 92 | self.output_features = output_features 93 | 94 | # nn.Parameter is a special kind of Variable, that will get 95 | # automatically registered as Module's parameter once it's assigned 96 | # as an attribute. Parameters and buffers need to be registered, or 97 | # they won't appear in .parameters() (doesn't apply to buffers), and 98 | # won't be converted when e.g. .cuda() is called. You can use 99 | # .register_buffer() to register buffers. 100 | # nn.Parameters can never be volatile and, different than Variables, 101 | # they require gradients by default. 102 | self.weight = nn.Parameter(torch.Tensor(input_features, output_features)) 103 | if bias: 104 | self.bias = nn.Parameter(torch.Tensor(output_features)) 105 | else: 106 | # You should always register all possible parameters, but the 107 | # optional ones can be None if you want. 108 | self.register_parameter('bias', None) 109 | 110 | # Not a very smart way to initialize weights 111 | self.weight.data.uniform_(-0.1, 0.1) 112 | if bias is not None: 113 | self.bias.data.uniform_(-0.1, 0.1) 114 | 115 | def forward(self, input): 116 | # See the autograd section for explanation of what happens here. 117 | return Linear()(input, self.weight, self.bias) 118 | #注意这个Linear是之前实现过的Linear 119 | ``` 120 | ## 编写自定义`C`扩展 121 | 122 | Coming soon. For now you can find an example at [GitHub](https://github.com/pytorch/extension-ffi). 123 | -------------------------------------------------------------------------------- /docs/package_references/torch-autograd.md: -------------------------------------------------------------------------------- 1 | # Automatic differentiation package - torch.autograd 2 | 3 | `torch.autograd`提供了类和函数用来对任意标量函数进行求导。要想使用自动求导,只需要对已有的代码进行微小的改变。只需要将所有的`tensor`包含进`Variable`对象中即可。 4 | 5 | ### torch.autograd.backward(variables, grad_variables, retain_variables=False) 6 | Computes the sum of gradients of given variables w.r.t. graph leaves. 7 | 给定图的叶子节点`variables`, 计算图中变量的梯度和。 8 | 计算图可以通过链式法则求导。如果`variables`中的任何一个`variable`是 非标量(`non-scalar`)的,且`requires_grad=True`。那么此函数需要指定`grad_variables`,它的长度应该和`variables`的长度匹配,里面保存了相关`variable`的梯度(对于不需要`gradient tensor`的`variable`,`None`是可取的)。 9 | 10 | 此函数累积`leaf variables`计算的梯度。你可能需要在调用此函数之前将`leaf variable`的梯度置零。 11 | 12 | 参数说明: 13 | 14 | - variables (variable 列表) – 被求微分的叶子节点,即 `ys` 。 15 | 16 | - grad_variables (`Tensor` 列表) – 对应`variable`的梯度。仅当`variable`不是标量且需要求梯度的时候使用。 17 | 18 | - retain_variables (bool) – `True`,计算梯度时所需要的`buffer`在计算完梯度后不会被释放。如果想对一个子图多次求微分的话,需要设置为`True`。 19 | 20 | ## Variable 21 | ### API 兼容性 22 | 23 | `Variable API` 几乎和 `Tensor API`一致 (除了一些`in-place`方法,这些`in-place`方法会修改 `required_grad=True`的 `input` 的值)。多数情况下,将`Tensor`替换为`Variable`,代码一样会正常的工作。由于这个原因,我们不会列出`Variable`的所有方法,你可以通过`torch.Tensor`的文档来获取相关知识。 24 | 25 | ### In-place operations on Variables 26 | 在`autograd`中支持`in-place operations`是非常困难的。同时在很多情况下,我们阻止使用`in-place operations`。`Autograd`的贪婪的 释放`buffer`和 复用使得它效率非常高。只有在非常少的情况下,使用`in-place operations`可以降低内存的使用。除非你面临很大的内存压力,否则不要使用`in-place operations`。 27 | 28 | ### In-place 正确性检查 29 | 所有的`Variable`都会记录用在他们身上的 `in-place operations`。如果`pytorch`检测到`variable`在一个`Function`中已经被保存用来`backward`,但是之后它又被`in-place operations`修改。当这种情况发生时,在`backward`的时候,`pytorch`就会报错。这种机制保证了,如果你用了`in-place operations`,但是在`backward`过程中没有报错,那么梯度的计算就是正确的。 30 | 31 | ### class torch.autograd.Variable [source] 32 | 33 | 包装一个`Tensor`,并记录用在它身上的`operations`。 34 | 35 | `Variable`是`Tensor`对象的一个`thin wrapper`,它同时保存着`Variable`的梯度和创建这个`Variable`的`Function`的引用。这个引用可以用来追溯创建这个`Variable`的整条链。如果`Variable`是被用户所创建的,那么它的`creator`是`None`,我们称这种对象为 `leaf Variables`。 36 | 37 | 由于`autograd`只支持标量值的反向求导(即:`y`是标量),梯度的大小总是和数据的大小匹配。同时,仅仅给`leaf variables`分配梯度,其他`Variable`的梯度总是为0. 38 | 39 | **`变量:`** 40 | 41 | - data – 包含的`Tensor` 42 | 43 | - grad – 保存着`Variable`的梯度。这个属性是懒分配的,且不能被重新分配。 44 | 45 | - requires_grad – 布尔值,指示这个`Variable`是否是被一个包含`Variable`的子图创建的。更多细节请看`Excluding subgraphs from backward`。只能改变`leaf variable`的这个标签。 46 | 47 | - volatile – 布尔值,指示这个`Variable`是否被用于推断模式(即,不保存历史信息)。更多细节请看`Excluding subgraphs from backward`。只能改变`leaf variable`的这个标签。 48 | 49 | - creator – 创建这个`Variable`的`Function`,对于`leaf variable`,这个属性为`None`。只读属性。 50 | 51 | **`属性:`** 52 | 53 | - data (any tensor class) – 被包含的`Tensor` 54 | 55 | - requires_grad (bool) – `requires_grad`标记. 只能通过`keyword`传入. 56 | 57 | - volatile (bool) – `volatile`标记. 只能通过`keyword`传入. 58 | 59 | #### backward(gradient=None, retain_variables=False)[source] 60 | 61 | 当前`Variable`对`leaf variable`求偏导。 62 | 63 | 计算图可以通过链式法则求导。如果`Variable`是 非标量(`non-scalar`)的,且`requires_grad=True`。那么此函数需要指定`gradient`,它的形状应该和`Variable`的长度匹配,里面保存了`Variable`的梯度。 64 | 65 | 此函数累积`leaf variable`的梯度。你可能需要在调用此函数之前将`Variable`的梯度置零。 66 | 67 | **`参数:`** 68 | 69 | - gradient (Tensor) – 其他函数对于此`Variable`的导数。仅当`Variable`不是标量的时候使用,类型和位形状应该和`self.data`一致。 70 | - retain_variables (bool) – `True`, 计算梯度所必要的`buffer`在经历过一次`backward`过程后不会被释放。如果你想多次计算某个子图的梯度的时候,设置为`True`。在某些情况下,使用`autograd.backward()`效率更高。 71 | 72 | #### detach()[source] 73 | Returns a new Variable, detached from the current graph. 74 | 返回一个新的`Variable`,从当前图中分离下来的。 75 | 76 | 返回的`Variable` `requires_grad=False`,如果输入 `volatile=True`,那么返回的`Variable` `volatile=True`。 77 | 78 | **`注意:`** 79 | 80 | 返回的`Variable`和原始的`Variable`公用同一个`data tensor`。`in-place`修改会在两个`Variable`上同时体现(因为它们共享`data tensor`),可能会导致错误。 81 | 82 | #### detach_()[source] 83 | 84 | 将一个`Variable`从创建它的图中分离,并把它设置成`leaf variable`。 85 | 86 | #### register_hook(hook)[source] 87 | 88 | 注册一个`backward`钩子。 89 | 90 | 每次`gradients`被计算的时候,这个`hook`都被调用。`hook`应该拥有以下签名: 91 | 92 | `hook(grad) -> Variable or None` 93 | 94 | `hook`不应该修改它的输入,但是它可以选择性的返回一个替代当前梯度的新梯度。 95 | 96 | 这个函数返回一个 句柄(`handle`)。它有一个方法 `handle.remove()`,可以用这个方法将`hook`从`module`移除。 97 | 98 | Example 99 | ```python 100 | v = Variable(torch.Tensor([0, 0, 0]), requires_grad=True) 101 | h = v.register_hook(lambda grad: grad * 2) # double the gradient 102 | v.backward(torch.Tensor([1, 1, 1])) 103 | #先计算原始梯度,再进hook,获得一个新梯度。 104 | print(v.grad.data) 105 | 106 | 2 107 | 2 108 | 2 109 | [torch.FloatTensor of size 3] 110 | >>> h.remove() # removes the hook 111 | ``` 112 | ```python 113 | def w_hook(grad): 114 | print("hello") 115 | return None 116 | w1 = Variable(torch.FloatTensor([1, 1, 1]),requires_grad=True) 117 | 118 | w1.register_hook(w_hook) # 如果hook返回的是None的话,那么梯度还是原来计算的梯度。 119 | 120 | w1.backward(gradient=torch.FloatTensor([1, 1, 1])) 121 | print(w1.grad) 122 | ``` 123 | ``` 124 | hello 125 | Variable containing: 126 | 1 127 | 1 128 | 1 129 | [torch.FloatTensor of size 3] 130 | ``` 131 | 132 | #### reinforce(reward)[source] 133 | 134 | 注册一个奖励,这个奖励是由一个随机过程得到的。 135 | 136 | 微分一个随机节点需要提供一个奖励值。如果你的计算图中包含随机 `operations`,你需要在他们的输出上调用这个函数。否则的话,会报错。 137 | 138 | **`参数:`** 139 | 140 | - reward (Tensor) – 每个元素的reward。必须和`Varaible`形状相同,并在同一个设备上。 141 | 142 | ### class torch.autograd.Function[source] 143 | Records operation history and defines formulas for differentiating ops. 144 | 记录`operation`的历史,定义微分公式。 145 | 每个执行在`Varaibles`上的`operation`都会创建一个`Function`对象,这个`Function`对象执行计算工作,同时记录下来。这个历史以有向无环图的形式保存下来,有向图的节点为`functions`,有向图的边代表数据依赖关系(`input<-output`)。之后,当`backward`被调用的时候,计算图以拓扑顺序处理,通过调用每个`Function`对象的`backward()`,同时将返回的梯度传递给下一个`Function`。 146 | 147 | 通常情况下,用户能和`Functions`交互的唯一方法就是创建`Function`的子类,定义新的`operation`。这是扩展`torch.autograd`的推荐方法。 148 | 149 | 由于`Function`逻辑在很多脚本上都是热点,所有我们把几乎所有的`Function`都使用`C`实现,通过这种策略保证框架的开销是最小的。 150 | 151 | 每个`Function`只被使用一次(在forward过程中)。 152 | 153 | **`变量:`** 154 | 155 | - saved_tensors – 调用`forward()`时需要被保存的 `Tensors`的 `tuple`。 156 | 157 | - needs_input_grad – 长度为 输入数量的 布尔值组成的 `tuple`。指示给定的`input`是否需要梯度。这个被用来优化用于`backward`过程中的`buffer`,忽略`backward`中的梯度计算。 158 | 159 | - num_inputs – `forward` 的输入参数数量。 160 | 161 | - num_outputs – `forward`返回的`Tensor`数量。 162 | 163 | - requires_grad – 布尔值。指示`backward`以后会不会被调用。 164 | 165 | - previous_functions – 长度为 `num_inputs`的 Tuple of (int, Function) pairs。`Tuple`中的每单元保存着创建 `input`的`Function`的引用,和索引。 166 | #### backward(* grad_output)[source] 167 | 168 | 定义了`operation`的微分公式。 169 | 170 | 所有的`Function`子类都应该重写这个方法。 171 | 172 | 所有的参数都是`Tensor`。他必须接收和`forward`的输出 相同个数的参数。而且它需要返回和`forward`的输入参数相同个数的`Tensor`。 173 | 即:`backward`的输入参数是 此`operation`的输出的值的梯度。`backward`的返回值是此`operation`输入值的梯度。 174 | 175 | #### forward(* input)[source] 176 | 177 | 执行`operation`。 178 | 179 | 所有的`Function`子类都需要重写这个方法。 180 | 181 | 可以接收和返回任意个数 `tensors` 182 | 183 | #### mark_dirty(* args)[source] 184 | 185 | 将输入的 `tensors` 标记为被`in-place operation`修改过。 186 | 187 | 这个方法应当至多调用一次,仅仅用在 `forward`方法里,而且`mark_dirty`的实参只能是`forward`的实参。 188 | 189 | 每个在`forward`方法中被`in-place operations`修改的`tensor`都应该传递给这个方法。这样,可以保证检查的正确性。这个方法在`tensor`修改前后调用都可以。 190 | 191 | #### mark_non_differentiable(* args)[source] 192 | 将输出标记为不可微。 193 | 194 | 这个方法至多只能被调用一次,只能在`forward`中调用,而且实参只能是`forward`的返回值。 195 | 196 | 这个方法会将输出标记成不可微,会增加`backward`过程中的效率。在`backward`中,你依旧需要接收`forward`输出值的梯度,但是这些梯度一直是`None`。 197 | 198 | This is used e.g. for indices returned from a max Function. 199 | 200 | #### mark_shared_storage(* pairs)[source] 201 | 将给定的`tensors pairs`标记为共享存储空间。 202 | 203 | 这个方法至多只能被调用一次,只能在`forward`中调用,而且所有的实参必须是`(input, output)`对。 204 | 205 | 如果一些 `inputs` 和 `outputs` 是共享存储空间的,所有的这样的 `(input, output)`对都应该传给这个函数,保证 `in-place operations` 检查的正确性。唯一的特例就是,当 `output`和`input`是同一个`tensor`(`in-place operations`的输入和输出)。这种情况下,就没必要指定它们之间的依赖关系,因为这个很容易就能推断出来。 206 | 207 | 这个函数在很多时候都用不到。主要是用在 索引 和 转置 这类的 `op` 中。 208 | 209 | #### save_for_backward(* tensors)[source] 210 | 211 | 将传入的 `tensor` 保存起来,留着`backward`的时候用。 212 | 213 | 这个方法至多只能被调用一次,只能在`forward`中调用。 214 | 215 | 之后,被保存的`tensors`可以通过 `saved_tensors`属性获取。在返回这些`tensors`之前,`pytorch`做了一些检查,保证这些`tensor`没有被`in-place operations`修改过。 216 | 217 | 实参可以是`None`。 218 | -------------------------------------------------------------------------------- /docs/package_references/torch-optim.md: -------------------------------------------------------------------------------- 1 | # torch.optim 2 | 3 | `torch.optim`是一个实现了各种优化算法的库。大部分常用的方法得到支持,并且接口具备足够的通用性,使得未来能够集成更加复杂的方法。 4 | 5 | ## 如何使用optimizer 6 | 为了使用`torch.optim`,你需要构建一个optimizer对象。这个对象能够保持当前参数状态并基于计算得到的梯度进行参数更新。 7 | 8 | ### 构建 9 | 为了构建一个`Optimizer`,你需要给它一个包含了需要优化的参数(必须都是`Variable`对象)的iterable。然后,你可以设置optimizer的参 10 | 数选项,比如学习率,权重衰减,等等。 11 | 12 | 例子: 13 | ```python 14 | optimizer = optim.SGD(model.parameters(), lr = 0.01, momentum=0.9) 15 | optimizer = optim.Adam([var1, var2], lr = 0.0001) 16 | ``` 17 | 18 | ### 为每个参数单独设置选项 19 | `Optimizer`也支持为每个参数单独设置选项。若想这么做,不要直接传入`Variable`的iterable,而是传入`dict`的iterable。每一个dict都分别定 20 | 义了一组参数,并且包含一个`param`键,这个键对应参数的列表。其他的键应该optimizer所接受的其他参数的关键字相匹配,并且会被用于对这组参数的 21 | 优化。 22 | 23 | **`注意:`** 24 | 25 | 你仍然能够传递选项作为关键字参数。在未重写这些选项的组中,它们会被用作默认值。当你只想改动一个参数组的选项,但其他参数组的选项不变时,这是 26 | 非常有用的。 27 | 28 | 例如,当我们想指定每一层的学习率时,这是非常有用的: 29 | 30 | ```python 31 | optim.SGD([ 32 | {'params': model.base.parameters()}, 33 | {'params': model.classifier.parameters(), 'lr': 1e-3} 34 | ], lr=1e-2, momentum=0.9) 35 | ``` 36 | 37 | 这意味着`model.base`的参数将会使用`1e-2`的学习率,`model.classifier`的参数将会使用`1e-3`的学习率,并且`0.9`的momentum将会被用于所 38 | 有的参数。 39 | 40 | ### 进行单次优化 41 | 所有的optimizer都实现了`step()`方法,这个方法会更新所有的参数。它能按两种方式来使用: 42 | 43 | **`optimizer.step()`** 44 | 45 | 这是大多数optimizer所支持的简化版本。一旦梯度被如`backward()`之类的函数计算好后,我们就可以调用这个函数。 46 | 47 | 例子 48 | 49 | ```python 50 | for input, target in dataset: 51 | optimizer.zero_grad() 52 | output = model(input) 53 | loss = loss_fn(output, target) 54 | loss.backward() 55 | optimizer.step() 56 | ``` 57 | 58 | **`optimizer.step(closure)`** 59 | 60 | 一些优化算法例如Conjugate Gradient和LBFGS需要重复多次计算函数,因此你需要传入一个闭包去允许它们重新计算你的模型。这个闭包应当清空梯度, 61 | 计算损失,然后返回。 62 | 63 | 例子: 64 | 65 | ```python 66 | for input, target in dataset: 67 | def closure(): 68 | optimizer.zero_grad() 69 | output = model(input) 70 | loss = loss_fn(output, target) 71 | loss.backward() 72 | return loss 73 | optimizer.step(closure) 74 | ``` 75 | 76 | ## 算法 77 | 78 | ### class torch.optim.Optimizer(params, defaults) [source] 79 | Base class for all optimizers. 80 | 81 | **参数:** 82 | 83 | * params (iterable) —— `Variable` 或者 `dict`的iterable。指定了什么参数应当被优化。 84 | * defaults —— (dict):包含了优化选项默认值的字典(一个参数组没有指定的参数选项将会使用默认值)。 85 | 86 | #### load_state_dict(state_dict) [source] 87 | 加载optimizer状态 88 | 89 | **参数:** 90 | 91 | state_dict (`dict`) —— optimizer的状态。应当是一个调用`state_dict()`所返回的对象。 92 | 93 | #### state_dict() [source] 94 | 以`dict`返回optimizer的状态。 95 | 96 | 它包含两项。 97 | 98 | * state - 一个保存了当前优化状态的dict。optimizer的类别不同,state的内容也会不同。 99 | * param_groups - 一个包含了全部参数组的dict。 100 | 101 | #### step(closure) [source] 102 | 进行单次优化 (参数更新). 103 | 104 | **参数:** 105 | 106 | * closure (`callable`) – 一个重新评价模型并返回loss的闭包,对于大多数参数来说是可选的。 107 | 108 | #### zero_grad() [source] 109 | 清空所有被优化过的Variable的梯度. 110 | 111 | ### class torch.optim.Adadelta(params, lr=1.0, rho=0.9, eps=1e-06, weight_decay=0)[source] 112 | 实现Adadelta算法。 113 | 114 | 它在[ADADELTA: An Adaptive Learning Rate Method.](https://arxiv.org/abs/1212.5701)中被提出。 115 | 116 | **参数:** 117 | 118 | * params (iterable) – 待优化参数的iterable或者是定义了参数组的dict 119 | * rho (`float`, 可选) – 用于计算平方梯度的运行平均值的系数(默认:0.9) 120 | * eps (`float`, 可选) – 为了增加数值计算的稳定性而加到分母里的项(默认:1e-6) 121 | * lr (`float`, 可选) – 在delta被应用到参数更新之前对它缩放的系数(默认:1.0) 122 | * weight_decay (`float`, 可选) – 权重衰减(L2惩罚)(默认: 0) 123 | 124 | #### step(closure) [source] 125 | 进行单次优化 (参数更新). 126 | 127 | **参数:** 128 | 129 | * closure (`callable`) – 一个重新评价模型并返回loss的闭包,对于大多数参数来说是可选的。 130 | 131 | ### class torch.optim.Adagrad(params, lr=0.01, lr_decay=0, weight_decay=0)[source] 132 | 实现Adagrad算法。 133 | 134 | 它在 [Adaptive Subgradient Methods for Online Learning and Stochastic Optimization]( 135 | http://jmlr.org/papers/v12/duchi11a.html)中被提出。 136 | 137 | **参数:** 138 | 139 | * params (iterable) – 待优化参数的iterable或者是定义了参数组的dict 140 | * lr (`float`, 可选) – 学习率(默认: 1e-2) 141 | * lr_decay (`float`, 可选) – 学习率衰减(默认: 0) 142 | * weight_decay (`float`, 可选) – 权重衰减(L2惩罚)(默认: 0) 143 | 144 | #### step(closure) [source] 145 | 进行单次优化 (参数更新). 146 | 147 | **参数:** 148 | 149 | * closure (`callable`) – 一个重新评价模型并返回loss的闭包,对于大多数参数来说是可选的。 150 | 151 | ### class torch.optim.Adam(params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0)[source] 152 | 实现Adam算法。 153 | 154 | 它在[Adam: A Method for Stochastic Optimization](https://arxiv.org/abs/1412.6980)中被提出。 155 | 156 | **参数:** 157 | 158 | * params (iterable) – 待优化参数的iterable或者是定义了参数组的dict 159 | * lr (`float`, 可选) – 学习率(默认:1e-3) 160 | * betas (Tuple[`float`, `float`], 可选) – 用于计算梯度以及梯度平方的运行平均值的系数(默认:0.9,0.999) 161 | * eps (`float`, 可选) – 为了增加数值计算的稳定性而加到分母里的项(默认:1e-8) 162 | * weight_decay (`float`, 可选) – 权重衰减(L2惩罚)(默认: 0) 163 | 164 | #### step(closure) [source] 165 | 进行单次优化 (参数更新). 166 | 167 | **参数:** 168 | 169 | * closure (`callable`) – 一个重新评价模型并返回loss的闭包,对于大多数参数来说是可选的。 170 | 171 | ### class torch.optim.Adamax(params, lr=0.002, betas=(0.9, 0.999), eps=1e-08, weight_decay=0)[source] 172 | 实现Adamax算法(Adam的一种基于无穷范数的变种)。 173 | 174 | 它在[Adam: A Method for Stochastic Optimization](https://arxiv.org/abs/1412.6980)中被提出。 175 | 176 | **参数:** 177 | 178 | * params (iterable) – 待优化参数的iterable或者是定义了参数组的dict 179 | * lr (`float`, 可选) – 学习率(默认:2e-3) 180 | * betas (Tuple[`float`, `float`], 可选) – 用于计算梯度以及梯度平方的运行平均值的系数 181 | * eps (`float`, 可选) – 为了增加数值计算的稳定性而加到分母里的项(默认:1e-8) 182 | * weight_decay (`float`, 可选) – 权重衰减(L2惩罚)(默认: 0) 183 | 184 | #### step(closure) [source] 185 | 进行单次优化 (参数更新). 186 | 187 | **参数:** 188 | 189 | * closure (`callable`) – 一个重新评价模型并返回loss的闭包,对于大多数参数来说是可选的。 190 | 191 | ### class torch.optim.ASGD(params, lr=0.01, lambd=0.0001, alpha=0.75, t0=1000000.0, weight_decay=0)[source] 192 | 实现平均随机梯度下降算法。 193 | 194 | 它在[Acceleration of stochastic approximation by averaging](http://dl.acm.org/citation.cfm?id=131098)中被提出。 195 | 196 | **参数:** 197 | 198 | * params (iterable) – 待优化参数的iterable或者是定义了参数组的dict 199 | * lr (`float`, 可选) – 学习率(默认:1e-2) 200 | * lambd (`float`, 可选) – 衰减项(默认:1e-4) 201 | * alpha (`float`, 可选) – eta更新的指数(默认:0.75) 202 | * t0 (`float`, 可选) – 指明在哪一次开始平均化(默认:1e6) 203 | * weight_decay (`float`, 可选) – 权重衰减(L2惩罚)(默认: 0) 204 | 205 | #### step(closure) [source] 206 | 进行单次优化 (参数更新). 207 | 208 | **参数:** 209 | 210 | * closure (`callable`) – 一个重新评价模型并返回loss的闭包,对于大多数参数来说是可选的。 211 | 212 | ### class torch.optim.LBFGS(params, lr=1, max_iter=20, max_eval=None, tolerance_grad=1e-05, tolerance_change=1e-09, history_size=100, line_search_fn=None)[source] 213 | 实现L-BFGS算法。 214 | 215 | #### 警告 216 | 这个optimizer不支持为每个参数单独设置选项以及不支持参数组(只能有一个) 217 | 218 | #### 警告 219 | 目前所有的参数不得不都在同一设备上。在将来这会得到改进。 220 | 221 | #### 注意 222 | 这是一个内存高度密集的optimizer(它要求额外的`param_bytes * (history_size + 1)` 个字节)。如果它不适应内存,尝试减小history size,或者使用不同的算法。 223 | 224 | **参数:** 225 | 226 | * lr (`float`) – 学习率(默认:1) 227 | * max_iter (`int`) – 每一步优化的最大迭代次数(默认:20)) 228 | * max_eval (`int`) – 每一步优化的最大函数评价次数(默认:max * 1.25) 229 | * tolerance_grad (`float`) – 一阶最优的终止容忍度(默认:1e-5) 230 | * tolerance_change (`float`) – 在函数值/参数变化量上的终止容忍度(默认:1e-9) 231 | * history_size (`int`) – 更新历史的大小(默认:100) 232 | 233 | #### step(closure) [source] 234 | 进行单次优化 (参数更新). 235 | 236 | **参数:** 237 | 238 | * closure (`callable`) – 一个重新评价模型并返回loss的闭包,对于大多数参数来说是可选的。 239 | 240 | ### class torch.optim.RMSprop(params, lr=0.01, alpha=0.99, eps=1e-08, weight_decay=0, momentum=0, centered=False)[source] 241 | 实现RMSprop算法。 242 | 243 | 由G. H`int`on在他的[课程](http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)中提出. 244 | 245 | 中心版本首次出现在[Generating Sequences With Recurrent Neural Networks]( 246 | https://arxiv.org/pdf/1308.0850v5.pdf). 247 | 248 | **参数:** 249 | 250 | * params (iterable) – 待优化参数的iterable或者是定义了参数组的dict 251 | * lr (`float`, 可选) – 学习率(默认:1e-2) 252 | * momentum (`float`, 可选) – 动量因子(默认:0) 253 | * alpha (`float`, 可选) – 平滑常数(默认:0.99) 254 | * eps (`float`, 可选) – 为了增加数值计算的稳定性而加到分母里的项(默认:1e-8) 255 | * centered (`bool`, 可选) – 如果为True,计算中心化的RMSProp,并且用它的方差预测值对梯度进行归一化 256 | * weight_decay (`float`, 可选) – 权重衰减(L2惩罚)(默认: 0) 257 | 258 | #### step(closure) [source] 259 | 进行单次优化 (参数更新). 260 | 261 | **参数:** 262 | 263 | * closure (`callable`) – 一个重新评价模型并返回loss的闭包,对于大多数参数来说是可选的。 264 | 265 | ### class torch.optim.Rprop(params, lr=0.01, etas=(0.5, 1.2), step_sizes=(1e-06, 50))[source] 266 | 实现弹性反向传播算法。 267 | 268 | **参数:** 269 | 270 | * params (iterable) – 待优化参数的iterable或者是定义了参数组的dict 271 | * lr (`float`, 可选) – 学习率(默认:1e-2) 272 | * etas (Tuple[`float`, `float`], 可选) – 一对(etaminus,etaplis), 它们分别是乘法的增加和减小的因子(默认:0.5,1.2) 273 | * step_sizes (Tuple[`float`, `float`], 可选) – 允许的一对最小和最大的步长(默认:1e-6,50) 274 | 275 | #### step(closure) [source] 276 | 进行单次优化 (参数更新). 277 | 278 | **参数:** 279 | 280 | * closure (`callable`) – 一个重新评价模型并返回loss的闭包,对于大多数参数来说是可选的。 281 | 282 | ### class torch.optim.SGD(params, lr=, momentum=0, dampening=0, weight_decay=0, nesterov=False)[source] 283 | 实现随机梯度下降算法(momentum可选)。 284 | 285 | Nesterov动量基于[On the importance of initialization and momentum in deep learning]( 286 | http://www.cs.toronto.edu/~h`int`on/absps/momentum.pdf)中的公式. 287 | 288 | **参数:** 289 | 290 | * params (iterable) – 待优化参数的iterable或者是定义了参数组的dict 291 | * lr (`float`) – 学习率 292 | * momentum (`float`, 可选) – 动量因子(默认:0) 293 | * weight_decay (`float`, 可选) – 权重衰减(L2惩罚)(默认:0) 294 | * dampening (`float`, 可选) – 动量的抑制因子(默认:0) 295 | * nesterov (`bool`, 可选) – 使用Nesterov动量(默认:False) 296 | 297 | **例子:** 298 | ```python 299 | >>> optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9) 300 | >>> optimizer.zero_grad() 301 | >>> loss_fn(model(input), target).backward() 302 | >>> optimizer.step() 303 | ``` 304 | 305 | #### Note 306 | 带有动量/Nesterov的SGD的实现稍微不同于Sutskever等人以及其他框架中的实现。 307 | 308 | 考虑动量的具体情况,更新可以写成 309 | 310 | v=ρ∗v+g 311 | 312 | p=p−lr∗v 313 | 314 | 其中,p、g、v和ρ分别是参数、梯度、速度和动量。 315 | 316 | 这跟Sutskever等人以及其他框架的实现是相反的,它们采用这样的更新 317 | 318 | v=ρ∗v+lr∗g 319 | 320 | p=p−v 321 | 322 | Nesterov的版本也类似地被修改了。 323 | 324 | #### step(closure) [source] 325 | 进行单次优化 (参数更新). 326 | 327 | **参数:** 328 | 329 | * closure (`callable`) – 一个重新评价模型并返回loss的闭包,对于大多数参数来说是可选的。 -------------------------------------------------------------------------------- /docs/package_references/functional.md: -------------------------------------------------------------------------------- 1 | # torch.nn.functional 2 | ## Convolution 函数 3 | ```python 4 | torch.nn.functional.conv1d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) 5 | ``` 6 | 对几个输入平面组成的输入信号应用1D卷积。 7 | 8 | 有关详细信息和输出形状,请参见`Conv1d`。 9 | 10 | **参数:** 11 | - **input** – 输入张量的形状 (minibatch x in_channels x iW) 12 | - **weight** – 过滤器的形状 (out_channels, in_channels, kW) 13 | - **bias** – 可选偏置的形状 (out_channels) 14 | - **stride** – 卷积核的步长,默认为1 15 | 16 | **例子:** 17 | ```python 18 | >>> filters = autograd.Variable(torch.randn(33, 16, 3)) 19 | >>> inputs = autograd.Variable(torch.randn(20, 16, 50)) 20 | >>> F.conv1d(inputs, filters) 21 | ``` 22 | 23 | ```python 24 | torch.nn.functional.conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) 25 | ``` 26 | 对几个输入平面组成的输入信号应用2D卷积。 27 | 28 | 有关详细信息和输出形状,请参见`Conv2d`。 29 | 30 | **参数:** 31 | - **input** – 输入张量 (minibatch x in_channels x iH x iW) 32 | - **weight** – 过滤器张量 (out_channels, in_channels/groups, kH, kW) 33 | - **bias** – 可选偏置张量 (out_channels) 34 | - **stride** – 卷积核的步长,可以是单个数字或一个元组 (sh x sw)。默认为1 35 | - **padding** – 输入上隐含零填充。可以是单个数字或元组。 默认值:0 36 | - **groups** – 将输入分成组,in_channels应该被组数除尽 37 | 38 | **例子:** 39 | ```python 40 | >>> # With square kernels and equal stride 41 | >>> filters = autograd.Variable(torch.randn(8,4,3,3)) 42 | >>> inputs = autograd.Variable(torch.randn(1,4,5,5)) 43 | >>> F.conv2d(inputs, filters, padding=1) 44 | ``` 45 | 46 | ```python 47 | torch.nn.functional.conv3d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) 48 | ``` 49 | 对几个输入平面组成的输入信号应用3D卷积。 50 | 51 | 有关详细信息和输出形状,请参见`Conv3d`。 52 | 53 | **参数:** 54 | - **input** – 输入张量的形状 (minibatch x in_channels x iT x iH x iW) 55 | - **weight** – 过滤器张量的形状 (out_channels, in_channels, kT, kH, kW) 56 | - **bias** – 可选偏置张量的形状 (out_channels) 57 | - **stride** – 卷积核的步长,可以是单个数字或一个元组 (sh x sw)。默认为1 58 | - **padding** – 输入上隐含零填充。可以是单个数字或元组。 默认值:0 59 | 60 | **例子:** 61 | ```python 62 | >>> filters = autograd.Variable(torch.randn(33, 16, 3, 3, 3)) 63 | >>> inputs = autograd.Variable(torch.randn(20, 16, 50, 10, 20)) 64 | >>> F.conv3d(inputs, filters) 65 | ``` 66 | 67 | ```python 68 | torch.nn.functional.conv_transpose1d(input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1) 69 | ``` 70 | 71 | ```python 72 | torch.nn.functional.conv_transpose2d(input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1) 73 | ``` 74 | 在由几个输入平面组成的输入图像上应用二维转置卷积,有时也称为“去卷积”。 75 | 76 | 有关详细信息和输出形状,请参阅`ConvTranspose2d`。 77 | 78 | **参数:** 79 | - **input** – 输入张量的形状 (minibatch x in_channels x iH x iW) 80 | - **weight** – 过滤器的形状 (in_channels x out_channels x kH x kW) 81 | - **bias** – 可选偏置的形状 (out_channels) 82 | - **stride** – 卷积核的步长,可以是单个数字或一个元组 (sh x sw)。默认: 1 83 | - **padding** – 输入上隐含零填充。可以是单个数字或元组。 (padh x padw)。默认: 0 84 | - **groups** – 将输入分成组,`in_channels`应该被组数除尽 85 | - **output_padding** – 0 <= padding >> # pool of square window of size=3, stride=2 119 | >>> input = Variable(torch.Tensor([[[1,2,3,4,5,6,7]]])) 120 | >>> F.avg_pool1d(input, kernel_size=3, stride=2) 121 | Variable containing: 122 | (0 ,.,.) = 123 | 2 4 6 124 | [torch.FloatTensor of size 1x1x3] 125 | ``` 126 | 127 | ```python 128 | torch.nn.functional.avg_pool2d(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True) 129 | ``` 130 | 在kh x kw区域中应用步长为dh x dw的二维平均池化操作。输出特征的数量等于输入平面的数量。 131 | 132 | 有关详细信息和输出形状,请参阅`AvgPool2d`。 133 | 134 | **参数:** 135 | - **input** – 输入的张量 (minibatch x in_channels x iH x iW) 136 | - **kernel_size** – 池化区域的大小,可以是单个数字或者元组 (kh x kw) 137 | - **stride** – 池化操作的步长,可以是单个数字或者元组 (sh x sw)。默认等于核的大小 138 | - **padding** – 在输入上隐式的零填充,可以是单个数字或者一个元组 (padh x padw),默认: 0 139 | - **ceil_mode** – 定义空间输出形状的操作 140 | - **count_include_pad** – 除以原始非填充图像内的元素数量或kh * kw 141 | 142 | ```python 143 | torch.nn.functional.avg_pool3d(input, kernel_size, stride=None) 144 | ``` 145 | 在kt x kh x kw区域中应用步长为dt x dh x dw的二维平均池化操作。输出特征的数量等于 input planes / dt。 146 | 147 | ```python 148 | torch.nn.functional.max_pool1d(input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False, return_indices=False) 149 | ``` 150 | 151 | ```python 152 | torch.nn.functional.max_pool2d(input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False, return_indices=False) 153 | ``` 154 | 155 | ```python 156 | torch.nn.functional.max_pool3d(input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False, return_indices=False) 157 | ``` 158 | 159 | ```python 160 | torch.nn.functional.max_unpool1d(input, indices, kernel_size, stride=None, padding=0, output_size=None) 161 | ``` 162 | 163 | ```python 164 | torch.nn.functional.max_unpool2d(input, indices, kernel_size, stride=None, padding=0, output_size=None) 165 | ``` 166 | 167 | ```python 168 | torch.nn.functional.max_unpool3d(input, indices, kernel_size, stride=None, padding=0, output_size=None) 169 | ``` 170 | 171 | ```python 172 | torch.nn.functional.lp_pool2d(input, norm_type, kernel_size, stride=None, ceil_mode=False) 173 | ``` 174 | 175 | ```python 176 | torch.nn.functional.adaptive_max_pool1d(input, output_size, return_indices=False) 177 | ``` 178 | 在由几个输入平面组成的输入信号上应用1D自适应最大池化。 179 | 180 | 有关详细信息和输出形状,请参阅`AdaptiveMaxPool1d`。 181 | 182 | **参数:** 183 | - **output_size** – 目标输出大小(单个整数) 184 | - **return_indices** – 是否返回池化的指数 185 | 186 | ```python 187 | torch.nn.functional.adaptive_max_pool2d(input, output_size, return_indices=False) 188 | ``` 189 | 在由几个输入平面组成的输入信号上应用2D自适应最大池化。 190 | 191 | 有关详细信息和输出形状,请参阅`AdaptiveMaxPool2d`。 192 | 193 | **参数:** 194 | - **output_size** – 目标输出大小(单整数或双整数元组) 195 | - **return_indices** – 是否返回池化的指数 196 | 197 | ```python 198 | torch.nn.functional.adaptive_avg_pool1d(input, output_size) 199 | ``` 200 | 在由几个输入平面组成的输入信号上应用1D自适应平均池化。 201 | 202 | 有关详细信息和输出形状,请参阅`AdaptiveAvgPool1d`。 203 | 204 | **参数:** 205 | - **output_size** – 目标输出大小(单整数或双整数元组) 206 | 207 | 208 | ```python 209 | torch.nn.functional.adaptive_avg_pool2d(input, output_size) 210 | ``` 211 | 在由几个输入平面组成的输入信号上应用2D自适应平均池化。 212 | 213 | 有关详细信息和输出形状,请参阅`AdaptiveAvgPool2d`。 214 | 215 | **参数:** 216 | - **output_size** – 目标输出大小(单整数或双整数元组) 217 | 218 | 219 | ## 非线性激活函数 220 | ```python 221 | torch.nn.functional.threshold(input, threshold, value, inplace=False) 222 | ``` 223 | 224 | ```python 225 | torch.nn.functional.relu(input, inplace=False) 226 | ``` 227 | 228 | ```python 229 | torch.nn.functional.hardtanh(input, min_val=-1.0, max_val=1.0, inplace=False) 230 | ``` 231 | 232 | ```python 233 | torch.nn.functional.relu6(input, inplace=False) 234 | ``` 235 | 236 | ```python 237 | torch.nn.functional.elu(input, alpha=1.0, inplace=False) 238 | ``` 239 | 240 | ```python 241 | torch.nn.functional.leaky_relu(input, negative_slope=0.01, inplace=False) 242 | ``` 243 | 244 | ```python 245 | torch.nn.functional.prelu(input, weight) 246 | ``` 247 | 248 | ```python 249 | torch.nn.functional.rrelu(input, lower=0.125, upper=0.3333333333333333, training=False, inplace=False) 250 | ``` 251 | 252 | ```python 253 | torch.nn.functional.logsigmoid(input) 254 | ``` 255 | 256 | ```python 257 | torch.nn.functional.hardshrink(input, lambd=0.5) 258 | ``` 259 | 260 | ```python 261 | torch.nn.functional.tanhshrink(input) 262 | ``` 263 | 264 | ```python 265 | torch.nn.functional.softsign(input) 266 | ``` 267 | 268 | ```python 269 | torch.nn.functional.softplus(input, beta=1, threshold=20) 270 | ``` 271 | 272 | ```python 273 | torch.nn.functional.softmin(input) 274 | ``` 275 | 276 | ```python 277 | torch.nn.functional.softmax(input) 278 | ``` 279 | 280 | ```python 281 | torch.nn.functional.softshrink(input, lambd=0.5) 282 | ``` 283 | 284 | ```python 285 | torch.nn.functional.log_softmax(input) 286 | ``` 287 | 288 | ```python 289 | torch.nn.functional.tanh(input) 290 | ``` 291 | 292 | ```python 293 | torch.nn.functional.sigmoid(input) 294 | ``` 295 | 296 | ## Normalization 函数 297 | ```python 298 | torch.nn.functional.batch_norm(input, running_mean, running_var, weight=None, bias=None, training=False, momentum=0.1, eps=1e-05) 299 | ``` 300 | 301 | ## 线性函数 302 | 303 | ```python 304 | torch.nn.functional.linear(input, weight, bias=None) 305 | ``` 306 | 307 | ## Dropout 函数 308 | 309 | ```python 310 | torch.nn.functional.dropout(input, p=0.5, training=False, inplace=False) 311 | ``` 312 | 313 | ## 距离函数(Distance functions) 314 | 315 | ```python 316 | torch.nn.functional.pairwise_distance(x1, x2, p=2, eps=1e-06) 317 | ``` 318 | 319 | 计算向量v1、v2之间的距离(成次或者成对,意思是可以计算多个,可以参看后面的参数) 320 | $$ 321 | \left \| x \right \|_{p}:=\left ( \sum_{i=1}^{N}\left | x_{i}^{p} \right | \right )^{1/p} 322 | $$ 323 | **参数:** 324 | 325 | * x1:第一个输入的张量 326 | * x2:第二个输入的张量 327 | * p:矩阵范数的维度。默认值是2,即二范数。 328 | 329 | **规格:** 330 | 331 | - 输入:(N,D)其中D等于向量的维度 332 | - 输出:(N,1) 333 | 334 | **例子:** 335 | 336 | ```python 337 | >>> input1 = autograd.Variable(torch.randn(100, 128)) 338 | >>> input2 = autograd.Variable(torch.randn(100, 128)) 339 | >>> output = F.pairwise_distance(input1, input2, p=2) 340 | >>> output.backward() 341 | ``` 342 | 343 | ## 损失函数(Loss functions) 344 | 345 | ```python 346 | torch.nn.functional.nll_loss(input, target, weight=None, size_average=True) 347 | ``` 348 | 负的log likelihood损失函数. 详细请看[NLLLoss](...). 349 | 350 | **参数:** 351 | - **input** - (N,C) C 是类别的个数 352 | - **target** - (N) 其大小是 0 <= targets[i] <= C-1 353 | - **weight** (Variable, optional) – 一个可手动指定每个类别的权重。如果给定的话,必须是大小为nclasses的Variable 354 | - **size_average** (bool, optional) – 默认情况下,是``mini-batch``loss的平均值,然而,如果size_average=False,则是``mini-batch``loss的总和。 355 | 356 | 357 | **Variables:** 358 | - **weight** – 对于constructor而言,每一类的权重作为输入 359 | 360 | ```python 361 | torch.nn.functional.kl_div(input, target, size_average=True) 362 | ``` 363 | KL 散度损失函数,详细请看[KLDivLoss](...) 364 | 365 | **参数:** 366 | - **input** – 任意形状的 Variable 367 | - **target** – 与输入相同形状的 Variable 368 | - **size_average** – 如果为TRUE,loss则是平均值,需要除以输入 tensor 中 element 的数目 369 | 370 | ```python 371 | torch.nn.functional.cross_entropy(input, target, weight=None, size_average=True) 372 | ``` 373 | 该函数使用了 log_softmax 和 nll_loss,详细请看[CrossEntropyLoss](...) 374 | 375 | **参数:** 376 | - **input** - (N,C) 其中,C 是类别的个数 377 | - **target** - (N) 其大小是 0 <= targets[i] <= C-1 378 | - **weight** (Variable, optional) – 一个可手动指定每个类别的权重。如果给定的话,必须是大小为nclasses的Variable 379 | - **size_average** (bool, optional) – 默认情况下,是``mini-batch``loss的平均值,然而,如果size_average=False,则是``mini-batch``loss的总和。 380 | 381 | ```python 382 | torch.nn.functional.binary_cross_entropy(input, target, weight=None, size_average=True) 383 | ``` 384 | 该函数计算了输出与target之间的二进制交叉熵,详细请看[BCELoss](...) 385 | 386 | **参数:** 387 | - **input** – 任意形状的 Variable 388 | - **target** – 与输入相同形状的 Variable 389 | - **weight** (Variable, optional) – 一个可手动指定每个类别的权重。如果给定的话,必须是大小为nclasses的Variable 390 | - **size_average** (bool, optional) – 默认情况下,是``mini-batch``loss的平均值,然而,如果size_average=False,则是``mini-batch``loss的总和。 391 | 392 | ```python 393 | torch.nn.functional.smooth_l1_loss(input, target, size_average=True) 394 | ``` 395 | 396 | 397 | ## Vision functions 398 | ### torch.nn.functional.pixel_shuffle(input, upscale_factor)[source] 399 | 400 | 将形状为`[*, C*r^2, H, W]`的`Tensor`重新排列成形状为`[C, H*r, W*r]`的Tensor. 401 | 402 | 详细请看[PixelShuffle](..). 403 | 404 | 形参说明: 405 | - input (Variable) – 输入 406 | - upscale_factor (int) – 增加空间分辨率的因子. 407 | 408 | 例子: 409 | ```python 410 | ps = nn.PixelShuffle(3) 411 | input = autograd.Variable(torch.Tensor(1, 9, 4, 4)) 412 | output = ps(input) 413 | print(output.size()) 414 | torch.Size([1, 1, 12, 12]) 415 | ``` 416 | ### torch.nn.functional.pad(input, pad, mode='constant', value=0)[source] 417 | 418 | 填充`Tensor`. 419 | 420 | 目前为止,只支持`2D`和`3D`填充. 421 | Currently only 2D and 3D padding supported. 422 | 当输入为`4D Tensor`的时候,`pad`应该是一个4元素的`tuple (pad_l, pad_r, pad_t, pad_b )` ,当输入为`5D Tensor`的时候,`pad`应该是一个6元素的`tuple (pleft, pright, ptop, pbottom, pfront, pback)`. 423 | 424 | 形参说明: 425 | 426 | - input (Variable) – 4D 或 5D `tensor` 427 | 428 | - pad (tuple) – 4元素 或 6-元素 `tuple` 429 | 430 | - mode – ‘constant’, ‘reflect’ or ‘replicate’ 431 | 432 | - value – 用于`constant padding` 的值. 433 | -------------------------------------------------------------------------------- /docs/package_references/Tensor.md: -------------------------------------------------------------------------------- 1 | # torch.Tensor 2 | `torch.Tensor`是一种包含单一数据类型元素的多维矩阵。 3 | 4 | Torch定义了七种CPU tensor类型和八种GPU tensor类型: 5 | 6 | | Data tyoe | CPU tensor | GPU tensor| 7 | | :--- | :--- | :--- | 8 | | 32-bit floating point | `torch.FloatTensor` | `torch.cuda.FloatTensor` | 9 | | 64-bit floating point | `torch.DoubleTensor` | `torch.cuda.DoubleTensor` | 10 | | 16-bit floating point | N/A | `torch.cuda.HalfTensor` | 11 | | 8-bit integer (unsigned) | `torch.ByteTensor` | `torch.cuda.ByteTensor` | 12 | | 8-bit integer (signed) | `torch.CharTensor` | `torch.cuda.CharTensor` | 13 | | 16-bit integer (signed) | `torch.ShortTensor` | `torch.cuda.ShortTensor` | 14 | | 32-bit integer (signed) | `torch.IntTensor` | `torch.cuda.IntTensor` | 15 | | 64-bit integer (signed) | `torch.LongTensor` | `torch.cuda.LongTensor` | 16 | 17 | `torch.Tensor`是默认的tensor类型(`torch.FloatTensor`)的简称。 18 | 19 | 一个张量tensor可以从Python的`list`或序列构建: 20 | ```python 21 | >>> torch.FloatTensor([[1, 2, 3], [4, 5, 6]]) 22 | 1 2 3 23 | 4 5 6 24 | [torch.FloatTensor of size 2x3] 25 | ``` 26 | 一个空张量tensor可以通过规定其大小来构建: 27 | 28 | ```python 29 | >>> torch.IntTensor(2, 4).zero_() 30 | 0 0 0 0 31 | 0 0 0 0 32 | [torch.IntTensor of size 2x4] 33 | ``` 34 | 35 | 可以用python的索引和切片来获取和修改一个张量tensor中的内容: 36 | 37 | ```python 38 | >>> x = torch.FloatTensor([[1, 2, 3], [4, 5, 6]]) 39 | >>> print(x[1][2]) 40 | 6.0 41 | >>> x[0][1] = 8 42 | >>> print(x) 43 | 1 8 3 44 | 4 5 6 45 | [torch.FloatTensor of size 2x3] 46 | ``` 47 | 48 | 每一个张量tensor都有一个相应的`torch.Storage`用来保存其数据。类tensor提供了一个存储的多维的、横向视图,并且定义了在数值运算。 49 | 50 | >**!注意:** 51 | >会改变tensor的函数操作会用一个下划线后缀来标示。比如,`torch.FloatTensor.abs_()`会在原地计算绝对值,并返回改变后的tensor,而`tensor.FloatTensor.abs()`将会在一个新的tensor中计算结果。 52 | 53 | 54 | ```python 55 | class torch.Tensor 56 | class torch.Tensor(*sizes) 57 | class torch.Tensor(size) 58 | class torch.Tensor(sequence) 59 | class torch.Tensor(ndarray) 60 | class torch.Tensor(tensor) 61 | class torch.Tensor(storage) 62 | ``` 63 | 根据可选择的大小和数据新建一个tensor。 64 | 如果没有提供参数,将会返回一个空的零维张量。如果提供了`numpy.ndarray`,`torch.Tensor`或`torch.Storage`,将会返回一个有同样参数的tensor.如果提供了python序列,将会从序列的副本创建一个tensor。 65 | 66 | #### abs() → Tensor 67 | 请查看`torch.abs()` 68 | #### abs_() → Tensor 69 | `abs()`的in-place运算形式 70 | #### acos() → Tensor 71 | 请查看`torch.acos()` 72 | #### acos_() → Tensor 73 | `acos()`的in-place运算形式 74 | #### add(_value_) 75 | 请查看`torch.add()` 76 | #### add_(_value_) 77 | `add()`的in-place运算形式 78 | #### addbmm(_beta=1, mat, alpha=1, batch1, batch2_) → Tensor 79 | 请查看`torch.addbmm()` 80 | #### addbmm_(_beta=1, mat, alpha=1, batch1, batch2_) → Tensor 81 | `addbmm()`的in-place运算形式 82 | #### addcdiv(_value=1, tensor1, tensor2_) → Tensor 83 | 请查看`torch.addcdiv()` 84 | #### addcdiv_(_value=1, tensor1, tensor2_) → Tensor 85 | `addcdiv()`的in-place运算形式 86 | #### addcmul(_value=1, tensor1, tensor2_) → Tensor 87 | 请查看`torch.addcmul()` 88 | #### addcmul_(_value=1, tensor1, tensor2_) → Tensor 89 | `addcmul()`的in-place运算形式 90 | #### addmm(_beta=1, mat, alpha=1, mat1, mat2_) → Tensor 91 | 请查看`torch.addmm()` 92 | #### addmm_(_beta=1, mat, alpha=1, mat1, mat2_) → Tensor 93 | `addmm()`的in-place运算形式 94 | #### addmv(_beta=1, tensor, alpha=1, mat, vec_) → Tensor 95 | 请查看`torch.addmv()` 96 | #### addmv_(_beta=1, tensor, alpha=1, mat, vec_) → Tensor 97 | `addmv()`的in-place运算形式 98 | #### addr(_beta=1, alpha=1, vec1, vec2_) → Tensor 99 | 请查看`torch.addr()` 100 | #### addr_(_beta=1, alpha=1, vec1, vec2_) → Tensor 101 | `addr()`的in-place运算形式 102 | #### apply_(_callable_) → Tensor 103 | 将函数`callable`作用于tensor中每一个元素,并将每个元素用`callable`函数返回值替代。 104 | >__!注意:__ 105 | 该函数只能在CPU tensor中使用,并且不应该用在有较高性能要求的代码块。 106 | #### asin() → Tensor 107 | 请查看`torch.asin()` 108 | #### asin_() → Tensor 109 | `asin()`的in-place运算形式 110 | #### atan() → Tensor 111 | 请查看`torch.atan()` 112 | #### atan2() → Tensor 113 | 请查看`torch.atan2()` 114 | #### atan2_() → Tensor 115 | `atan2()`的in-place运算形式 116 | #### atan_() → Tensor 117 | `atan()`的in-place运算形式 118 | #### baddbmm(_beta=1, alpha=1, batch1, batch2_) → Tensor 119 | 请查看`torch.baddbmm()` 120 | #### baddbmm_(_beta=1, alpha=1, batch1, batch2_) → Tensor 121 | `baddbmm()`的in-place运算形式 122 | #### bernoulli() → Tensor 123 | 请查看`torch.bernoulli()` 124 | #### bernoulli_() → Tensor 125 | `bernoulli()`的in-place运算形式 126 | #### bmm(_batch2_) → Tensor 127 | 请查看`torch.bmm()` 128 | #### byte() → Tensor 129 | 将tensor改为byte类型 130 | #### bmm(_median=0, sigma=1, *, generator=None_) → Tensor 131 | 将tensor中元素用柯西分布得到的数值填充: 132 | $$ 133 | P(x)={\frac1 \pi} {\frac \sigma {(x-median)^2 + \sigma^2}} 134 | $$ 135 | #### ceil() → Tensor 136 | 请查看`torch.ceil()` 137 | #### ceil_() → Tensor 138 | `ceil()`的in-place运算形式 139 | #### char() 140 | 将tensor元素改为char类型 141 | #### chunk(_n_chunks, dim=0_) → Tensor 142 | 将tensor分割为tensor元组. 143 | 请查看`torch.chunk()` 144 | #### clamp(_min, max_) → Tensor 145 | 请查看`torch.clamp()` 146 | #### clamp_(_min, max_) → Tensor 147 | `clamp()`的in-place运算形式 148 | #### clone() → Tensor 149 | 返回与原tensor有相同大小和数据类型的tensor 150 | #### contiguous() → Tensor 151 | 返回一个内存连续的有相同数据的tensor,如果原tensor内存连续则返回原tensor 152 | #### copy_(_src, async=False_) → Tensor 153 | 将`src`中的元素复制到tensor中并返回这个tensor。 154 | 两个tensor应该有相同数目的元素,可以是不同的数据类型或存储在不同的设备上。 155 | __参数:__ 156 | - __src__ (_Tensor_)-复制的源tensor 157 | - __async__ (_bool_)-如果为True并且复制是在CPU和GPU之间进行的,则复制后的拷贝可能会与源信息异步,对于其他类型的复制操作则该参数不会发生作用。 158 | 159 | #### cos() → Tensor 160 | 请查看`torch.cos()` 161 | #### cos_() → Tensor 162 | `cos()`的in-place运算形式 163 | #### cosh() → Tensor 164 | 请查看`torch.cosh()` 165 | #### cosh_() → Tensor 166 | `cosh()`的in-place运算形式 167 | #### cpu() → Tensor 168 | 如果在CPU上没有该tensor,则会返回一个CPU的副本 169 | #### cross(_other, dim=-1_) → Tensor 170 | 请查看`torch.cross()` 171 | #### cuda(device=None, async=False) 172 | 返回此对象在CPU内存中的一个副本 173 | 如果对象已近存在与CUDA存储中并且在正确的设备上,则不会进行复制并返回原始对象。 174 | 175 | __参数:__ 176 | - __device__(_int_)-目的GPU的id,默认为当前的设备。 177 | - __async__(_bool_)-如果为True并且资源在固定内存中,则复制的副本将会与原始数据异步。否则,该参数没有意义。 178 | #### cumprod(_dim_) → Tensor 179 | 请查看`torch.cumprod()` 180 | #### cumsum(_dim_) → Tensor 181 | 请查看`torch.cumsum()` 182 | #### data_ptr() → int 183 | 返回tensor第一个元素的地址 184 | #### diag(_diagonal=0_) → Tensor 185 | 请查看`torch.diag()` 186 | #### dim() → int 187 | 返回tensor的维数 188 | #### dist(_other, p=2_) → Tensor 189 | 请查看`torch.dist()` 190 | #### div(_value_) 191 | 请查看`torch.div()` 192 | #### div_(_value_) 193 | `div()`的in-place运算形式 194 | #### dot(_tensor2_) → float 195 | 请查看`torch.dot()` 196 | #### double() 197 | 将该tensor投射为double类型 198 | #### eig(_eigenvectors=False_) -> (_Tensor, Tensor_) 199 | 请查看`torch.eig()` 200 | #### element_size() → int 201 | 返回单个元素的字节大小。 202 | 例: 203 | ```python 204 | >>> torch.FloatTensor().element_size() 205 | 4 206 | >>> torch.ByteTensor().element_size() 207 | 1 208 | ``` 209 | #### eq(_other_) → Tensor 210 | 请查看`torch.eq()` 211 | #### eq_(_other_) → Tensor 212 | `eq()`的in-place运算形式 213 | #### equal(_other_) → bool 214 | 请查看`torch.equal()` 215 | #### exp() → Tensor 216 | 请查看`torch.exp()` 217 | #### exp_() → Tensor 218 | `exp()`的in-place运算形式 219 | #### expand(*sizes) 220 | 返回tensor的一个新视图,单个维度扩大为更大的尺寸。 221 | tensor也可以扩大为更高维,新增加的维度将附在前面。 222 | 扩大tensor不需要分配新内存,只是仅仅新建一个tensor的视图,其中通过将`stride`设为0,一维将会扩展位更高维。任何一个一维的在不分配新内存情况下可扩展为任意的数值。 223 | 224 | __参数:__ 225 | - __sizes__(_torch.Size or int..._)-需要扩展的大小 226 | 227 | __例:__ 228 | ```python 229 | >>> x = torch.Tensor([[1], [2], [3]]) 230 | >>> x.size() 231 | torch.Size([3, 1]) 232 | >>> x.expand(3, 4) 233 | 1 1 234 | 1 1 235 | 2 2 2 2 236 | 3 3 3 3 237 | [torch.FloatTensor of size 3x4] 238 | ``` 239 | #### expand_as(_tensor_) 240 | 将tensor扩展为参数tensor的大小。 241 | 该操作等效与: 242 | ```python 243 | self.expand(tensor.size()) 244 | ``` 245 | #### exponential_(_lambd=1, *, generator=None_) $to$ Tensor 246 | 将该tensor用指数分布得到的元素填充: 247 | $$ 248 | P(x)= \lambda e^{- \lambda x} 249 | $$ 250 | #### fill_(_value_) → Tensor 251 | 将该tensor用指定的数值填充 252 | #### float() 253 | 将tensor投射为float类型 254 | #### floor() → Tensor 255 | 请查看`torch.floor()` 256 | #### floor_() → Tensor 257 | `floor()`的in-place运算形式 258 | #### fmod(_divisor_) → Tensor 259 | 请查看`torch.fmod()` 260 | #### fmod_(_divisor_) → Tensor 261 | `fmod()`的in-place运算形式 262 | #### frac() → Tensor 263 | 请查看`torch.frac()` 264 | #### frac_() → Tensor 265 | `frac()`的in-place运算形式 266 | #### gather(_dim, index_) → Tensor 267 | 请查看`torch.gather()` 268 | #### ge(_other_) → Tensor 269 | 请查看`torch.ge()` 270 | #### ge_(_other_) → Tensor 271 | `ge()`的in-place运算形式 272 | #### gels(_A_) → Tensor 273 | 请查看`torch.gels()` 274 | #### geometric_(_p, *, generator=None_) → Tensor 275 | 将该tensor用几何分布得到的元素填充: 276 | $$ 277 | P(X=k)= (1-p)^{k-1}p 278 | $$ 279 | #### geqrf() -> (_Tensor, Tensor_) 280 | 请查看`torch.geqrf()` 281 | #### ger(_vec2_) → Tensor 282 | 请查看`torch.ger()` 283 | #### gesv(_A_) → Tensor, Tensor 284 | 请查看`torch.gesv()` 285 | #### gt(_other_) → Tensor 286 | 请查看`torch.gt()` 287 | #### gt_(_other_) → Tensor 288 | `gt()`的in-place运算形式 289 | #### half() 290 | 将tensor投射为半精度浮点类型 291 | #### histc(_bins=100, min=0, max=0_) → Tensor 292 | 请查看`torch.histc()` 293 | #### index(_m_) → Tensor 294 | 用一个二进制的掩码或沿着一个给定的维度从tensor中选取元素。`tensor.index(m)`与`tensor[m]`完全相同。 295 | 296 | __参数:__ 297 | - __m__(_int or Byte Tensor or slice_)-用来选取元素的维度或掩码 298 | #### index_add_(_dim, index, tensor_) → Tensor 299 | 按参数index中的索引数确定的顺序,将参数tensor中的元素加到原来的tensor中。参数tensor的尺寸必须严格地与原tensor匹配,否则会发生错误。 300 | 301 | __参数:__ 302 | - __dim__(_int_)-索引index所指向的维度 303 | - __index__(_LongTensor_)-需要从tensor中选取的指数 304 | - __tensor__(_Tensor_)-含有相加元素的tensor 305 | 306 | __例:__ 307 | ```python 308 | >>> x = torch.Tensor([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) 309 | >>> t = torch.Tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 310 | >>> index = torch.LongTensor([0, 2, 1]) 311 | >>> x.index_add_(0, index, t) 312 | >>> x 313 | 2 3 4 314 | 8 9 10 315 | 5 6 7 316 | [torch.FloatTensor of size 3x3] 317 | ``` 318 | #### index_copy_(_dim, index, tensor_) → Tensor 319 | 按参数index中的索引数确定的顺序,将参数tensor中的元素复制到原来的tensor中。参数tensor的尺寸必须严格地与原tensor匹配,否则会发生错误。 320 | 321 | __参数:__ 322 | - __dim__ (_int_)-索引index所指向的维度 323 | - __index__ (_LongTensor_)-需要从tensor中选取的指数 324 | - __tensor__ (_Tensor_)-含有被复制元素的tensor 325 | 326 | __例:__ 327 | ```python 328 | >>> x = torch.Tensor(3, 3) 329 | >>> t = torch.Tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 330 | >>> index = torch.LongTensor([0, 2, 1]) 331 | >>> x.index_copy_(0, index, t) 332 | >>> x 333 | 1 2 3 334 | 7 8 9 335 | 4 5 6 336 | [torch.FloatTensor of size 3x3] 337 | ``` 338 | #### index_fill_(_dim, index, val_) → Tensor 339 | 按参数index中的索引数确定的顺序,将原tensor用参数`val`值填充。 340 | 341 | __参数:__ 342 | - __dim__ (_int_)-索引index所指向的维度 343 | - __index__ (_LongTensor_)-索引 344 | - __val__ (_Tensor_)-填充的值 345 | 346 | __例:__ 347 | ```python 348 | >>> x = torch.Tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 349 | >>> index = torch.LongTensor([0, 2]) 350 | >>> x.index_fill_(0, index, -1) 351 | >>> x 352 | -1 2 -1 353 | -1 5 -1 354 | -1 8 -1 355 | [torch.FloatTensor of size 3x3] 356 | ``` 357 | #### index_select(_dim, index_) → Tensor 358 | 请查看`torch.index_select()` 359 | #### int() 360 | 将该tensor投射为int类型 361 | #### inverse() → Tensor 362 | 请查看`torch.inverse()` 363 | #### is_contiguous() → bool 364 | 如果该tensor在内存中是连续的则返回True。 365 | #### is_cuda 366 | #### is_pinned() 367 | 如果该tensor在固定内内存中则返回True 368 | #### is_set_to(_tensor_) → bool 369 | 如果此对象引用与Torch C API相同的`THTensor`对象作为给定的张量,则返回True。 370 | #### is_signed() 371 | #### kthvalue(_k, dim=None_) -> (_Tensor, LongTensor_) 372 | 请查看`torch.kthvalue()` 373 | #### le(_other_) → Tensor 374 | 请查看`torch.le()` 375 | #### le_(_other_) → Tensor 376 | `le()`的in-place运算形式 377 | #### lerp(_start, end, weight_) 378 | 请查看`torch.lerp()` 379 | #### lerp_(*start, end, weight*) → Tensor 380 | `lerp()`的in-place运算形式 381 | #### log() → Tensor 382 | 请查看`torch.log()` 383 | #### loglp() → Tensor 384 | 请查看`torch.loglp()` 385 | #### loglp_() → Tensor 386 | `loglp()`的in-place运算形式 387 | #### log_()→ Tensor 388 | `log()`的in-place运算形式 389 | #### log_normal_(*mwan=1, std=2, *, gegnerator=None*) 390 | 将该tensor用均值为$\mu$,标准差为$\sigma$的对数正态分布得到的元素填充。要注意`mean`和`stdv`是基本正态分布的均值和标准差,不是返回的分布: 391 | $$ 392 | P(X)= \frac {1} {x \sigma \sqrt {2 \pi}}e^{- \frac {(lnx- \mu)^2} {2 \sigma^2}} 393 | $$ 394 | #### long() 395 | 将tensor投射为long类型 396 | #### lt(*other*) → Tensor 397 | 请查看`torch.lt()` 398 | #### lt_(*other*) → Tensor 399 | `lt()`的in-place运算形式 400 | #### map_(*tensor, callable*) 401 | 将`callable`作用于本tensor和参数tensor中的每一个元素,并将结果存放在本tensor中。`callable`应该有下列标志: 402 | ```pyhton 403 | def callable(a, b) -> number 404 | ``` 405 | #### masked_copy_(*mask, source*) 406 | 将`mask`中值为1元素对应的`source`中位置的元素复制到本tensor中。`mask`应该有和本tensor相同数目的元素。`source`中元素的个数最少为`mask`中值为1的元素的个数。 407 | 408 | __参数:__ 409 | - __mask__ (*ByteTensor*)-二进制掩码 410 | - __source__ (*Tensor*)-复制的源tensor 411 | 412 | >__注意:__ 413 | >`mask`作用于`self`自身的tensor,而不是参数中的`source`。 414 | #### masked_fill_(*mask, value*) 415 | 在`mask`值为1的位置处用`value`填充。`mask`的元素个数需和本tensor相同,但尺寸可以不同。 416 | 417 | __参数:__ 418 | - __mask__ (*ByteTensor*)-二进制掩码 419 | - __value__ (*Tensor*)-用来填充的值 420 | #### masked_select(*mask*) → Tensor 421 | 请查看`torch.masked_select()` 422 | #### max(*dim=None*) -> *float or(Tensor, Tensor)* 423 | 请查看`torch.max()` 424 | #### mean(*dim=None*) -> *float or(Tensor, Tensor)* 425 | 请查看`torch.mean()` 426 | #### median(*dim=-1, value=None, indices=None*) -> *(Tensor, LongTensor)* 427 | 请查看`torch.median()` 428 | #### min(*dim=None*) -> *float or(Tensor, Tensor)* 429 | 请查看`torch.min()` 430 | #### mm(*mat2*) → Tensor 431 | 请查看`torch.mm()` 432 | #### mode(*dim=-1, value=None, indices=None*) -> *(Tensor, LongTensor)* 433 | 请查看`torch.mode()` 434 | #### mul(*value*) → Tensor 435 | 请查看`torch.mul()` 436 | #### mul_(*value*) 437 | `mul()`的in-place运算形式 438 | #### multinomial(*num_samples, replacement=False, *, generator=None*) → Tensor 439 | 请查看`torch.multinomial()` 440 | #### mv(*vec*) → Tensor 441 | 请查看`torch.mv()` 442 | #### narrow(*dimension, start, length*) → Te 443 | 返回一个本tensor经过缩小后的tensor。维度`dim`缩小范围是`start`到`start+length`。原tensor与返回的tensor共享相同的底层内存。 444 | 445 | __参数:__ 446 | - __dimension__ (*int*)-需要缩小的维度 447 | - __start__ (*int*)-起始维度 448 | - __length__ (*int*)- 449 | 450 | __例:__ 451 | ```python 452 | >>> x = torch.Tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 453 | >>> x.narrow(0, 0, 2) 454 | 1 2 3 455 | 4 5 6 456 | [torch.FloatTensor of size 2x3] 457 | >>> x.narrow(1, 1, 2) 458 | 2 3 459 | 5 6 460 | 8 9 461 | [torch.FloatTensor of size 3x2] 462 | ``` 463 | #### ndimension() → int 464 | `dim()`的另一种表示。 465 | #### ne(*other*) → Tensor 466 | 请查看`torch.ne()` 467 | #### ne_(*other*) → Tensor 468 | `ne()`的in-place运算形式 469 | #### neg() → Tensor 470 | 请查看`torch.neg()` 471 | #### neg_() → Tensor 472 | `neg()`的in-place运算形式 473 | #### nelement() → int 474 | `numel()`的另一种表示 475 | #### new(_*args, **kwargs_) 476 | 构建一个有相同数据类型的tensor 477 | #### nonezero() → LongTensor 478 | 请查看`torch.nonezero() 479 | #### norm(*p=2*) → float 480 | 请查看`torch.norm() 481 | #### normal_(*mean=0, std=1, *, gengerator=None*) 482 | 将tensor用均值为`mean`和标准差为`std`的正态分布填充。 483 | #### numel() → int 484 | 请查看`numel()` 485 | #### numpy() → ndarray 486 | 将该tensor以NumPy的形式返回`ndarray`,两者共享相同的底层内存。原tensor改变后会相应的在`ndarray`有反映,反之也一样。 487 | #### orgqr(*input2*) → Tensor 488 | 请查看`torch.orgqr()` 489 | #### ormqr(*input2, input3, left=True, transpose=False*) → Tensor 490 | 请查看`torch.ormqr()` 491 | #### permute(*dims*) 492 | 将tensor的维度换位。 493 | 494 | __参数:__ 495 | - __*dims__ (*int..*)-换位顺序 496 | 497 | __例:__ 498 | ```python 499 | >>> x = torch.randn(2, 3, 5) 500 | >>> x.size() 501 | torch.Size([2, 3, 5]) 502 | >>> x.permute(2, 0, 1).size() 503 | torch.Size([5, 2, 3]) 504 | ``` 505 | #### pin_memory() 506 | 如果原来没有在固定内存中,则将tensor复制到固定内存中。 507 | #### potrf(*upper=True*) → Tensor 508 | 请查看`torch.potrf()` 509 | #### potri(*upper=True*) → Tensor 510 | 请查看`torch.potri()` 511 | #### potrs(*input2, upper=True*) → Tensor 512 | 请查看`torch.potrs()` 513 | #### pow(*exponent*) 514 | 请查看`torch.pow()` 515 | #### pow_() 516 | `pow()`的in-place运算形式 517 | #### prod()) → float 518 | 请查看`torch.prod()` 519 | #### pstrf(*upper=True, tol=-1*) -> (*Tensor, IntTensor*) 520 | 请查看`torch.pstrf()` 521 | #### qr()-> (*Tensor, IntTensor*) 522 | 请查看`torch.qr()` 523 | #### random_(_from=0, to=None, *, generator=None_) 524 | 将tensor用从在[from, to-1]上的正态分布或离散正态分布取样值进行填充。如果没有明确说明,则填充值仅由本tensor的数据类型限定。 525 | #### reciprocal() → Tensor 526 | 请查看`torch.reciprocal()` 527 | #### reciprocal_() → Tensor 528 | `reciprocal()`的in-place运算形式 529 | #### remainder(*divisor*) → Tensor 530 | 请查看`torch.remainder()` 531 | #### remainder_(*divisor*) → Tensor 532 | `remainder()`的in-place运算形式 533 | #### renorm(*p, dim, maxnorm*) → Tensor 534 | 请查看`torch.renorm()` 535 | #### renorm_(*p, dim, maxnorm*) → Tensor 536 | `renorm()`的in-place运算形式 537 | #### repeat(_*sizes_) 538 | 沿着指定的维度重复tensor。 539 | 不同于`expand()`,本函数复制的是tensor中的数据。 540 | 541 | __参数:__ 542 | - __*sizes__ (_torch.Size ot int..._)-沿着每一维重复的次数 543 | 544 | __例:__ 545 | ```python 546 | >>> x = torch.Tensor([1, 2, 3]) 547 | >>> x.repeat(4, 2) 548 | 1 2 3 1 2 3 549 | 1 2 3 1 2 3 550 | 1 2 3 1 2 3 551 | 1 2 3 1 2 3 552 | [torch.FloatTensor of size 4x6] 553 | >>> x.repeat(4, 2, 1).size() 554 | torch.Size([4, 2, 3]) 555 | ``` 556 | #### resize_(_*sizes_) 557 | 将tensor的大小调整为指定的大小。如果元素个数比当前的内存大小大,就将底层存储大小调整为与新元素数目一致的大小。如果元素个数比当前内存小,则底层存储不会被改变。原来tensor中被保存下来的元素将保持不变,但新内存将不会被初始化。 558 | 559 | __参数:__ 560 | - __*sizes__ (_torch.Size or int..._)-需要调整的大小 561 | 562 | __例:__ 563 | ```python 564 | >>> x = torch.Tensor([[1, 2], [3, 4], [5, 6]]) 565 | >>> x.resize_(2, 2) 566 | >>> x 567 | 1 2 568 | 3 4 569 | [torch.FloatTensor of size 2x2] 570 | ``` 571 | #### resize_as_(_tensor_) 572 | 将本tensor的大小调整为与参数中的tensor相同的大小。等效于: 573 | ```python 574 | self.resize_(tensor.size()) 575 | ``` 576 | #### round() → Tensor 577 | 请查看`torch.round()` 578 | #### round_() → Tensor 579 | `round()`的in-place运算形式 580 | #### rsqrt() → Tensor 581 | 请查看`torch.rsqrt()` 582 | #### rsqrt_() → Tensor 583 | `rsqrt()`的in-place运算形式 584 | #### scatter_(*input, dim, index, src*) → Tensor 585 | 将`src`中的所有值按照`index`确定的索引写入本tensor中。其中索引是根据给定的dimension,dim按照`gather()`描述的规则来确定。 586 | 587 | 注意,index的值必须是在_0_到_(self.size(dim)-1)_之间, 588 | 589 | __参数:__ 590 | - __input__ (_Tensor_)-源tensor 591 | - __dim__ (_int_)-索引的轴向 592 | - __index__ (_LongTensor_)-散射元素的索引指数 593 | - __src__ (_Tensor or float_)-散射的源元素 594 | 595 | __例:__ 596 | ```python 597 | >>> x = torch.rand(2, 5) 598 | >>> x 599 | 600 | 0.4319 0.6500 0.4080 0.8760 0.2355 601 | 0.2609 0.4711 0.8486 0.8573 0.1029 602 | [torch.FloatTensor of size 2x5] 603 | 604 | >>> torch.zeros(3, 5).scatter_(0, torch.LongTensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]]), x) 605 | 606 | 0.4319 0.4711 0.8486 0.8760 0.2355 607 | 0.0000 0.6500 0.0000 0.8573 0.0000 608 | 0.2609 0.0000 0.4080 0.0000 0.1029 609 | [torch.FloatTensor of size 3x5] 610 | 611 | >>> z = torch.zeros(2, 4).scatter_(1, torch.LongTensor([[2], [3]]), 1.23) 612 | >>> z 613 | 614 | 0.0000 0.0000 1.2300 0.0000 615 | 0.0000 0.0000 0.0000 1.2300 616 | [torch.FloatTensor of size 2x4] 617 | ``` 618 | #### select(*dim, index*) → Tensor or number 619 | 按照index中选定的维度将tensor切片。如果tensor是一维的,则返回一个数字。否则,返回给定维度已经被移除的tensor。 620 | 621 | __参数:__ 622 | - __dim__ (_int_)-切片的维度 623 | - __index__ (_int_)-用来选取的索引 624 | 625 | >__!注意:__ 626 | `select()`等效于切片。例如,`tensor.select(0, index)`等效于`tensor[index]`,`tensor.select(2, index)`等效于`tensor[:, :, index]`. 627 | #### set(_source=None, storage_offset=0, size=None, stride=None_) 628 | 设置底层内存,大小和步长。如果`tensor`是一个tensor,则将会与本tensor共享底层内存并且有相同的大小和步长。改变一个tensor中的元素将会反映在另一个tensor。 629 | 如果`source`是一个`Storage`,则将设置底层内存,偏移量,大小和步长。 630 | 631 | __参数:__ 632 | - __source__ (_Tensor or Storage_)-用到的tensor或内存 633 | - __storage_offset__ (_int_)-内存的偏移量 634 | - __size__ (_torch.Size_)-需要的大小,默认为源tensor的大小。 635 | - __stride__(_tuple_)-需要的步长,默认为C连续的步长。 636 | #### share_memory_() 637 | 将底层内存移到共享内存中。 638 | 如果底层内存已经在共享内存中是将不进行任何操作。在共享内存中的tensor不能调整大小。 639 | #### short() 640 | 将tensor投射为short类型。 641 | #### sigmoid() → Tensor 642 | 请查看`torch.sigmoid()` 643 | #### sigmoid_() → Tensor 644 | `sidmoid()`的in-place运算形式 645 | #### sign() → Tensor 646 | 请查看`torch.sign()` 647 | #### sign_() → Tensor 648 | `sign()`的in-place运算形式 649 | #### sin() → Tensor 650 | 请查看`torch.sin()` 651 | #### sin_() → Tensor 652 | `sin()`的in-place运算形式 653 | #### sinh() → Tensor 654 | 请查看`torch.sinh()` 655 | #### sinh_() → Tensor 656 | `sinh()`的in-place运算形式 657 | #### size() → torch.Size 658 | 返回tensor的大小。返回的值是`tuple`的子类。 659 | 660 | __例:__ 661 | ```python 662 | >>> torch.Tensor(3, 4, 5).size() 663 | torch.Size([3, 4, 5]) 664 | ``` 665 | #### sort(_dim=None, descending=False_) -> (_Tensor, LongTensor_) 666 | 请查看`torhc.sort()` 667 | #### split(_split_size, dim=0_) 668 | 将tensor分割成tensor数组。 669 | 请查看`torhc.split()` 670 | #### sqrt() → Tensor 671 | 请查看`torch.sqrt()` 672 | #### sqrt_() → Tensor 673 | `sqrt()`的in-place运算形式 674 | #### squeeze(_dim=None_) → Tensor 675 | 请查看`torch.squeeze()` 676 | #### squeeze_(_dim=None_) → Tensor 677 | `squeeze()`的in-place运算形式 678 | #### std() → float 679 | 请查看`torch.std()` 680 | #### storage() → torch.Storage 681 | 返回底层内存。 682 | #### storage_offset() → int 683 | 以储存元素的个数的形式返回tensor在地城内存中的偏移量。 684 | 例: 685 | ```python 686 | >>> x = torch.Tensor([1, 2, 3, 4, 5]) 687 | >>> x.storage_offset() 688 | 0 689 | >>> x[3:].storage_offset() 690 | 3 691 | ``` 692 | #### _classmethod()_ storage_type() 693 | #### stride() → Tensor 694 | 返回tesnor的步长。 695 | #### sub(_value, other_) → Tensor 696 | 从tensor中抽取一个标量或tensor。如果`value`和`other`都是给定的,则在使用之前`other`的每一个元素都会被`value`缩放。 697 | #### sub_(_x_) → Tensor 698 | `sub()`的in-place运算形式 699 | #### sum(_dim=None_) → Tensor 700 | 请查看`torch.sum()` 701 | #### svd(_some=True_) -> (Tensor, Tensor, Tensor) 702 | 请查看`torch.svd()` 703 | #### symeig(_eigenvectors=False, upper=True) -> (Tensor, Tensor) 704 | 请查看`torch.symeig()` 705 | #### t() → Tensor 706 | 请查看`torch.t()` 707 | #### t() → Tensor 708 | `t()`的in-place运算形式 709 | #### tan() → Tensor 710 | 请查看`torch.tan()` 711 | #### tan_() → Tensor 712 | `tan()`的in-place运算形式 713 | #### tanh() → Tensor 714 | 请查看`torch.tanh()` 715 | #### tanh_() → Tensor 716 | `tanh()`的in-place运算形式 717 | #### tolist() 718 | 返回一个tensor的嵌套列表表示。 719 | #### topk(_k, dim=None, largest=True, sorted=True_) -> (Tensor, LongTensor) 720 | 请查看`torch.topk()` 721 | #### trace() → float 722 | 请查看`torch.trace()` 723 | #### transpose(_dim0, dim1_) → Tensor 724 | 请查看`torch.transpose()` 725 | #### transpose(_dim0, dim1_) → Tensor 726 | `transpose()`的in-place运算形式 727 | #### tril(_k=0_) → Tensor 728 | 请查看`torch.tril()` 729 | #### tril_(_k=0_) → Tensor 730 | `tril()`的in-place运算形式 731 | #### triu(_k=0_) → Tensor 732 | 请查看`torch.triu()` 733 | #### triu(_k=0_) → Tensor 734 | `triu()`的in-place运算形式 735 | #### trtrs(_A, upper=True, transpose=False, unitriangular=False_) -> (Tensor, Tensor) 736 | 请查看`torch.trtrs()` 737 | #### trunc() → Tensor 738 | 请查看`torch.trunc()` 739 | #### trunc() → Tensor 740 | `trunc()`的in-place运算形式 741 | #### type(_new_type=None, async=False_) 742 | 将对象投为指定的类型。 743 | 如果已经是正确的类型,则不会进行复制并返回原对象。 744 | 745 | __参数:__ 746 | - __new_type__ (_type or string_)-需要的类型 747 | - __async__ (_bool_)-如果为True,并且源地址在固定内存中,目的地址在GPU或者相反,则会相对于源主异步执行复制。否则,该参数不发挥作用。 748 | #### type_as(_tesnor_) 749 | 将tensor投射为参数给定tensor类型并返回。 750 | 如果tensor已经是正确的类型则不会执行操作。等效于: 751 | ```python 752 | self.type(tensor.type()) 753 | ``` 754 | __参数:__ 755 | - __tensor__ (Tensor):有所需要类型的tensor 756 | #### unfold(_dim, size, step_) → Tensor 757 | 返回一个tensor,其中含有在`dim`维tianchong度上所有大小为`size`的分片。两个分片之间的步长为`step`。 758 | 如果_sizedim_是dim维度的原始大小,则在返回tensor中的维度dim大小是_(sizedim-size)/step+1_ 759 | 维度大小的附加维度将附加在返回的tensor中。 760 | 761 | __参数:__ 762 | - __dim__ (_int_)-需要展开的维度 763 | - __size__ (_int_)-每一个分片需要展开的大小 764 | - __step__ (_int_)-相邻分片之间的步长 765 | 766 | __例:__ 767 | ```python 768 | >>> x = torch.arange(1, 8) 769 | >>> x 770 | 771 | 1 772 | 2 773 | 3 774 | 4 775 | 5 776 | 6 777 | 7 778 | [torch.FloatTensor of size 7] 779 | 780 | >>> x.unfold(0, 2, 1) 781 | 782 | 1 2 783 | 2 3 784 | 3 4 785 | 4 5 786 | 5 6 787 | 6 7 788 | [torch.FloatTensor of size 6x2] 789 | 790 | >>> x.unfold(0, 2, 2) 791 | 792 | 1 2 793 | 3 4 794 | 5 6 795 | [torch.FloatTensor of size 3x2] 796 | ``` 797 | #### uniform_(_from=0, to=1_) → Tensor 798 | 将tensor用从均匀分布中抽样得到的值填充。 799 | #### unsqueeze(_dim_) 800 | 请查看`torch.unsqueeze()` 801 | #### unsqueeze_(_dim_) → Tensor 802 | `unsqueeze()`的in-place运算形式 803 | #### var() 804 | 请查看`torch.var()` 805 | #### view(_*args_) → Tensor 806 | 返回一个有相同数据但大小不同的tensor。 807 | 返回的tensor必须有与原tensor相同的数据和相同数目的元素,但可以有不同的大小。一个tensor必须是连续的`contiguous()`才能被查看。 808 | 809 | __例:__ 810 | ```python 811 | >>> x = torch.randn(4, 4) 812 | >>> x.size() 813 | torch.Size([4, 4]) 814 | >>> y = x.view(16) 815 | >>> y.size() 816 | torch.Size([16]) 817 | >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions 818 | >>> z.size() 819 | torch.Size([2, 8]) 820 | ``` 821 | #### view_as(_tensor_) 822 | 返回被视作与给定的tensor相同大小的原tensor。 823 | 等效于: 824 | ```python 825 | self.view(tensor.size()) 826 | ``` 827 | #### zero_() 828 | 用0填充该tensor。 829 | -------------------------------------------------------------------------------- /docs/package_references/torch-nn.md: -------------------------------------------------------------------------------- 1 | # torch.nn 2 | 3 | ## Parameters 4 | ### class torch.nn.Parameter() 5 | `Variable`的一种,常被用于模块参数(`module parameter`)。 6 | 7 | `Parameters` 是 `Variable` 的子类。`Paramenters`和`Modules`一起使用的时候会有一些特殊的属性,即:当`Paramenters`赋值给`Module`的属性的时候,他会自动的被加到 `Module`的 参数列表中(即:会出现在 `parameters() 迭代器中`)。将`Varibale`赋值给`Module`属性则不会有这样的影响。 8 | 这样做的原因是:我们有时候会需要缓存一些临时的状态(`state`), 比如:模型中`RNN`的最后一个隐状态。如果没有`Parameter`这个类的话,那么这些临时变量也会注册成为模型变量。 9 | 10 | `Variable` 与 `Parameter`的另一个不同之处在于,`Parameter`不能被 `volatile`(即:无法设置`volatile=True`)而且默认`requires_grad=True`。`Variable`默认`requires_grad=False`。 11 | 12 | 13 | 参数说明: 14 | 15 | - data (Tensor) – parameter tensor. 16 | 17 | - requires_grad (bool, optional) – 默认为`True`,在`BP`的过程中会对其求微分。 18 | 19 | ## Containers(容器): 20 | ### class torch.nn.Module 21 | 所有网络的基类。 22 | 23 | 你的模型也应该继承这个类。 24 | 25 | `Modules`也可以包含其它`Modules`,允许使用树结构嵌入他们。你可以将子模块赋值给模型属性。 26 | ```python 27 | import torch.nn as nn 28 | import torch.nn.functional as F 29 | 30 | class Model(nn.Module): 31 | def __init__(self): 32 | super(Model, self).__init__() 33 | self.conv1 = nn.Conv2d(1, 20, 5)# submodule: Conv2d 34 | self.conv2 = nn.Conv2d(20, 20, 5) 35 | 36 | def forward(self, x): 37 | x = F.relu(self.conv1(x)) 38 | return F.relu(self.conv2(x)) 39 | ``` 40 | 41 | 通过上面方式赋值的`submodule`会被注册。当调用 `.cuda()` 的时候,`submodule`的参数也会转换为`cuda Tensor`。 42 | 43 | #### add_module(name, module) 44 | 将一个 `child module` 添加到当前 `modle`。 45 | 被添加的`module`可以通过 `name`属性来获取。 46 | 例: 47 | ```python 48 | import torch.nn as nn 49 | class Model(nn.Module): 50 | def __init__(self): 51 | super(Model, self).__init__() 52 | self.add_module("conv", nn.Conv2d(10, 20, 4)) 53 | #self.conv = nn.Conv2d(10, 20, 4) 和上面这个增加module的方式等价 54 | model = Model() 55 | print(model.conv) 56 | ``` 57 | 输出: 58 | ``` 59 | Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1)) 60 | ``` 61 | 62 | #### children() 63 | Returns an iterator over immediate children modules. 64 | 返回当前模型 子模块的迭代器。 65 | ```python 66 | import torch.nn as nn 67 | class Model(nn.Module): 68 | def __init__(self): 69 | super(Model, self).__init__() 70 | self.add_module("conv", nn.Conv2d(10, 20, 4)) 71 | self.add_module("conv1", nn.Conv2d(20 ,10, 4)) 72 | model = Model() 73 | 74 | for sub_module in model.children(): 75 | print(sub_module) 76 | ``` 77 | ``` 78 | Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1)) 79 | Conv2d(20, 10, kernel_size=(4, 4), stride=(1, 1)) 80 | ``` 81 | 82 | #### cpu(device_id=None) 83 | 84 | 将所有的模型参数(`parameters`)和`buffers`复制到`CPU` 85 | 86 | `NOTE`:官方文档用的move,但我觉着`copy`更合理。 87 | 88 | #### cuda(device_id=None) 89 | 90 | 将所有的模型参数(`parameters`)和`buffers`赋值`GPU` 91 | 92 | 参数说明: 93 | 94 | - device_id (int, optional) – 如果指定的话,所有的模型参数都会复制到指定的设备上。 95 | 96 | #### double() 97 | 98 | 将`parameters`和`buffers`的数据类型转换成`double`。 99 | 100 | #### eval() 101 | 102 | 将模型设置成`evaluation`模式 103 | 104 | 仅仅当模型中有`Dropout`和`BatchNorm`是才会有影响。 105 | 106 | #### float() 107 | 108 | 将`parameters`和`buffers`的数据类型转换成`float`。 109 | 110 | #### forward(* input) 111 | 112 | 定义了每次执行的 计算步骤。 113 | 在所有的子类中都需要重写这个函数。 114 | 115 | #### half() 116 | 117 | 将`parameters`和`buffers`的数据类型转换成`half`。 118 | 119 | #### load_state_dict(state_dict) 120 | 将`state_dict`中的`parameters`和`buffers`复制到此`module`和它的后代中。`state_dict`中的`key`必须和 `model.state_dict()`返回的`key`一致。 121 | `NOTE`:用来加载模型参数。 122 | 123 | 参数说明: 124 | 125 | - state_dict (dict) – 保存`parameters`和`persistent buffers`的字典。 126 | 127 | #### modules() 128 | 返回一个包含 当前模型 所有模块的迭代器。 129 | ```python 130 | import torch.nn as nn 131 | class Model(nn.Module): 132 | def __init__(self): 133 | super(Model, self).__init__() 134 | self.add_module("conv", nn.Conv2d(10, 20, 4)) 135 | self.add_module("conv1", nn.Conv2d(20 ,10, 4)) 136 | model = Model() 137 | 138 | for module in model.modules(): 139 | print(module) 140 | ``` 141 | ``` 142 | Model ( 143 | (conv): Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1)) 144 | (conv1): Conv2d(20, 10, kernel_size=(4, 4), stride=(1, 1)) 145 | ) 146 | Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1)) 147 | Conv2d(20, 10, kernel_size=(4, 4), stride=(1, 1)) 148 | ``` 149 | 可以看出,`modules()`返回的`iterator`不止包含 子模块。这是和`children()`的不同。 150 | 151 | **`NOTE:`** 152 | 重复的模块只被返回一次(`children()也是`)。 在下面的例子中, `submodule` 只会被返回一次: 153 | 154 | ```python 155 | import torch.nn as nn 156 | 157 | class Model(nn.Module): 158 | def __init__(self): 159 | super(Model, self).__init__() 160 | submodule = nn.Conv2d(10, 20, 4) 161 | self.add_module("conv", submodule) 162 | self.add_module("conv1", submodule) 163 | model = Model() 164 | 165 | for module in model.modules(): 166 | print(module) 167 | ``` 168 | ``` 169 | Model ( 170 | (conv): Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1)) 171 | (conv1): Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1)) 172 | ) 173 | Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1)) 174 | ``` 175 | #### named_children() 176 | 返回 包含 模型当前子模块 的迭代器,`yield` 模块名字和模块本身。 177 | 178 | 例子: 179 | ```python 180 | for name, module in model.named_children(): 181 | if name in ['conv4', 'conv5']: 182 | print(module) 183 | ``` 184 | #### named_modules(memo=None, prefix='')[source] 185 | 186 | 返回包含网络中所有模块的迭代器, `yielding` 模块名和模块本身。 187 | 188 | **`注意:`** 189 | 190 | 重复的模块只被返回一次(`children()也是`)。 在下面的例子中, `submodule` 只会被返回一次。 191 | 192 | 193 | #### parameters(memo=None) 194 | 195 | 返回一个 包含模型所有参数 的迭代器。 196 | 197 | 一般用来当作`optimizer`的参数。 198 | 199 | 例子: 200 | ```python 201 | for param in model.parameters(): 202 | print(type(param.data), param.size()) 203 | 204 | (20L,) 205 | (20L, 1L, 5L, 5L) 206 | ``` 207 | #### register_backward_hook(hook) 208 | 209 | 在`module`上注册一个`bachward hook`。 210 | 211 | 每次计算`module`的`inputs`的梯度的时候,这个`hook`会被调用。`hook`应该拥有下面的`signature`。 212 | 213 | `hook(module, grad_input, grad_output) -> Variable or None` 214 | 215 | 如果`module`有多个输入输出的话,那么`grad_input` `grad_output`将会是个`tuple`。 216 | `hook`不应该修改它的`arguments`,但是它可以选择性的返回关于输入的梯度,这个返回的梯度在后续的计算中会替代`grad_input`。 217 | 218 | 这个函数返回一个 句柄(`handle`)。它有一个方法 `handle.remove()`,可以用这个方法将`hook`从`module`移除。 219 | 220 | 221 | #### register_buffer(name, tensor) 222 | 223 | 给`module`添加一个`persistent buffer`。 224 | 225 | `persistent buffer`通常被用在这么一种情况:我们需要保存一个状态,但是这个状态不能看作成为模型参数。 226 | 例如:, `BatchNorm’s` running_mean 不是一个 `parameter`, 但是它也是需要保存的状态之一。 227 | 228 | `Buffers`可以通过注册时候的`name`获取。 229 | 230 | **`NOTE`:我们可以用 buffer 保存 `moving average`** 231 | 232 | 例子: 233 | 234 | ```python 235 | self.register_buffer('running_mean', torch.zeros(num_features)) 236 | 237 | self.running_mean 238 | ``` 239 | 240 | #### register_forward_hook(hook) 241 | 242 | 在`module`上注册一个`forward hook`。 243 | 每次调用`forward()`计算输出的时候,这个`hook`就会被调用。它应该拥有以下签名: 244 | 245 | `hook(module, input, output) -> None` 246 | 247 | `hook`不应该修改 `input`和`output`的值。 这个函数返回一个 句柄(`handle`)。它有一个方法 `handle.remove()`,可以用这个方法将`hook`从`module`移除。 248 | 249 | 250 | #### register_parameter(name, param) 251 | 向`module`添加 `parameter` 252 | 253 | `parameter`可以通过注册时候的`name`获取。 254 | 255 | #### state_dict(destination=None, prefix='')[source] 256 | 257 | 返回一个字典,保存着`module`的所有状态(`state`)。 258 | 259 | `parameters`和`persistent buffers`都会包含在字典中,字典的`key`就是`parameter`和`buffer`的 `names`。 260 | 261 | 例子: 262 | ```python 263 | import torch 264 | from torch.autograd import Variable 265 | import torch.nn as nn 266 | 267 | class Model(nn.Module): 268 | def __init__(self): 269 | super(Model, self).__init__() 270 | self.conv2 = nn.Linear(1, 2) 271 | self.vari = Variable(torch.rand([1])) 272 | self.par = nn.Parameter(torch.rand([1])) 273 | self.register_buffer("buffer", torch.randn([2,3])) 274 | 275 | model = Model() 276 | print(model.state_dict().keys()) 277 | 278 | ``` 279 | ``` 280 | odict_keys(['par', 'buffer', 'conv2.weight', 'conv2.bias']) 281 | ``` 282 | #### train(mode=True) 283 | 284 | 将`module`设置为 `training mode`。 285 | 286 | 仅仅当模型中有`Dropout`和`BatchNorm`是才会有影响。 287 | 288 | #### zero_grad() 289 | 290 | 将`module`中的所有模型参数的梯度设置为0. 291 | 292 | ### class torch.nn.Sequential(* args) 293 | 294 | 一个时序容器。`Modules` 会以他们传入的顺序被添加到容器中。当然,也可以传入一个`OrderedDict`。 295 | 296 | 为了更容易的理解如何使用`Sequential`, 下面给出了一个例子: 297 | 298 | ```python 299 | # Example of using Sequential 300 | 301 | model = nn.Sequential( 302 | nn.Conv2d(1,20,5), 303 | nn.ReLU(), 304 | nn.Conv2d(20,64,5), 305 | nn.ReLU() 306 | ) 307 | # Example of using Sequential with OrderedDict 308 | model = nn.Sequential(OrderedDict([ 309 | ('conv1', nn.Conv2d(1,20,5)), 310 | ('relu1', nn.ReLU()), 311 | ('conv2', nn.Conv2d(20,64,5)), 312 | ('relu2', nn.ReLU()) 313 | ])) 314 | ``` 315 | 316 | ### class torch.nn.ModuleList(modules=None)[source] 317 | 将`submodules`保存在一个`list`中。 318 | 319 | `ModuleList`可以像一般的`Python list`一样被`索引`。而且`ModuleList`中包含的`modules`已经被正确的注册,对所有的`module method`可见。 320 | 321 | 322 | 参数说明: 323 | 324 | - modules (list, optional) – 将要被添加到`MuduleList`中的 `modules` 列表 325 | 326 | 例子: 327 | ```python 328 | class MyModule(nn.Module): 329 | def __init__(self): 330 | super(MyModule, self).__init__() 331 | self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(10)]) 332 | 333 | def forward(self, x): 334 | # ModuleList can act as an iterable, or be indexed using ints 335 | for i, l in enumerate(self.linears): 336 | x = self.linears[i // 2](x) + l(x) 337 | return x 338 | ``` 339 | 340 | #### append(module)[source] 341 | 等价于 list 的 `append()` 342 | 343 | 参数说明: 344 | 345 | - module (nn.Module) – 要 append 的`module` 346 | #### extend(modules)[source] 347 | 等价于 `list` 的 `extend()` 方法 348 | 349 | 参数说明: 350 | 351 | - modules (list) – list of modules to append 352 | 353 | ### class torch.nn.ParameterList(parameters=None) 354 | 将`submodules`保存在一个`list`中。 355 | 356 | `ParameterList`可以像一般的`Python list`一样被`索引`。而且`ParameterList`中包含的`parameters`已经被正确的注册,对所有的`module method`可见。 357 | 358 | 359 | 参数说明: 360 | 361 | - modules (list, optional) – a list of nn.Parameter 362 | 363 | 例子: 364 | ```python 365 | class MyModule(nn.Module): 366 | def __init__(self): 367 | super(MyModule, self).__init__() 368 | self.params = nn.ParameterList([nn.Parameter(torch.randn(10, 10)) for i in range(10)]) 369 | 370 | def forward(self, x): 371 | # ModuleList can act as an iterable, or be indexed using ints 372 | for i, p in enumerate(self.params): 373 | x = self.params[i // 2].mm(x) + p.mm(x) 374 | return x 375 | ``` 376 | #### append(parameter)[source] 377 | 等价于` python list` 的 `append` 方法。 378 | 379 | 参数说明: 380 | 381 | - parameter (nn.Parameter) – parameter to append 382 | #### extend(parameters)[source] 383 | 等价于` python list` 的 `extend` 方法。 384 | 385 | 参数说明: 386 | 387 | - parameters (list) – list of parameters to append 388 | 389 | ## 卷积层 390 | ### class torch.nn.Conv1d(in\_channels, out\_channels, kernel\_size, stride=1, padding=0, dilation=1, groups=1, bias=True)### 391 | 一维卷积层,输入的尺度是(N, C_in,L),输出尺度( N,C_out,L_out)的计算方式: 392 | 393 | $$ 394 | 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) 395 | $$ 396 | 397 | **说明** 398 | 399 | `bigotimes`: 表示相关系数计算 400 | `stride`: 控制相关系数的计算步长 401 | `dilation`: 用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md) 402 | `groups`: 控制输入和输出之间的连接, `group=1`,输出是所有的输入的卷积;`group=2`,此时相当于有并排的两个卷积层,每个卷积层计算输入通道的一半,并且产生的输出是输出通道的一半,随后将这两个输出连接起来。 403 | 404 | 405 | 406 | **Parameters:** 407 | 408 | - in_channels(`int`) – 输入信号的通道 409 | - out_channels(`int`) – 卷积产生的通道 410 | - kerner_size(`int` or `tuple`) - 卷积核的尺寸 411 | - stride(`int` or `tuple`, `optional`) - 卷积步长 412 | - padding (`int` or `tuple`, `optional`)- 输入的每一条边补充0的层数 413 | - dilation(`int` or `tuple`, `optional``) – 卷积核元素之间的间距 414 | - groups(`int`, `optional`) – 从输入通道到输出通道的阻塞连接数 415 | - bias(`bool`, `optional`) - 如果`bias=True`,添加偏置 416 | 417 | **shape:** 418 | 输入: (N,C_in,L_in) 419 | 输出: (N,C_out,L_out) 420 | 输入输出的计算方式: 421 | $$L_{out}=floor((L_{in}+2*padding-dilation*(kernerl\_size-1)-1)/stride+1)$$ 422 | 423 | **变量:** 424 | weight(`tensor`) - 卷积的权重,大小是(`out_channels`, `in_channels`, `kernel_size`) 425 | bias(`tensor`) - 卷积的偏置系数,大小是(`out_channel`) 426 | 427 | **example:** 428 | ```python 429 | >>> m = nn.Conv1d(16, 33, 3, stride=2) 430 | >>> input = autograd.Variable(torch.randn(20, 16, 50)) 431 | >>> output = m(input) 432 | ``` 433 | 434 | ### class torch.nn.Conv2d(in\_channels, out\_channels, kernel\_size, stride=1, padding=0, dilation=1, groups=1, bias=True)### 435 | 二维卷积层, 输入的尺度是(N, C_in,H,W),输出尺度(N,C_out,H_out,W_out)的计算方式: 436 | 437 | $$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)$$ 438 | 439 | **说明** 440 | `bigotimes`: 表示二维的相关系数计算 441 | `stride`: 控制相关系数的计算步长 442 | `dilation`: 用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md) 443 | `groups`: 控制输入和输出之间的连接: `group=1`,输出是所有的输入的卷积;`group=2`,此时相当于有并排的两个卷积层,每个卷积层计算输入通道的一半,并且产生的输出是输出通道的一半,随后将这两个输出连接起来。 444 | 445 | 参数`kernel_size`,`stride,padding`,`dilation`也可以是一个`int`的数据,此时卷积height和width值相同;也可以是一个`tuple`数组,`tuple`的第一维度表示height的数值,tuple的第二维度表示width的数值 446 | 447 | **Parameters:** 448 | 449 | - in_channels(`int`) – 输入信号的通道 450 | - out_channels(`int`) – 卷积产生的通道 451 | - kerner\_size(`int` or `tuple`) - 卷积核的尺寸 452 | - stride(`int` or `tuple`, `optional`) - 卷积步长 453 | - padding(`int` or `tuple`, `optional`) - 输入的每一条边补充0的层数 454 | - dilation(`int` or `tuple`, `optional`) – 卷积核元素之间的间距 455 | - groups(`int`, `optional`) – 从输入通道到输出通道的阻塞连接数 456 | - bias(`bool`, `optional`) - 如果`bias=True`,添加偏置 457 | 458 | **shape:** 459 | input: (N,C_in,H_in,W_in) 460 | output: (N,C_out,H_out,W_out) 461 | $$H_{out}=floor((H_{in}+2*padding[0]-dilation[0]*(kernerl\_size[0]-1)-1)/stride[0]+1)$$ 462 | 463 | $$W_{out}=floor((W_{in}+2*padding[1]-dilation[1]*(kernerl\_size[1]-1)-1)/stride[1]+1)$$ 464 | 465 | **变量:** 466 | weight(`tensor`) - 卷积的权重,大小是(`out_channels`, `in_channels`,`kernel_size`) 467 | bias(`tensor`) - 卷积的偏置系数,大小是(`out_channel`) 468 | 469 | **example:** 470 | ```python 471 | >>> # With square kernels and equal stride 472 | >>> m = nn.Conv2d(16, 33, 3, stride=2) 473 | >>> # non-square kernels and unequal stride and with padding 474 | >>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2)) 475 | >>> # non-square kernels and unequal stride and with padding and dilation 476 | >>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1)) 477 | >>> input = autograd.Variable(torch.randn(20, 16, 50, 100)) 478 | >>> output = m(input) 479 | ``` 480 | 481 | ### class torch.nn.Conv3d(in\_channels, out\_channels, kernel\_size, stride=1, padding=0, dilation=1, groups=1, bias=True)### 482 | 三维卷积层, 输入的尺度是(N, C_in,D,H,W),输出尺度(N,C_out,D_out,H_out,W_out)的计算方式: 483 | $$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)$$ 484 | 485 | **说明** 486 | `bigotimes`: 表示二维的相关系数计算 487 | `stride`: 控制相关系数的计算步长 488 | `dilation`: 用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md) 489 | `groups`: 控制输入和输出之间的连接: `group=1`,输出是所有的输入的卷积;`group=2`,此时相当于有并排的两个卷积层,每个卷积层计算输入通道的一半,并且产生的输出是输出通道的一半,随后将这两个输出连接起来。 490 | 参数`kernel_size`,`stride`,`padding`,`dilation`可以是一个`int`的数据 - 卷积height和width值相同,也可以是一个有三个`int`数据的`tuple`数组,`tuple`的第一维度表示depth的数值,`tuple`的第二维度表示height的数值,`tuple`的第三维度表示width的数值 491 | 492 | **Parameters:** 493 | 494 | - in_channels(`int`) – 输入信号的通道 495 | - out_channels(`int`) – 卷积产生的通道 496 | - kernel\_size(`int` or `tuple`) - 卷积核的尺寸 497 | - stride(`int` or `tuple`, `optional`) - 卷积步长 498 | - padding(`int` or `tuple`, `optional`) - 输入的每一条边补充0的层数 499 | - dilation(`int` or `tuple`, `optional`) – 卷积核元素之间的间距 500 | - groups(`int`, `optional`) – 从输入通道到输出通道的阻塞连接数 501 | - bias(`bool`, `optional`) - 如果`bias=True`,添加偏置 502 | 503 | **shape:** 504 | `input`: (N,C_in,D_in,H_in,W_in) 505 | `output`: (N,C_out,D_out,H_out,W_out) 506 | $$D_{out}=floor((D_{in}+2*padding[0]-dilation[0]*(kernerl\_size[0]-1)-1)/stride[0]+1)$$ 507 | 508 | $$H_{out}=floor((H_{in}+2*padding[1]-dilation[2]*(kernerl\_size[1]-1)-1)/stride[1]+1)$$ 509 | 510 | $$W_{out}=floor((W_{in}+2*padding[2]-dilation[2]*(kernerl\_size[2]-1)-1)/stride[2]+1)$$ 511 | 512 | **变量:** 513 | 514 | - weight(`tensor`) - 卷积的权重,shape是(`out_channels`, `in_channels`,`kernel_size`)` 515 | - bias(`tensor`) - 卷积的偏置系数,shape是(`out_channel`) 516 | 517 | **example:** 518 | ```python 519 | >>> # With square kernels and equal stride 520 | >>> m = nn.Conv3d(16, 33, 3, stride=2) 521 | >>> # non-square kernels and unequal stride and with padding 522 | >>> m = nn.Conv3d(16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(4, 2, 0)) 523 | >>> input = autograd.Variable(torch.randn(20, 16, 10, 50, 100)) 524 | >>> output = m(input) 525 | ``` 526 | ### class torch.nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True)### 527 | 1维的解卷积操作(`transposed convolution operator`,注意改视作操作可视作解卷积操作,但并不是真正的解卷积操作) 528 | 该模块可以看作是`Conv1d`相对于其输入的梯度,有时(但不正确地)被称为解卷积操作。 529 | 530 | **注意** 531 | 由于内核的大小,输入的最后的一些列的数据可能会丢失。因为输入和输出是不是完全的互相关。因此,用户可以进行适当的填充(padding操作)。 532 | 533 | **参数** 534 | 535 | - in_channels(`int`) – 输入信号的通道数 536 | - out_channels(`int`) – 卷积产生的通道 537 | - kernel\_size(`int` or `tuple`) - 卷积核的大小 538 | - stride(`int` or `tuple`, `optional`) - 卷积步长 539 | - padding(`int` or `tuple`, `optional`) - 输入的每一条边补充0的层数 540 | - output_padding(`int` or `tuple`, `optional`) - 输出的每一条边补充0的层数 541 | - dilation(`int` or `tuple`, `optional`) – 卷积核元素之间的间距 542 | - groups(`int`, `optional`) – 从输入通道到输出通道的阻塞连接数 543 | - bias(`bool`, `optional`) - 如果`bias=True`,添加偏置 544 | 545 | **shape:** 546 | 输入: (N,C_in,L_in) 547 | 输出: (N,C_out,L_out) 548 | $$L_{out}=(L_{in}-1)*stride-2*padding+kernel\_size+output\_padding$$ 549 | 550 | **变量:** 551 | - weight(`tensor`) - 卷积的权重,大小是(`in_channels`, `in_channels`,`kernel_size`) 552 | - bias(`tensor`) - 卷积的偏置系数,大小是(`out_channel`) 553 | 554 | ### class torch.nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True) 555 | 2维的转置卷积操作(`transposed convolution operator`,注意改视作操作可视作解卷积操作,但并不是真正的解卷积操作) 556 | 该模块可以看作是`Conv2d`相对于其输入的梯度,有时(但不正确地)被称为解卷积操作。 557 | 558 | **说明** 559 | 560 | `stride`: 控制相关系数的计算步长 561 | `dilation`: 用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md) 562 | `groups`: 控制输入和输出之间的连接: `group=1`,输出是所有的输入的卷积;`group=2`,此时相当于有并排的两个卷积层,每个卷积层计算输入通道的一半,并且产生的输出是输出通道的一半,随后将这两个输出连接起来。 563 | 564 | 参数`kernel_size`,`stride`,`padding`,`dilation`数据类型: 565 | 可以是一个`int`类型的数据,此时卷积height和width值相同; 566 | 也可以是一个`tuple`数组(包含来两个`int`类型的数据),第一个`int`数据表示`height`的数值,第二个`int`类型的数据表示width的数值 567 | 568 | **注意** 569 | 由于内核的大小,输入的最后的一些列的数据可能会丢失。因为输入和输出是不是完全的互相关。因此,用户可以进行适当的填充(`padding`操作)。 570 | 571 | **参数:** 572 | 573 | - in_channels(`int`) – 输入信号的通道数 574 | - out_channels(`int`) – 卷积产生的通道数 575 | - kerner\_size(`int` or `tuple`) - 卷积核的大小 576 | - stride(`int` or `tuple`,` optional`) - 卷积步长 577 | - padding(`int` or `tuple`, `optional`) - 输入的每一条边补充0的层数 578 | - output_padding(`int` or `tuple`, `optional`) - 输出的每一条边补充0的层数 579 | - dilation(`int` or `tuple`, `optional`) – 卷积核元素之间的间距 580 | - groups(`int`, `optional`) – 从输入通道到输出通道的阻塞连接数 581 | - bias(`bool`, `optional`) - 如果`bias=True`,添加偏置 582 | 583 | **shape:** 584 | 输入: (N,C_in,H_in,W_in) 585 | 输出: (N,C_out,H_out,W_out) 586 | $$H_{out}=(H_{in}-1)*stride[0]-2*padding[0]+kernel\_size[0]+output\_padding[0]$$ 587 | 588 | $$W_{out}=(W_{in}-1)*stride[1]-2*padding[1]+kernel\_size[1]+output\_padding[1]$$ 589 | 590 | **变量:** 591 | - weight(`tensor`) - 卷积的权重,大小是(`in_channels`, `in_channels`,`kernel_size`) 592 | - bias(`tensor`) - 卷积的偏置系数,大小是(`out_channel`) 593 | 594 | **Example** 595 | 596 | ```python 597 | >>> # With square kernels and equal stride 598 | >>> m = nn.ConvTranspose2d(16, 33, 3, stride=2) 599 | >>> # non-square kernels and unequal stride and with padding 600 | >>> m = nn.ConvTranspose2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2)) 601 | >>> input = autograd.Variable(torch.randn(20, 16, 50, 100)) 602 | >>> output = m(input) 603 | >>> # exact output size can be also specified as an argument 604 | >>> input = autograd.Variable(torch.randn(1, 16, 12, 12)) 605 | >>> downsample = nn.Conv2d(16, 16, 3, stride=2, padding=1) 606 | >>> upsample = nn.ConvTranspose2d(16, 16, 3, stride=2, padding=1) 607 | >>> h = downsample(input) 608 | >>> h.size() 609 | torch.Size([1, 16, 6, 6]) 610 | >>> output = upsample(h, output_size=input.size()) 611 | >>> output.size() 612 | torch.Size([1, 16, 12, 12]) 613 | ``` 614 | 615 | ### torch.nn.ConvTranspose3d(in\_channels, out\_channels, kernel\_size, stride=1, padding=0, output\_padding=0, groups=1, bias=True) 616 | 617 | 3维的转置卷积操作(`transposed convolution operator`,注意改视作操作可视作解卷积操作,但并不是真正的解卷积操作) 618 | 转置卷积操作将每个输入值和一个可学习权重的卷积核相乘,输出所有输入通道的求和 619 | 620 | 该模块可以看作是`Conv3d`相对于其输入的梯度,有时(但不正确地)被称为解卷积操作。 621 | 622 | **说明** 623 | 624 | `stride`: 控制相关系数的计算步长 625 | `dilation`: 用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md) 626 | `groups`: 控制输入和输出之间的连接: `group=1`,输出是所有的输入的卷积;`group=2`,此时相当于有并排的两个卷积层,每个卷积层计算输入通道的一半,并且产生的输出是输出通道的一半,随后将这两个输出连接起来。 627 | 628 | 参数`kernel\_size`,`stride`, `padding`,`dilation`数据类型: 629 | 一个`int`类型的数据,此时卷积height和width值相同; 630 | 也可以是一个`tuple`数组(包含来两个`int`类型的数据),第一个`int`数据表示height的数值,tuple的第二个int类型的数据表示width的数值 631 | 632 | **注意** 633 | 由于内核的大小,输入的最后的一些列的数据可能会丢失。因为输入和输出是不是完全的互相关。因此,用户可以进行适当的填充(padding操作)。 634 | 635 | **参数:** 636 | 637 | - in_channels(`int`) – 输入信号的通道数 638 | - out_channels(`int`) – 卷积产生的通道数 639 | - kernel_size(`int` or `tuple`) - 卷积核的大小 640 | - stride(`int` or `tuple`, `optional`) - 卷积步长 641 | - padding(`int` or `tuple`, `optional`) - 输入的每一条边补充0的层数 642 | - output_padding(`int` or `tuple`, `optional`) - 输出的每一条边补充0的层数 643 | - dilation(`int` or `tuple`, `optional`) – 卷积核元素之间的间距 644 | - groups(`int`, `optional`) – 从输入通道到输出通道的阻塞连接数 645 | - bias(`bool`, `optional`) - 如果`bias=True`,添加偏置 646 | 647 | **shape:** 648 | 输入: (N,C_in,H_in,W_in) 649 | 输出: (N,C_out,H_out,W_out) 650 | $$D_{out}=(D_{in}-1)*stride[0]-2*padding[0]+kernel\_size[0]+output\_padding[0]$$ 651 | 652 | $$H_{out}=(H_{in}-1)*stride[1]-2*padding[1]+kernel\_size[1]+output\_padding[0]$$ 653 | 654 | $$W_{out}=(W_{in}-1)*stride[2]-2*padding[2]+kernel\_size[2]+output\_padding[2]$$ 655 | 656 | **变量:** 657 | - weight(`tensor`) - 卷积的权重,大小是(`in_channels`, `in_channels`,`kernel_size`) 658 | - bias(`tensor`) - 卷积的偏置系数,大小是(`out_channel`) 659 | 660 | **Example** 661 | ```python 662 | >>> # With square kernels and equal stride 663 | >>> m = nn.ConvTranspose3d(16, 33, 3, stride=2) 664 | >>> # non-square kernels and unequal stride and with padding 665 | >>> m = nn.Conv3d(16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(0, 4, 2)) 666 | >>> input = autograd.Variable(torch.randn(20, 16, 10, 50, 100)) 667 | >>> output = m(input) 668 | ``` 669 | 670 | ## 池化层## 671 | 672 | ### class torch.nn.MaxPool1d(kernel\_size, stride=None, padding=0, dilation=1, return\_indices=False, ceil_mode=False) 673 | 674 | 对于输入信号的输入通道,提供1维最大池化(`max pooling`)操作 675 | 676 | 如果输入的大小是(N,C,L),那么输出的大小是(N,C,L_out)的计算方式是: 677 | $$out(N_i, C_j,k)=max^{kernel\_size-1}_{m=0}input(N_{i},C_j,stride*k+m)$$ 678 | 679 | 如果`padding`不是0,会在输入的每一边添加相应数目0 680 | `dilation`用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md) 681 | 682 | **参数:** 683 | 684 | - kernel_size(`int` or `tuple`) - max pooling的窗口大小 685 | - stride(`int` or `tuple`, `optional`) - max pooling的窗口移动的步长。默认值是`kernel_size` 686 | - padding(`int` or `tuple`, `optional`) - 输入的每一条边补充0的层数 687 | - dilation(`int` or `tuple`, `optional`) – 一个控制窗口中元素步幅的参数 688 | - return_indices - 如果等于`True`,会返回输出最大值的序号,对于上采样操作会有帮助 689 | - ceil_mode - 如果等于`True`,计算输出信号大小的时候,会使用向上取整,代替默认的向下取整的操作 690 | 691 | **shape:** 692 | 输入: (N,C_in,L_in) 693 | 输出: (N,C_out,L_out) 694 | $$L_{out}=floor((L_{in} + 2*padding - dilation*(kernel\_size - 1) - 1)/stride + 1$$ 695 | 696 | **example:** 697 | ```python 698 | >>> # pool of size=3, stride=2 699 | >>> m = nn.MaxPool1d(3, stride=2) 700 | >>> input = autograd.Variable(torch.randn(20, 16, 50)) 701 | >>> output = m(input) 702 | ``` 703 | 704 | ### class torch.nn.MaxPool2d(kernel\_size, stride=None, padding=0, dilation=1, return\_indices=False, ceil\_mode=False) 705 | 706 | 对于输入信号的输入通道,提供2维最大池化(`max pooling`)操作 707 | 708 | 如果输入的大小是(N,C,H,W),那么输出的大小是(N,C,H_out,W_out)和池化窗口大小(kH,kW)的关系是: 709 | $$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)$$ 710 | 711 | 如果`padding`不是0,会在输入的每一边添加相应数目0 712 | `dilation`用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md) 713 | 714 | 参数`kernel_size`,`stride`, `padding`,`dilation`数据类型: 715 | 可以是一个`int`类型的数据,此时卷积height和width值相同; 716 | 也可以是一个`tuple`数组(包含来两个int类型的数据),第一个`int`数据表示height的数值,`tuple`的第二个int类型的数据表示width的数值 717 | 718 | **参数:** 719 | 720 | - kernel_size(`int` or `tuple`) - max pooling的窗口大小 721 | - stride(`int` or `tuple`, `optional`) - max pooling的窗口移动的步长。默认值是`kernel_size` 722 | - padding(`int` or `tuple`, `optional`) - 输入的每一条边补充0的层数 723 | - dilation(`int` or `tuple`, `optional`) – 一个控制窗口中元素步幅的参数 724 | - return_indices - 如果等于`True`,会返回输出最大值的序号,对于上采样操作会有帮助 725 | - ceil_mode - 如果等于`True`,计算输出信号大小的时候,会使用向上取整,代替默认的向下取整的操作 726 | 727 | **shape:** 728 | 输入: (N,C,H_{in},W_in) 729 | 输出: (N,C,H_out,W_out) 730 | $$H_{out}=floor((H_{in} + 2*padding[0] - dilation[0]*(kernel\_size[0] - 1) - 1)/stride[0] + 1$$ 731 | 732 | $$W_{out}=floor((W_{in} + 2*padding[1] - dilation[1]*(kernel\_size[1] - 1) - 1)/stride[1] + 1$$ 733 | 734 | **example:** 735 | ```python 736 | >>> # pool of square window of size=3, stride=2 737 | >>> m = nn.MaxPool2d(3, stride=2) 738 | >>> # pool of non-square window 739 | >>> m = nn.MaxPool2d((3, 2), stride=(2, 1)) 740 | >>> input = autograd.Variable(torch.randn(20, 16, 50, 32)) 741 | >>> output = m(input) 742 | ``` 743 | 744 | ### class torch.nn.MaxPool3d(kernel\_size, stride=None, padding=0, dilation=1, return\_indices=False, ceil\_mode=False) 745 | 746 | 对于输入信号的输入通道,提供3维最大池化(max pooling)操作 747 | 748 | 如果输入的大小是(N,C,D,H,W),那么输出的大小是(N,C,D,H_out,W_out)和池化窗口大小(kD,kH,kW)的关系是: 749 | $$out(N_i,C_j,d,h,w)=max^{kD-1}_{m=0}max^{kH-1}_{m=0}max^{kW-1}_{m=0}$$ 750 | 751 | $$input(N_{i},C_j,stride[0]*k+d,stride[1]*h+m,stride[2]*w+n)$$ 752 | 753 | 如果`padding`不是0,会在输入的每一边添加相应数目0 754 | `dilation`用于控制内核点之间的距离,详细描述在[这里](https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md) 755 | 756 | 参数`kernel_size`,`stride`, `padding`,`dilation`数据类型: 757 | 可以是`int`类型的数据,此时卷积height和width值相同; 758 | 也可以是一个`tuple`数组(包含来两个`int`类型的数据),第一个`int`数据表示height的数值,`tuple`的第二个`int`类型的数据表示width的数值 759 | 760 | **参数:** 761 | 762 | - kernel\_size(`int` or `tuple`) - max pooling的窗口大小 763 | - stride(`int` or `tuple`, `optional`) - max pooling的窗口移动的步长。默认值是kernel_size 764 | - padding(`int` or `tuple`, `optional`) - 输入的每一条边补充0的层数 765 | - dilation(`int` or `tuple`, `optional`) – 一个控制窗口中元素步幅的参数 766 | - return_indices - 如果等于`True`,会返回输出最大值的序号,对于上采样操作会有帮助 767 | - ceil_mode - 如果等于`True`,计算输出信号大小的时候,会使用向上取整,代替默认的向下取整的操作 768 | 769 | **shape:** 770 | 输入: (N,C,H_in,W_in) 771 | 输出: (N,C,H_out,W_out) 772 | $$D_{out}=floor((D_{in} + 2*padding[0] - dilation[0]*(kernel\_size[0] - 1) - 1)/stride[0] + 1)$$ 773 | 774 | $$H_{out}=floor((H_{in} + 2*padding[1] - dilation[1]*(kernel\_size[0] - 1) - 1)/stride[1] + 1)$$ 775 | 776 | $$W_{out}=floor((W_{in} + 2*padding[2] - dilation[2]*(kernel\_size[2] - 1) - 1)/stride[2] + 1)$$ 777 | 778 | **example:** 779 | ```python 780 | >>> # pool of square window of size=3, stride=2 781 | >>>m = nn.MaxPool3d(3, stride=2) 782 | >>> # pool of non-square window 783 | >>> m = nn.MaxPool3d((3, 2, 2), stride=(2, 1, 2)) 784 | >>> input = autograd.Variable(torch.randn(20, 16, 50,44, 31)) 785 | >>> output = m(input) 786 | ``` 787 | 788 | #### class torch.nn.MaxUnpool1d(kernel\_size, stride=None, padding=0) 789 | `Maxpool1d`的逆过程,不过并不是完全的逆过程,因为在`maxpool1d`的过程中,一些最大值的已经丢失。 790 | `MaxUnpool1d`输入`MaxPool1d`的输出,包括最大值的索引,并计算所有`maxpool1d`过程中非最大值被设置为零的部分的反向。 791 | 792 | **注意:** 793 | `MaxPool1d`可以将多个输入大小映射到相同的输出大小。因此,反演过程可能会变得模棱两可。 为了适应这一点,可以在调用中将输出大小(`output_size`)作为额外的参数传入。 具体用法,请参阅下面的输入和示例 794 | 795 | **参数:** 796 | 797 | - kernel_size(`int` or `tuple`) - max pooling的窗口大小 798 | - stride(`int` or `tuple`, `optional`) - max pooling的窗口移动的步长。默认值是`kernel_size` 799 | - padding(`int` or `tuple`, `optional`) - 输入的每一条边补充0的层数 800 | 801 | **输入:** 802 | `input`:需要转换的`tensor` 803 | `indices`:Maxpool1d的索引号 804 | `output_size`:一个指定输出大小的`torch.Size` 805 | 806 | **shape:** 807 | `input`: (N,C,H_in) 808 | `output`:(N,C,H_out) 809 | $$H_{out}=(H_{in}-1)*stride[0]-2*padding[0]+kernel\_size[0]$$ 810 | 也可以使用`output_size`指定输出的大小 811 | 812 | **Example:** 813 | ```python 814 | >>> pool = nn.MaxPool1d(2, stride=2, return_indices=True) 815 | >>> unpool = nn.MaxUnpool1d(2, stride=2) 816 | >>> input = Variable(torch.Tensor([[[1, 2, 3, 4, 5, 6, 7, 8]]])) 817 | >>> output, indices = pool(input) 818 | >>> unpool(output, indices) 819 | Variable containing: 820 | (0 ,.,.) = 821 | 0 2 0 4 0 6 0 8 822 | [torch.FloatTensor of size 1x1x8] 823 | 824 | >>> # Example showcasing the use of output_size 825 | >>> input = Variable(torch.Tensor([[[1, 2, 3, 4, 5, 6, 7, 8, 9]]])) 826 | >>> output, indices = pool(input) 827 | >>> unpool(output, indices, output_size=input.size()) 828 | Variable containing: 829 | (0 ,.,.) = 830 | 0 2 0 4 0 6 0 8 0 831 | [torch.FloatTensor of size 1x1x9] 832 | >>> unpool(output, indices) 833 | Variable containing: 834 | (0 ,.,.) = 835 | 0 2 0 4 0 6 0 8 836 | [torch.FloatTensor of size 1x1x8] 837 | ``` 838 | 839 | #### class torch.nn.MaxUnpool2d(kernel\_size, stride=None, padding=0) 840 | `Maxpool2d`的逆过程,不过并不是完全的逆过程,因为在maxpool2d的过程中,一些最大值的已经丢失。 841 | `MaxUnpool2d`的输入是`MaxPool2d`的输出,包括最大值的索引,并计算所有`maxpool2d`过程中非最大值被设置为零的部分的反向。 842 | 843 | **注意:** 844 | `MaxPool2d`可以将多个输入大小映射到相同的输出大小。因此,反演过程可能会变得模棱两可。 为了适应这一点,可以在调用中将输出大小(`output_size`)作为额外的参数传入。具体用法,请参阅下面示例 845 | 846 | **参数:** 847 | 848 | - kernel_size(`int` or `tuple`) - max pooling的窗口大小 849 | - stride(`int` or `tuple`, `optional`) - max pooling的窗口移动的步长。默认值是`kernel_size` 850 | - padding(`int` or `tuple`, `optional`) - 输入的每一条边补充0的层数 851 | 852 | **输入:** 853 | `input`:需要转换的`tensor` 854 | `indices`:Maxpool1d的索引号 855 | `output_size`:一个指定输出大小的`torch.Size` 856 | 857 | **大小:** 858 | `input`: (N,C,H_in,W_in) 859 | `output`:(N,C,H_out,W_out) 860 | 861 | $$H_{out}=(H_{in}-1)*stride[0]-2*padding[0]+kernel\_size[0]$$ 862 | 863 | $$W_{out}=(W_{in}-1)*stride[1]-2*padding[1]+kernel\_size[1]$$ 864 | 865 | 也可以使用`output_size`指定输出的大小 866 | 867 | **Example:** 868 | ```python 869 | >>> pool = nn.MaxPool2d(2, stride=2, return_indices=True) 870 | >>> unpool = nn.MaxUnpool2d(2, stride=2) 871 | >>> input = Variable(torch.Tensor([[[[ 1, 2, 3, 4], 872 | ... [ 5, 6, 7, 8], 873 | ... [ 9, 10, 11, 12], 874 | ... [13, 14, 15, 16]]]])) 875 | >>> output, indices = pool(input) 876 | >>> unpool(output, indices) 877 | Variable containing: 878 | (0 ,0 ,.,.) = 879 | 0 0 0 0 880 | 0 6 0 8 881 | 0 0 0 0 882 | 0 14 0 16 883 | [torch.FloatTensor of size 1x1x4x4] 884 | 885 | >>> # specify a different output size than input size 886 | >>> unpool(output, indices, output_size=torch.Size([1, 1, 5, 5])) 887 | Variable containing: 888 | (0 ,0 ,.,.) = 889 | 0 0 0 0 0 890 | 6 0 8 0 0 891 | 0 0 0 14 0 892 | 16 0 0 0 0 893 | 0 0 0 0 0 894 | [torch.FloatTensor of size 1x1x5x5] 895 | ``` 896 | 897 | #### class torch.nn.MaxUnpool3d(kernel\_size, stride=None, padding=0) 898 | `Maxpool3d`的逆过程,不过并不是完全的逆过程,因为在`maxpool3d`的过程中,一些最大值的已经丢失。 899 | `MaxUnpool3d`的输入就是`MaxPool3d`的输出,包括最大值的索引,并计算所有`maxpool3d`过程中非最大值被设置为零的部分的反向。 900 | 901 | **注意:** 902 | `MaxPool3d`可以将多个输入大小映射到相同的输出大小。因此,反演过程可能会变得模棱两可。为了适应这一点,可以在调用中将输出大小(`output_size`)作为额外的参数传入。具体用法,请参阅下面的输入和示例 903 | 904 | **参数:** 905 | 906 | - kernel_size(`int` or `tuple`) - Maxpooling窗口大小 907 | - stride(`int` or `tuple`, `optional`) - max pooling的窗口移动的步长。默认值是`kernel_size` 908 | - padding(`int` or `tuple`, `optional`) - 输入的每一条边补充0的层数 909 | 910 | **输入:** 911 | `input`:需要转换的`tensor` 912 | `indices`:`Maxpool1d`的索引序数 913 | `output_size`:一个指定输出大小的`torch.Size` 914 | 915 | **大小:** 916 | `input`: (N,C,D_in,H_in,W_in) 917 | `outpu`t:(N,C,D_out,H_out,W_out) 918 | $$ 919 | \begin{aligned} 920 | D_{out}=(D_{in}-1)*stride[0]-2*padding[0]+kernel\_size[0]\\ 921 | 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] 922 | \end{aligned} 923 | $$ 924 | 925 | 也可以使用`output_size`指定输出的大小 926 | 927 | **Example:** 928 | ```python 929 | >>> # pool of square window of size=3, stride=2 930 | >>> pool = nn.MaxPool3d(3, stride=2, return_indices=True) 931 | >>> unpool = nn.MaxUnpool3d(3, stride=2) 932 | >>> output, indices = pool(Variable(torch.randn(20, 16, 51, 33, 15))) 933 | >>> unpooled_output = unpool(output, indices) 934 | >>> unpooled_output.size() 935 | torch.Size([20, 16, 51, 33, 15]) 936 | ``` 937 | 938 | ### class torch.nn.AvgPool1d(kernel\_size, stride=None, padding=0, ceil\_mode=False, count\_include_pad=True) 939 | 940 | 对信号的输入通道,提供1维平均池化(average pooling ) 941 | 输入信号的大小(N,C,L),输出大小(N,C,L_out)和池化窗口大小k的关系是: 942 | $$out(N_i,C_j,l)=1/k*\sum^{k}_{m=0}input(N_{i},C_{j},stride*l+m)$$ 943 | 如果`padding`不是0,会在输入的每一边添加相应数目0 944 | 945 | **参数:** 946 | 947 | - kernel\_size(`int` or `tuple`) - 池化窗口大小 948 | - stride(`int` or `tuple`, `optional`) - max pooling的窗口移动的步长。默认值是`kernel_size` 949 | - padding(`int` or `tuple`, `optional`) - 输入的每一条边补充0的层数 950 | - dilation(`int` or `tuple`, `optional`) – 一个控制窗口中元素步幅的参数 951 | - return_indices - 如果等于`True`,会返回输出最大值的序号,对于上采样操作会有帮助 952 | - ceil_mode - 如果等于`True`,计算输出信号大小的时候,会使用向上取整,代替默认的向下取整的操作 953 | 954 | **大小:** 955 | `input`:(N,C,L_in) 956 | `output`:(N,C,L_out) 957 | $$L_{out}=floor((L_{in}+2*padding-kernel\_size)/stride+1)$$ 958 | 959 | **Example:** 960 | ```python 961 | >>> # pool with window of size=3, stride=2 962 | >>> m = nn.AvgPool1d(3, stride=2) 963 | >>> m(Variable(torch.Tensor([[[1,2,3,4,5,6,7]]]))) 964 | Variable containing: 965 | (0 ,.,.) = 966 | 2 4 6 967 | [torch.FloatTensor of size 1x1x3] 968 | ``` 969 | 970 | ### class torch.nn.AvgPool2d(kernel\_size, stride=None, padding=0, ceil\_mode=False, count\_include_pad=True) 971 | 972 | 对信号的输入通道,提供2维的平均池化(average pooling ) 973 | 输入信号的大小(N,C,H,W),输出大小(N,C,H_out,W_out)和池化窗口大小(kH,kW)的关系是: 974 | $$ 975 | 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)$$ 976 | 977 | 如果`padding`不是0,会在输入的每一边添加相应数目0 978 | 979 | **参数:** 980 | 981 | - kernel_size(`int` or `tuple`) - 池化窗口大小 982 | - stride(`int` or `tuple`, `optional`) - max pooling的窗口移动的步长。默认值是`kernel_size` 983 | - padding(`int` or `tuple`, `optional`) - 输入的每一条边补充0的层数 984 | - dilation(`int` or `tuple`, `optional`) – 一个控制窗口中元素步幅的参数 985 | - ceil_mode - 如果等于`True`,计算输出信号大小的时候,会使用向上取整,代替默认的向下取整的操作 986 | - count_include_pad - 如果等于`True`,计算平均池化时,将包括`padding`填充的0 987 | 988 | **shape:** 989 | `input`: (N,C,H_in,W_in) 990 | `output`: (N,C,H_out,W_out) 991 | $$\begin{aligned} 992 | H_{out}=floor((H_{in}+2*padding[0]-kernel\_size[0])/stride[0]+1)\\ 993 | W_{out}=floor((W_{in}+2*padding[1]-kernel\_size[1])/stride[1]+1) 994 | \end{aligned} 995 | $$ 996 | 997 | 998 | **Example:** 999 | ```python 1000 | >>> # pool of square window of size=3, stride=2 1001 | >>> m = nn.AvgPool2d(3, stride=2) 1002 | >>> # pool of non-square window 1003 | >>> m = nn.AvgPool2d((3, 2), stride=(2, 1)) 1004 | >>> input = autograd.Variable(torch.randn(20, 16, 50, 32)) 1005 | >>> output = m(input) 1006 | ``` 1007 | 1008 | ### class torch.nn.AvgPool3d(kernel\_size, stride=None) 1009 | 1010 | 对信号的输入通道,提供3维的平均池化(`average pooling`) 1011 | 输入信号的大小(N,C,D,H,W),输出大小(N,C,D_out,H_out,W_out)和池化窗口大小(kD,kH,kW)的关系是: 1012 | 1013 | $$ 1014 | \begin{aligned} 1015 | 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) 1016 | \end{aligned} 1017 | $$ 1018 | 如果`padding`不是0,会在输入的每一边添加相应数目0 1019 | 1020 | **参数:** 1021 | 1022 | - kernel_size(`int` or `tuple`) - 池化窗口大小 1023 | - stride(`int` or `tuple`, `optional`) - max `pooling`的窗口移动的步长。默认值是`kernel_size` 1024 | 1025 | 1026 | **shape:** 1027 | 输入大小:(N,C,D_in,H_in,W_in) 1028 | 输出大小:(N,C,D_out,H_out,W_out) 1029 | $$\begin{aligned} 1030 | D_{out}=floor((D_{in}+2*padding[0]-kernel\_size[0])/stride[0]+1)\\ 1031 | H_{out}=floor((H_{in}+2*padding[1]-kernel\_size[1])/stride[1]+1)\\ 1032 | W_{out}=floor((W_{in}+2*padding[2]-kernel\_size[2])/stride[2]+1) 1033 | \end{aligned} 1034 | $$ 1035 | 1036 | **Example:** 1037 | ```python 1038 | >>> # pool of square window of size=3, stride=2 1039 | >>> m = nn.AvgPool3d(3, stride=2) 1040 | >>> # pool of non-square window 1041 | >>> m = nn.AvgPool3d((3, 2, 2), stride=(2, 1, 2)) 1042 | >>> input = autograd.Variable(torch.randn(20, 16, 50,44, 31)) 1043 | >>> output = m(input) 1044 | ``` 1045 | 1046 | ### class torch.nn.FractionalMaxPool2d(kernel\_size, output\_size=None, output\_ratio=None, return\_indices=False, \_random\_samples=None) 1047 | 1048 | 对输入的信号,提供2维的分数最大化池化操作 1049 | 分数最大化池化的细节请阅读[论文](https://arxiv.org/abs/1412.6071) 1050 | 由目标输出大小确定的随机步长,在$kH*kW$区域进行最大池化操作。输出特征和输入特征的数量相同。 1051 | 1052 | **参数:** 1053 | 1054 | - kernel_size(`int` or `tuple`) - 最大池化操作时的窗口大小。可以是一个数字(表示`K*K`的窗口),也可以是一个元组(`kh*kw`) 1055 | - output_size - 输出图像的尺寸。可以使用一个`tuple`指定(oH,oW),也可以使用一个数字oH指定一个oH*oH的输出。 1056 | - output_ratio – 将输入图像的大小的百分比指定为输出图片的大小,使用一个范围在(0,1)之间的数字指定 1057 | - return_indices - 默认值`False`,如果设置为`True`,会返回输出的索引,索引对 `nn.MaxUnpool2d`有用。 1058 | 1059 | **Example:** 1060 | ```python 1061 | >>> # pool of square window of size=3, and target output size 13x12 1062 | >>> m = nn.FractionalMaxPool2d(3, output_size=(13, 12)) 1063 | >>> # pool of square window and target output size being half of input image size 1064 | >>> m = nn.FractionalMaxPool2d(3, output_ratio=(0.5, 0.5)) 1065 | >>> input = autograd.Variable(torch.randn(20, 16, 50, 32)) 1066 | >>> output = m(input) 1067 | ``` 1068 | 1069 | ### class torch.nn.LPPool2d(norm\_type, kernel\_size, stride=None, ceil\_mode=False) 1070 | 对输入信号提供2维的幂平均池化操作。 1071 | 输出的计算方式: 1072 | $$f(x)=pow(sum(X,p),1/p)$$ 1073 | 1074 | - 当p为无穷大的时候时,等价于最大池化操作 1075 | - 当`p=1`时,等价于平均池化操作 1076 | 1077 | 参数`kernel_size`, `stride`的数据类型: 1078 | 1079 | - `int`,池化窗口的宽和高相等 1080 | - `tuple`数组(两个数字的),一个元素是池化窗口的高,另一个是宽 1081 | 1082 | 1083 | **参数** 1084 | 1085 | - kernel_size: 池化窗口的大小 1086 | - stride:池化窗口移动的步长。`kernel_size`是默认值 1087 | - ceil_mode: `ceil_mode=True`时,将使用向下取整代替向上取整 1088 | 1089 | **shape** 1090 | 1091 | - 输入:(N,C,H_in,W_in) 1092 | - 输出:(N,C,H_out,W_out) 1093 | $$\begin{aligned} 1094 | H_{out} = floor((H_{in}+2*padding[0]-dilation[0]*(kernel\_size[0]-1)-1)/stride[0]+1)\\ 1095 | W_{out} = floor((W_{in}+2*padding[1]-dilation[1]*(kernel\_size[1]-1)-1)/stride[1]+1) 1096 | \end{aligned} 1097 | $$ 1098 | 1099 | **Example:** 1100 | ```python 1101 | >>> # power-2 pool of square window of size=3, stride=2 1102 | >>> m = nn.LPPool2d(2, 3, stride=2) 1103 | >>> # pool of non-square window of power 1.2 1104 | >>> m = nn.LPPool2d(1.2, (3, 2), stride=(2, 1)) 1105 | >>> input = autograd.Variable(torch.randn(20, 16, 50, 32)) 1106 | >>> output = m(input) 1107 | ``` 1108 | 1109 | ### class torch.nn.AdaptiveMaxPool1d(output\_size, return\_indices=False) 1110 | 对输入信号,提供1维的自适应最大池化操作 1111 | 对于任何输入大小的输入,可以将输出尺寸指定为H,但是输入和输出特征的数目不会变化。 1112 | 1113 | **参数:** 1114 | 1115 | - output_size: 输出信号的尺寸 1116 | - return\_indices: 如果设置为`True`,会返回输出的索引。对 `nn.MaxUnpool1d`有用,默认值是`False` 1117 | 1118 | **Example:** 1119 | ```python 1120 | >>> # target output size of 5 1121 | >>> m = nn.AdaptiveMaxPool1d(5) 1122 | >>> input = autograd.Variable(torch.randn(1, 64, 8)) 1123 | >>> output = m(input) 1124 | ``` 1125 | ### class torch.nn.AdaptiveMaxPool2d(output\_size, return\_indices=False) 1126 | 对输入信号,提供2维的自适应最大池化操作 1127 | 对于任何输入大小的输入,可以将输出尺寸指定为H*W,但是输入和输出特征的数目不会变化。 1128 | 1129 | **参数:** 1130 | 1131 | - output_size: 输出信号的尺寸,可以用(H,W)表示`H*W`的输出,也可以使用数字`H`表示`H*H`大小的输出 1132 | - return_indices: 如果设置为`True`,会返回输出的索引。对 `nn.MaxUnpool2d`有用,默认值是`False` 1133 | 1134 | **Example:** 1135 | ```python 1136 | >>> # target output size of 5x7 1137 | >>> m = nn.AdaptiveMaxPool2d((5,7)) 1138 | >>> input = autograd.Variable(torch.randn(1, 64, 8, 9)) 1139 | >>> # target output size of 7x7 (square) 1140 | >>> m = nn.AdaptiveMaxPool2d(7) 1141 | >>> input = autograd.Variable(torch.randn(1, 64, 10, 9)) 1142 | >>> output = m(input) 1143 | ``` 1144 | 1145 | ### class torch.nn.AdaptiveAvgPool1d(output\_size) 1146 | 对输入信号,提供1维的自适应平均池化操作 1147 | 对于任何输入大小的输入,可以将输出尺寸指定为H*W,但是输入和输出特征的数目不会变化。 1148 | 1149 | **参数:** 1150 | 1151 | - output_size: 输出信号的尺寸 1152 | 1153 | **Example:** 1154 | ```python 1155 | >>> # target output size of 5 1156 | >>> m = nn.AdaptiveAvgPool1d(5) 1157 | >>> input = autograd.Variable(torch.randn(1, 64, 8)) 1158 | >>> output = m(input) 1159 | ``` 1160 | 1161 | ### class torch.nn.AdaptiveAvgPool2d(output\_size) 1162 | 对输入信号,提供2维的自适应平均池化操作 1163 | 对于任何输入大小的输入,可以将输出尺寸指定为`H*W`,但是输入和输出特征的数目不会变化。 1164 | 1165 | **参数:** 1166 | 1167 | - output_size: 输出信号的尺寸,可以用(H,W)表示`H*W`的输出,也可以使用耽搁数字H表示H*H大小的输出 1168 | 1169 | **Example:** 1170 | ```python 1171 | >>> # target output size of 5x7 1172 | >>> m = nn.AdaptiveAvgPool2d((5,7)) 1173 | >>> input = autograd.Variable(torch.randn(1, 64, 8, 9)) 1174 | >>> # target output size of 7x7 (square) 1175 | >>> m = nn.AdaptiveAvgPool2d(7) 1176 | >>> input = autograd.Variable(torch.randn(1, 64, 10, 9)) 1177 | >>> output = m(input) 1178 | ``` 1179 | 1180 | ## Non-Linear Activations [[source]](http://pytorch.org/docs/nn.html#non-linear-activations) 1181 | 1182 | > class torch.nn.ReLU(inplace=False) [[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#ReLU) 1183 | 1184 | 对输入运用修正线性单元函数${ReLU}(x)= max(0, x)$, 1185 | 1186 | 参数: inplace-选择是否进行覆盖运算 1187 | 1188 | shape: 1189 | 1190 | - 输入:$(N, *)$,*代表任意数目附加维度 1191 | - 输出:$(N, *)$,与输入拥有同样的shape属性 1192 | 1193 | 例子: 1194 | 1195 | ```python 1196 | >>> m = nn.ReLU() 1197 | >>> input = autograd.Variable(torch.randn(2)) 1198 | >>> print(input) 1199 | >>> print(m(input)) 1200 | ``` 1201 | 1202 | > class torch.nn.ReLU6(inplace=False) [[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#ReLU6) 1203 | 1204 | 对输入的每一个元素运用函数${ReLU6}(x) = min(max(0,x), 6)$, 1205 | 1206 | 参数: inplace-选择是否进行覆盖运算 1207 | 1208 | shape: 1209 | 1210 | - 输入:$(N, *)$,*代表任意数目附加维度 1211 | - 输出:$(N, *)$,与输入拥有同样的shape属性 1212 | 1213 | 例子: 1214 | 1215 | ```python 1216 | >>> m = nn.ReLU6() 1217 | >>> input = autograd.Variable(torch.randn(2)) 1218 | >>> print(input) 1219 | >>> print(m(input)) 1220 | ``` 1221 | > class torch.nn.ELU(alpha=1.0, inplace=False) [[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#ELU) 1222 | 1223 | 对输入的每一个元素运用函数$f(x) = max(0,x) + min(0, alpha * (e^x - 1))$, 1224 | 1225 | shape: 1226 | 1227 | - 输入:$(N, *)$,星号代表任意数目附加维度 1228 | - 输出:$(N, *)$与输入拥有同样的shape属性 1229 | 1230 | 例子: 1231 | 1232 | ```python 1233 | >>> m = nn.ELU() 1234 | >>> input = autograd.Variable(torch.randn(2)) 1235 | >>> print(input) 1236 | >>> print(m(input)) 1237 | ``` 1238 | > class torch.nn.PReLU(num_parameters=1, init=0.25)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#PReLU) 1239 | 1240 | 对输入的每一个元素运用函数$PReLU(x) = max(0,x) + a * min(0,x)$,`a`是一个可学习参数。当没有声明时,`nn.PReLU()`在所有的输入中只有一个参数`a`;如果是`nn.PReLU(nChannels)`,`a`将应用到每个输入。 1241 | 1242 | 注意:当为了表现更佳的模型而学习参数`a`时不要使用权重衰减(weight decay) 1243 | 1244 | 参数: 1245 | 1246 | - num_parameters:需要学习的`a`的个数,默认等于1 1247 | - init:`a`的初始值,默认等于0.25 1248 | 1249 | shape: 1250 | 1251 | - 输入:$(N, *)$,*代表任意数目附加维度 1252 | - 输出:$(N, *)$,与输入拥有同样的shape属性 1253 | 1254 | 例子: 1255 | 1256 | ```python 1257 | >>> m = nn.PReLU() 1258 | >>> input = autograd.Variable(torch.randn(2)) 1259 | >>> print(input) 1260 | >>> print(m(input)) 1261 | ``` 1262 | > class torch.nn.LeakyReLU(negative_slope=0.01, inplace=False) [[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#LeakyReLU) 1263 | 1264 | 对输入的每一个元素运用$f(x) = max(0, x) + {negative\_slope} * min(0, x)$ 1265 | 1266 | 参数: 1267 | 1268 | - negative_slope:控制负斜率的角度,默认等于0.01 1269 | - inplace-选择是否进行覆盖运算 1270 | 1271 | shape: 1272 | 1273 | - 输入:$(N, *)$,*代表任意数目附加维度 1274 | - 输出:$(N, *)$,与输入拥有同样的shape属性 1275 | 1276 | 例子: 1277 | 1278 | ```python 1279 | >>> m = nn.LeakyReLU(0.1) 1280 | >>> input = autograd.Variable(torch.randn(2)) 1281 | >>> print(input) 1282 | >>> print(m(input)) 1283 | ``` 1284 | 1285 | > class torch.nn.Threshold(threshold, value, inplace=False) [[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Threshold) 1286 | 1287 | Threshold定义: 1288 | 1289 | $$ 1290 | y = x ,if\ x >= threshold\\ 1291 | y = value,if\ x < threshold 1292 | $$ 1293 | 1294 | 参数: 1295 | 1296 | - threshold:阈值 1297 | - value:输入值小于阈值则会被value代替 1298 | - inplace:选择是否进行覆盖运算 1299 | 1300 | 1301 | shape: 1302 | 1303 | - 输入:$(N, *)$,*代表任意数目附加维度 1304 | - 输出:$(N, *)$,与输入拥有同样的shape属性 1305 | 1306 | 例子: 1307 | 1308 | ```python 1309 | >>> m = nn.Threshold(0.1, 20) 1310 | >>> input = Variable(torch.randn(2)) 1311 | >>> print(input) 1312 | >>> print(m(input)) 1313 | ``` 1314 | > class torch.nn.Hardtanh(min_value=-1, max_value=1, inplace=False) [[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Hardtanh) 1315 | 1316 | 对每个元素, 1317 | 1318 | $$ 1319 | f(x) = +1, if\ x > 1;\\ 1320 | f(x) = -1, if\ x < -1;\\ 1321 | f(x) = x, otherwise 1322 | $$ 1323 | 1324 | 线性区域的范围[-1,1]可以被调整 1325 | 1326 | 参数: 1327 | 1328 | - min_value:线性区域范围最小值 1329 | - max_value:线性区域范围最大值 1330 | - inplace:选择是否进行覆盖运算 1331 | 1332 | shape: 1333 | 1334 | - 输入:(N, \*),*表示任意维度组合 1335 | - 输出:(N, *),与输入有相同的shape属性 1336 | 1337 | 例子: 1338 | 1339 | ```python 1340 | >>> m = nn.Hardtanh() 1341 | >>> input = autograd.Variable(torch.randn(2)) 1342 | >>> print(input) 1343 | >>> print(m(input)) 1344 | ``` 1345 | > class torch.nn.Sigmoid [[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Sigmoid) 1346 | 1347 | 对每个元素运用Sigmoid函数,Sigmoid 定义如下: 1348 | 1349 | $$f(x) = 1 / ( 1 + e^{-x})$$ 1350 | 1351 | shape: 1352 | 1353 | - 输入:(N, \*),*表示任意维度组合 1354 | - 输出:(N, *),与输入有相同的shape属性 1355 | 1356 | 例子: 1357 | 1358 | ```python 1359 | >>> m = nn.Sigmoid() 1360 | >>> input = autograd.Variable(torch.randn(2)) 1361 | >>> print(input) 1362 | >>> print(m(input)) 1363 | ``` 1364 | > class torch.nn.Tanh [[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Tanh) 1365 | 1366 | 对输入的每个元素, 1367 | 1368 | $$f(x) = \frac{e^{x} - e^{-x}} {e^{x} + e^{x}}$$ 1369 | 1370 | shape: 1371 | 1372 | - 输入:(N, \*),*表示任意维度组合 1373 | - 输出:(N, *),与输入有相同的shape属性 1374 | 1375 | 例子: 1376 | 1377 | ```python 1378 | >>> m = nn.Tanh() 1379 | >>> input = autograd.Variable(torch.randn(2)) 1380 | >>> print(input) 1381 | >>> print(m(input)) 1382 | ``` 1383 | > class torch.nn.LogSigmoid [[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#LogSigmoid) 1384 | 1385 | 对输入的每个元素,$LogSigmoid(x) = log( 1 / ( 1 + e^{-x}))$ 1386 | 1387 | shape: 1388 | 1389 | - 输入:(N, \*),*表示任意维度组合 1390 | - 输出:(N, *),与输入有相同的shape属性 1391 | 1392 | 例子: 1393 | 1394 | ```python 1395 | >>> m = nn.LogSigmoid() 1396 | >>> input = autograd.Variable(torch.randn(2)) 1397 | >>> print(input) 1398 | >>> print(m(input)) 1399 | ``` 1400 | > class torch.nn.Softplus(beta=1, threshold=20)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Softplus) 1401 | 1402 | 对每个元素运用Softplus函数,Softplus 定义如下: 1403 | 1404 | $$f(x) = \frac{1}{beta} * log(1 + e^{(beta * x_i)})$$ 1405 | 1406 | Softplus函数是ReLU函数的平滑逼近,Softplus函数可以使得输出值限定为正数。 1407 | 1408 | 为了保证数值稳定性,线性函数的转换可以使输出大于某个值。 1409 | 1410 | 参数: 1411 | 1412 | - beta:Softplus函数的beta值 1413 | - threshold:阈值 1414 | 1415 | shape: 1416 | 1417 | - 输入:(N, \*),*表示任意维度组合 1418 | - 输出:(N, *),与输入有相同的shape属性 1419 | 1420 | 例子: 1421 | 1422 | ```python 1423 | >>> m = nn.Softplus() 1424 | >>> input = autograd.Variable(torch.randn(2)) 1425 | >>> print(input) 1426 | >>> print(m(input)) 1427 | ``` 1428 | > class torch.nn.Softshrink(lambd=0.5)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Softshrink) 1429 | 1430 | 对每个元素运用Softshrink函数,Softshrink函数定义如下: 1431 | 1432 | $$ 1433 | f(x) = x-lambda, if\ x > lambda\\ 1434 | f(x) = x+lambda, if\ x < -lambda\\ 1435 | f(x) = 0, otherwise 1436 | $$ 1437 | 1438 | 参数: 1439 | 1440 | lambd:Softshrink函数的lambda值,默认为0.5 1441 | 1442 | shape: 1443 | 1444 | - 输入:(N, \*),*表示任意维度组合 1445 | - 输出:(N, *),与输入有相同的shape属性 1446 | 1447 | 例子: 1448 | 1449 | ```python 1450 | >>> m = nn.Softshrink() 1451 | >>> input = autograd.Variable(torch.randn(2)) 1452 | >>> print(input) 1453 | >>> print(m(input)) 1454 | ``` 1455 | > class torch.nn.Softsign [[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Softsign) 1456 | 1457 | $f(x) = x / (1 + |x|)$ 1458 | 1459 | shape: 1460 | 1461 | - 输入:(N, \*),*表示任意维度组合 1462 | - 输出:(N, *),与输入有相同的shape属性 1463 | 1464 | 例子: 1465 | 1466 | ```python 1467 | >>> m = nn.Softsign() 1468 | >>> input = autograd.Variable(torch.randn(2)) 1469 | >>> print(input) 1470 | >>> print(m(input)) 1471 | ``` 1472 | 1473 | > class torch.nn.Softshrink(lambd=0.5)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Softshrink) 1474 | 1475 | 对每个元素运用Tanhshrink函数,Tanhshrink函数定义如下: 1476 | 1477 | $$ 1478 | Tanhshrink(x) = x - Tanh(x) 1479 | $$ 1480 | 1481 | shape: 1482 | 1483 | - 输入:(N, \*),*表示任意维度组合 1484 | - 输出:(N, *),与输入有相同的shape属性 1485 | 1486 | 例子: 1487 | 1488 | ```python 1489 | >>> m = nn.Tanhshrink() 1490 | >>> input = autograd.Variable(torch.randn(2)) 1491 | >>> print(input) 1492 | >>> print(m(input)) 1493 | ``` 1494 | > class torch.nn.Softmin [[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Softmin) 1495 | 1496 | 对n维输入张量运用Softmin函数,将张量的每个元素缩放到(0,1)区间且和为1。Softmin函数定义如下: 1497 | 1498 | $$f_i(x) = \frac{e^{(-x_i - shift)}} { \sum^j e^{(-x_j - shift)}},shift = max (x_i)$$ 1499 | 1500 | shape: 1501 | 1502 | - 输入:(N, L) 1503 | - 输出:(N, L) 1504 | 1505 | 例子: 1506 | 1507 | ```python 1508 | >>> m = nn.Softmin() 1509 | >>> input = autograd.Variable(torch.randn(2, 3)) 1510 | >>> print(input) 1511 | >>> print(m(input)) 1512 | ``` 1513 | 1514 | ---------- 1515 | 1516 | 1517 | > class torch.nn.Softmax [[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#Softmax) 1518 | 1519 | 对n维输入张量运用Softmax函数,将张量的每个元素缩放到(0,1)区间且和为1。Softmax函数定义如下: 1520 | 1521 | $$f_i(x) = \frac{e^{(x_i - shift)}} { \sum^j e^{(x_j - shift)}},shift = max (x_i)$$ 1522 | 1523 | shape: 1524 | 1525 | - 输入:(N, L) 1526 | - 输出:(N, L) 1527 | 1528 | 返回结果是一个与输入维度相同的张量,每个元素的取值范围在(0,1)区间。 1529 | 1530 | 例子: 1531 | 1532 | ```python 1533 | >>> m = nn.Softmax() 1534 | >>> input = autograd.Variable(torch.randn(2, 3)) 1535 | >>> print(input) 1536 | >>> print(m(input)) 1537 | ``` 1538 | 1539 | > class torch.nn.LogSoftmax [[source]](http://pytorch.org/docs/_modules/torch/nn/modules/activation.html#LogSoftmax) 1540 | 1541 | 对n维输入张量运用LogSoftmax函数,LogSoftmax函数定义如下: 1542 | 1543 | $$f_i(x) = log \frac{e^{(x_i)}} {a}, a = \sum^j e^{(x_j)}$$ 1544 | 1545 | shape: 1546 | 1547 | - 输入:(N, L) 1548 | - 输出:(N, L) 1549 | 1550 | 例子: 1551 | 1552 | ```python 1553 | >>> m = nn.LogSoftmax() 1554 | >>> input = autograd.Variable(torch.randn(2, 3)) 1555 | >>> print(input) 1556 | >>> print(m(input)) 1557 | ``` 1558 | 1559 | ## Normalization layers [[source]](http://pytorch.org/docs/nn.html#normalization-layers) 1560 | ### class torch.nn.BatchNorm1d(num_features, eps=1e-05, momentum=0.1, affine=True) [[source]](http://pytorch.org/docs/nn.html#torch.nn.BatchNorm1d) 1561 | 1562 | 对小批量(mini-batch)的2d或3d输入进行批标准化(Batch Normalization)操作 1563 | 1564 | $$ y = \frac{x - mean[x]}{ \sqrt{Var[x]} + \epsilon} * gamma + beta $$ 1565 | 1566 | 在每一个小批量(mini-batch)数据中,计算输入各个维度的均值和标准差。gamma与beta是可学习的大小为C的参数向量(C为输入大小) 1567 | 1568 | 在训练时,该层计算每次输入的均值与方差,并进行移动平均。移动平均默认的动量值为0.1。 1569 | 1570 | 在验证时,训练求得的均值/方差将用于标准化验证数据。 1571 | 1572 | **参数:** 1573 | 1574 | - **num_features:** 来自期望输入的特征数,该期望输入的大小为'batch_size x num_features [x width]' 1575 | - **eps:** 为保证数值稳定性(分母不能趋近或取0),给分母加上的值。默认为1e-5。 1576 | - **momentum:** 动态均值和动态方差所使用的动量。默认为0.1。 1577 | - **affine:** 一个布尔值,当设为true,给该层添加可学习的仿射变换参数。 1578 | 1579 | **Shape:** 1580 | - 输入:(N, C)或者(N, C, L) 1581 | - 输出:(N, C)或者(N,C,L)(输入输出相同) 1582 | 1583 | **例子** 1584 | ```python 1585 | >>> # With Learnable Parameters 1586 | >>> m = nn.BatchNorm1d(100) 1587 | >>> # Without Learnable Parameters 1588 | >>> m = nn.BatchNorm1d(100, affine=False) 1589 | >>> input = autograd.Variable(torch.randn(20, 100)) 1590 | >>> output = m(input) 1591 | ``` 1592 | *** 1593 | 1594 | ### 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) 1595 | 1596 | 对小批量(mini-batch)3d数据组成的4d输入进行批标准化(Batch Normalization)操作 1597 | 1598 | $$ y = \frac{x - mean[x]}{ \sqrt{Var[x]} + \epsilon} * gamma + beta $$ 1599 | 1600 | 在每一个小批量(mini-batch)数据中,计算输入各个维度的均值和标准差。gamma与beta是可学习的大小为C的参数向量(C为输入大小) 1601 | 1602 | 在训练时,该层计算每次输入的均值与方差,并进行移动平均。移动平均默认的动量值为0.1。 1603 | 1604 | 在验证时,训练求得的均值/方差将用于标准化验证数据。 1605 | 1606 | **参数:** 1607 | 1608 | - **num_features:** 来自期望输入的特征数,该期望输入的大小为'batch_size x num_features x height x width' 1609 | - **eps:** 为保证数值稳定性(分母不能趋近或取0),给分母加上的值。默认为1e-5。 1610 | - **momentum:** 动态均值和动态方差所使用的动量。默认为0.1。 1611 | - **affine:** 一个布尔值,当设为true,给该层添加可学习的仿射变换参数。 1612 | 1613 | **Shape:** 1614 | - 输入:(N, C,H, W) 1615 | - 输出:(N, C, H, W)(输入输出相同) 1616 | 1617 | **例子** 1618 | ```python 1619 | >>> # With Learnable Parameters 1620 | >>> m = nn.BatchNorm2d(100) 1621 | >>> # Without Learnable Parameters 1622 | >>> m = nn.BatchNorm2d(100, affine=False) 1623 | >>> input = autograd.Variable(torch.randn(20, 100, 35, 45)) 1624 | >>> output = m(input) 1625 | ``` 1626 | *** 1627 | 1628 | ### class torch.nn.BatchNorm3d(num_features, eps=1e-05, momentum=0.1, affine=True)[[source]](http://pytorch.org/docs/nn.html#torch.nn.BatchNorm3d) 1629 | 1630 | 对小批量(mini-batch)4d数据组成的5d输入进行批标准化(Batch Normalization)操作 1631 | 1632 | $$ y = \frac{x - mean[x]}{ \sqrt{Var[x]} + \epsilon} * gamma + beta $$ 1633 | 1634 | 在每一个小批量(mini-batch)数据中,计算输入各个维度的均值和标准差。gamma与beta是可学习的大小为C的参数向量(C为输入大小) 1635 | 1636 | 在训练时,该层计算每次输入的均值与方差,并进行移动平均。移动平均默认的动量值为0.1。 1637 | 1638 | 在验证时,训练求得的均值/方差将用于标准化验证数据。 1639 | 1640 | **参数:** 1641 | 1642 | - **num_features:** 来自期望输入的特征数,该期望输入的大小为'batch_size x num_features depth x height x width' 1643 | - **eps:** 为保证数值稳定性(分母不能趋近或取0),给分母加上的值。默认为1e-5。 1644 | - **momentum:** 动态均值和动态方差所使用的动量。默认为0.1。 1645 | - **affine:** 一个布尔值,当设为true,给该层添加可学习的仿射变换参数。 1646 | 1647 | **Shape:** 1648 | - 输入:(N, C,D, H, W) 1649 | - 输出:(N, C, D, H, W)(输入输出相同) 1650 | 1651 | **例子** 1652 | ```python 1653 | >>> # With Learnable Parameters 1654 | >>> m = nn.BatchNorm3d(100) 1655 | >>> # Without Learnable Parameters 1656 | >>> m = nn.BatchNorm3d(100, affine=False) 1657 | >>> input = autograd.Variable(torch.randn(20, 100, 35, 45, 10)) 1658 | >>> output = m(input) 1659 | ``` 1660 | *** 1661 | 1662 | 1663 | 1664 | ## Recurrent layers 1665 | ### class torch.nn.RNN(* args, ** kwargs)[source] 1666 | 1667 | 将一个多层的 `Elman RNN`,激活函数为`tanh`或者`ReLU`,用于输入序列。 1668 | 1669 | 对输入序列中每个元素,`RNN`每层的计算公式为 1670 | $$ 1671 | h_t=tanh(w_{ih}* x_t+b_{ih}+w_{hh}* h_{t-1}+b_{hh}) 1672 | $$ 1673 | $h_t$是时刻$t$的隐状态。 $x_t$是上一层时刻$t$的隐状态,或者是第一层在时刻$t$的输入。如果`nonlinearity='relu'`,那么将使用`relu`代替`tanh`作为激活函数。 1674 | 1675 | 参数说明: 1676 | 1677 | - input_size – 输入`x`的特征数量。 1678 | 1679 | - hidden_size – 隐层的特征数量。 1680 | 1681 | - num_layers – RNN的层数。 1682 | 1683 | - nonlinearity – 指定非线性函数使用`tanh`还是`relu`。默认是`tanh`。 1684 | 1685 | - bias – 如果是`False`,那么RNN层就不会使用偏置权重 $b_ih$和$b_hh$,默认是`True` 1686 | 1687 | - batch_first – 如果`True`的话,那么输入`Tensor`的shape应该是[batch_size, time_step, feature],输出也是这样。 1688 | - dropout – 如果值非零,那么除了最后一层外,其它层的输出都会套上一个`dropout`层。 1689 | 1690 | - bidirectional – 如果`True`,将会变成一个双向`RNN`,默认为`False`。 1691 | 1692 | 1693 | `RNN`的输入: 1694 | **(input, h_0)** 1695 | - input (seq_len, batch, input_size): 保存输入序列特征的`tensor`。`input`可以是被填充的变长的序列。细节请看`torch.nn.utils.rnn.pack_padded_sequence()` 1696 | 1697 | - h_0 (num_layers * num_directions, batch, hidden_size): 保存着初始隐状态的`tensor` 1698 | 1699 | `RNN`的输出: 1700 | **(output, h_n)** 1701 | 1702 | - output (seq_len, batch, hidden_size * num_directions): 保存着`RNN`最后一层的输出特征。如果输入是被填充过的序列,那么输出也是被填充的序列。 1703 | - h_n (num_layers * num_directions, batch, hidden_size): 保存着最后一个时刻隐状态。 1704 | 1705 | `RNN`模型参数: 1706 | 1707 | - weight_ih_l[k] – 第`k`层的 `input-hidden` 权重, 可学习,形状是`(input_size x hidden_size)`。 1708 | 1709 | - weight_hh_l[k] – 第`k`层的 `hidden-hidden` 权重, 可学习,形状是`(hidden_size x hidden_size)` 1710 | 1711 | - bias_ih_l[k] – 第`k`层的 `input-hidden` 偏置, 可学习,形状是`(hidden_size)` 1712 | 1713 | - bias_hh_l[k] – 第`k`层的 `hidden-hidden` 偏置, 可学习,形状是`(hidden_size)` 1714 | 1715 | 示例: 1716 | ```python 1717 | rnn = nn.RNN(10, 20, 2) 1718 | input = Variable(torch.randn(5, 3, 10)) 1719 | h0 = Variable(torch.randn(2, 3, 20)) 1720 | output, hn = rnn(input, h0) 1721 | ``` 1722 | ### class torch.nn.LSTM(* args, ** kwargs)[source] 1723 | 1724 | 将一个多层的 `(LSTM)` 应用到输入序列。 1725 | 1726 | 对输入序列的每个元素,`LSTM`的每层都会执行以下计算: 1727 | $$ 1728 | \begin{aligned} 1729 | i_t &= sigmoid(W_{ii}x_t+b_{ii}+W_{hi}h_{t-1}+b_{hi}) \\ 1730 | f_t &= sigmoid(W_{if}x_t+b_{if}+W_{hf}h_{t-1}+b_{hf}) \\ 1731 | o_t &= sigmoid(W_{io}x_t+b_{io}+W_{ho}h_{t-1}+b_{ho})\\ 1732 | g_t &= tanh(W_{ig}x_t+b_{ig}+W_{hg}h_{t-1}+b_{hg})\\ 1733 | c_t &= f_t*c_{t-1}+i_t*g_t\\ 1734 | h_t &= o_t*tanh(c_t) 1735 | \end{aligned} 1736 | $$ 1737 | $h_t$是时刻$t$的隐状态,$c_t$是时刻$t$的细胞状态,$x_t$是上一层的在时刻$t$的隐状态或者是第一层在时刻$t$的输入。$i_t, f_t, g_t, o_t$ 分别代表 输入门,遗忘门,细胞和输出门。 1738 | 1739 | 参数说明: 1740 | 1741 | - input_size – 输入的特征维度 1742 | 1743 | - hidden_size – 隐状态的特征维度 1744 | 1745 | - num_layers – 层数(和时序展开要区分开) 1746 | 1747 | - bias – 如果为`False`,那么`LSTM`将不会使用$b_{ih},b_{hh}$,默认为`True`。 1748 | 1749 | - batch_first – 如果为`True`,那么输入和输出`Tensor`的形状为`(batch, seq, feature)` 1750 | 1751 | - dropout – 如果非零的话,将会在`RNN`的输出上加个`dropout`,最后一层除外。 1752 | 1753 | - bidirectional – 如果为`True`,将会变成一个双向`RNN`,默认为`False`。 1754 | 1755 | `LSTM`输入: 1756 | input, (h_0, c_0) 1757 | 1758 | - input (seq_len, batch, input_size): 包含输入序列特征的`Tensor`。也可以是`packed variable` ,详见 [pack_padded_sequence](#torch.nn.utils.rnn.pack_padded_sequence(input, lengths, batch_first=False[source]) 1759 | 1760 | - h_0 (num_layers * num_directions, batch, hidden_size):保存着`batch`中每个元素的初始化隐状态的`Tensor` 1761 | 1762 | - c_0 (num_layers * num_directions, batch, hidden_size): 保存着`batch`中每个元素的初始化细胞状态的`Tensor` 1763 | 1764 | `LSTM`输出 1765 | output, (h_n, c_n) 1766 | 1767 | - output (seq_len, batch, hidden_size * num_directions): 保存`RNN`最后一层的输出的`Tensor`。 如果输入是`torch.nn.utils.rnn.PackedSequence`,那么输出也是`torch.nn.utils.rnn.PackedSequence`。 1768 | 1769 | - h_n (num_layers * num_directions, batch, hidden_size): `Tensor`,保存着`RNN`最后一个时间步的隐状态。 1770 | 1771 | - c_n (num_layers * num_directions, batch, hidden_size): `Tensor`,保存着`RNN`最后一个时间步的细胞状态。 1772 | 1773 | `LSTM`模型参数: 1774 | 1775 | - weight_ih_l[k] – 第`k`层可学习的`input-hidden`权重($W_{ii}|W_{if}|W_{ig}|W_{io}$),形状为`(input_size x 4*hidden_size)` 1776 | 1777 | - weight_hh_l[k] – 第`k`层可学习的`hidden-hidden`权重($W_{hi}|W_{hf}|W_{hg}|W_{ho}$),形状为`(hidden_size x 4*hidden_size)`。 1778 | 1779 | - bias_ih_l[k] – 第`k`层可学习的`input-hidden`偏置($b_{ii}|b_{if}|b_{ig}|b_{io}$),形状为`( 4*hidden_size)` 1780 | 1781 | - bias_hh_l[k] – 第`k`层可学习的`hidden-hidden`偏置($b_{hi}|b_{hf}|b_{hg}|b_{ho}$),形状为`( 4*hidden_size)`。 1782 | 示例: 1783 | ```python 1784 | lstm = nn.LSTM(10, 20, 2) 1785 | input = Variable(torch.randn(5, 3, 10)) 1786 | h0 = Variable(torch.randn(2, 3, 20)) 1787 | c0 = Variable(torch.randn(2, 3, 20)) 1788 | output, hn = lstm(input, (h0, c0)) 1789 | ``` 1790 | 1791 | ### class torch.nn.GRU(* args, ** kwargs)[source] 1792 | 1793 | 将一个多层的`GRU`用于输入序列。 1794 | 1795 | 对输入序列中的每个元素,每层进行了一下计算: 1796 | 1797 | $$ 1798 | \begin{aligned} 1799 | r_t&=sigmoid(W_{ir}x_t+b_{ir}+W_{hr}h_{(t-1)}+b_{hr})\\ 1800 | i_t&=sigmoid(W_{ii}x_t+b_{ii}+W_{hi}h_{(t-1)}+b_{hi})\\ 1801 | n_t&=tanh(W_{in}x_t+b_{in}+rt*(W_{hn}h_{(t-1)}+b_{hn}))\\ 1802 | h_t&=(1-i_t)* nt+i_t*h(t-1) 1803 | \end{aligned} 1804 | $$ 1805 | $h_t$是是时间$t$的上的隐状态,$x_t$是前一层$t$时刻的隐状态或者是第一层的$t$时刻的输入,$r_t, i_t, n_t$分别是重置门,输入门和新门。 1806 | 1807 | 参数说明: 1808 | - input_size – 期望的输入$x$的特征值的维度 1809 | - hidden_size – 隐状态的维度 1810 | - num_layers – `RNN`的层数。 1811 | - bias – 如果为`False`,那么`RNN`层将不会使用`bias`,默认为`True`。 1812 | - batch_first – 如果为`True`的话,那么输入和输出的`tensor`的形状是`(batch, seq, feature)`。 1813 | - dropout – 如果非零的话,将会在`RNN`的输出上加个`dropout`,最后一层除外。 1814 | - bidirectional – 如果为`True`,将会变成一个双向`RNN`,默认为`False`。 1815 | 1816 | 输入: 1817 | input, h_0 1818 | 1819 | - input (seq_len, batch, input_size): 包含输入序列特征的`Tensor`。也可以是`packed variable` ,详见 [pack_padded_sequence](#torch.nn.utils.rnn.pack_padded_sequence(input, lengths, batch_first=False[source])。 1820 | 1821 | - h_0 (num_layers * num_directions, batch, hidden_size):保存着`batch`中每个元素的初始化隐状态的`Tensor` 1822 | 1823 | 输出: 1824 | output, h_n 1825 | 1826 | - output (seq_len, batch, hidden_size * num_directions): ten保存`RNN`最后一层的输出的`Tensor`。 如果输入是`torch.nn.utils.rnn.PackedSequence`,那么输出也是`torch.nn.utils.rnn.PackedSequence`。 1827 | 1828 | - h_n (num_layers * num_directions, batch, hidden_size): `Tensor`,保存着`RNN`最后一个时间步的隐状态。 1829 | 1830 | 变量: 1831 | 1832 | - weight_ih_l[k] – 第`k`层可学习的`input-hidden`权重($W_{ir}|W_{ii}|W_{in}$),形状为`(input_size x 3*hidden_size)` 1833 | 1834 | - weight_hh_l[k] – 第`k`层可学习的`hidden-hidden`权重($W_{hr}|W_{hi}|W_{hn}$),形状为`(hidden_size x 3*hidden_size)`。 1835 | 1836 | - bias_ih_l[k] – 第`k`层可学习的`input-hidden`偏置($b_{ir}|b_{ii}|b_{in}$),形状为`( 3*hidden_size)` 1837 | 1838 | - bias_hh_l[k] – 第`k`层可学习的`hidden-hidden`偏置($b_{hr}|b_{hi}|b_{hn}$),形状为`( 3*hidden_size)`。 1839 | 1840 | 1841 | 例子: 1842 | ```python 1843 | rnn = nn.GRU(10, 20, 2) 1844 | input = Variable(torch.randn(5, 3, 10)) 1845 | h0 = Variable(torch.randn(2, 3, 20)) 1846 | output, hn = rnn(input, h0) 1847 | ``` 1848 | 1849 | ### class torch.nn.RNNCell(input_size, hidden_size, bias=True, nonlinearity='tanh')[source] 1850 | 1851 | 一个 `Elan RNN cell`,激活函数是`tanh`或`ReLU`,用于输入序列。 1852 | 将一个多层的 `Elman RNNCell`,激活函数为`tanh`或者`ReLU`,用于输入序列。 1853 | $$ 1854 | h'=tanh(w_{ih}* x+b_{ih}+w_{hh}* h+b_{hh}) 1855 | $$ 1856 | 如果`nonlinearity=relu`,那么将会使用`ReLU`来代替`tanh`。 1857 | 1858 | 参数: 1859 | 1860 | - input_size – 输入$x$,特征的维度。 1861 | 1862 | - hidden_size – 隐状态特征的维度。 1863 | 1864 | - bias – 如果为`False`,`RNN cell`中将不会加入`bias`,默认为`True`。 1865 | 1866 | - nonlinearity – 用于选择非线性激活函数 [`tanh`|`relu`]. 默认值为: `tanh` 1867 | 1868 | 输入: 1869 | input, hidden 1870 | 1871 | - input (batch, input_size): 包含输入特征的`tensor`。 1872 | 1873 | - hidden (batch, hidden_size): 保存着初始隐状态值的`tensor`。 1874 | 1875 | 输出: h’ 1876 | 1877 | - h’ (batch, hidden_size):下一个时刻的隐状态。 1878 | 1879 | 变量: 1880 | 1881 | - weight_ih – `input-hidden` 权重, 可学习,形状是`(input_size x hidden_size)`。 1882 | 1883 | - weight_hh – `hidden-hidden` 权重, 可学习,形状是`(hidden_size x hidden_size)` 1884 | 1885 | - bias_ih – `input-hidden` 偏置, 可学习,形状是`(hidden_size)` 1886 | 1887 | - bias_hh – `hidden-hidden` 偏置, 可学习,形状是`(hidden_size)` 1888 | 1889 | 例子: 1890 | 1891 | ```python 1892 | rnn = nn.RNNCell(10, 20) 1893 | input = Variable(torch.randn(6, 3, 10)) 1894 | hx = Variable(torch.randn(3, 20)) 1895 | output = [] 1896 | for i in range(6): 1897 | hx = rnn(input[i], hx) 1898 | output.append(hx) 1899 | ``` 1900 | 1901 | ### class torch.nn.LSTMCell(input_size, hidden_size, bias=True)[source] 1902 | 1903 | `LSTM cell`。 1904 | $$ 1905 | \begin{aligned} 1906 | i &= sigmoid(W_{ii}x+b_{ii}+W_{hi}h+b_{hi}) \\ 1907 | f &= sigmoid(W_{if}x+b_{if}+W_{hf}h+b_{hf}) \\ 1908 | o &= sigmoid(W_{io}x+b_{io}+W_{ho}h+b_{ho})\\ 1909 | g &= tanh(W_{ig}x+b_{ig}+W_{hg}h+b_{hg})\\ 1910 | c' &= f_t*c_{t-1}+i_t*g_t\\ 1911 | h' &= o_t*tanh(c') 1912 | \end{aligned} 1913 | $$ 1914 | 1915 | 参数: 1916 | 1917 | - input_size – 输入的特征维度。 1918 | - hidden_size – 隐状态的维度。 1919 | - bias – 如果为`False`,那么将不会使用`bias`。默认为`True`。 1920 | 1921 | `LSTM`输入: 1922 | input, (h_0, c_0) 1923 | 1924 | - input (seq_len, batch, input_size): 包含输入序列特征的`Tensor`。也可以是`packed variable` ,详见 [pack_padded_sequence](#torch.nn.utils.rnn.pack_padded_sequence(input, lengths, batch_first=False[source]) 1925 | 1926 | - h_0 ( batch, hidden_size):保存着`batch`中每个元素的初始化隐状态的`Tensor` 1927 | 1928 | - c_0 (batch, hidden_size): 保存着`batch`中每个元素的初始化细胞状态的`Tensor` 1929 | 1930 | 输出: 1931 | h_1, c_1 1932 | 1933 | - h_1 (batch, hidden_size): 下一个时刻的隐状态。 1934 | - c_1 (batch, hidden_size): 下一个时刻的细胞状态。 1935 | 1936 | `LSTM`模型参数: 1937 | 1938 | - weight_ih – `input-hidden`权重($W_{ii}|W_{if}|W_{ig}|W_{io}$),形状为`(input_size x 4*hidden_size)` 1939 | 1940 | - weight_hh – `hidden-hidden`权重($W_{hi}|W_{hf}|W_{hg}|W_{ho}$),形状为`(hidden_size x 4*hidden_size)`。 1941 | 1942 | - bias_ih – `input-hidden`偏置($b_{ii}|b_{if}|b_{ig}|b_{io}$),形状为`( 4*hidden_size)` 1943 | 1944 | - bias_hh – `hidden-hidden`偏置($b_{hi}|b_{hf}|b_{hg}|b_{ho}$),形状为`( 4*hidden_size)`。 1945 | 1946 | Examples: 1947 | ```python 1948 | rnn = nn.LSTMCell(10, 20) 1949 | input = Variable(torch.randn(6, 3, 10)) 1950 | hx = Variable(torch.randn(3, 20)) 1951 | cx = Variable(torch.randn(3, 20)) 1952 | output = [] 1953 | for i in range(6): 1954 | hx, cx = rnn(input[i], (hx, cx)) 1955 | output.append(hx) 1956 | ``` 1957 | 1958 | ### class torch.nn.GRUCell(input_size, hidden_size, bias=True)[source] 1959 | 1960 | 一个`GRU cell`。 1961 | $$ 1962 | \begin{aligned} 1963 | r&=sigmoid(W_{ir}x+b_{ir}+W_{hr}h+b_{hr})\\ 1964 | i&=sigmoid(W_{ii}x+b_{ii}+W_{hi}h+b_{hi})\\ 1965 | n&=tanh(W_{in}x+b_{in}+r*(W_{hn}h+b_{hn}))\\ 1966 | h'&=(1-i)* n+i*h 1967 | \end{aligned} 1968 | $$ 1969 | 1970 | 参数说明: 1971 | - input_size – 期望的输入$x$的特征值的维度 1972 | - hidden_size – 隐状态的维度 1973 | - bias – 如果为`False`,那么`RNN`层将不会使用`bias`,默认为`True`。 1974 | 1975 | 输入: 1976 | input, h_0 1977 | 1978 | - input (batch, input_size): 包含输入特征的`Tensor` 1979 | 1980 | - h_0 (batch, hidden_size):保存着`batch`中每个元素的初始化隐状态的`Tensor` 1981 | 1982 | 输出: 1983 | h_1 1984 | 1985 | - h_1 (batch, hidden_size): `Tensor`,保存着`RNN`下一个时刻的隐状态。 1986 | 1987 | 变量: 1988 | 1989 | - weight_ih – `input-hidden`权重($W_{ir}|W_{ii}|W_{in}$),形状为`(input_size x 3*hidden_size)` 1990 | 1991 | - weight_hh – `hidden-hidden`权重($W_{hr}|W_{hi}|W_{hn}$),形状为`(hidden_size x 3*hidden_size)`。 1992 | 1993 | - bias_ih – `input-hidden`偏置($b_{ir}|b_{ii}|b_{in}$),形状为`( 3*hidden_size)` 1994 | 1995 | - bias_hh – `hidden-hidden`偏置($b_{hr}|b_{hi}|b_{hn}$),形状为`( 3*hidden_size)`。 1996 | 1997 | 例子: 1998 | ```python 1999 | rnn = nn.GRUCell(10, 20) 2000 | input = Variable(torch.randn(6, 3, 10)) 2001 | hx = Variable(torch.randn(3, 20)) 2002 | output = [] 2003 | for i in range(6): 2004 | hx = rnn(input[i], hx) 2005 | output.append(hx) 2006 | ``` 2007 | ## Linear layers 2008 | ```python 2009 | class torch.nn.Linear(in_features, out_features, bias=True) 2010 | ``` 2011 | 2012 | 对输入数据做线性变换:\\(y = Ax + b\\) 2013 | 2014 | **参数:** 2015 | 2016 | - **in_features** - 每个输入样本的大小 2017 | - **out_features** - 每个输出样本的大小 2018 | - **bias** - 若设置为False,这层不会学习偏置。默认值:True 2019 | 2020 | **形状:** 2021 | 2022 | - **输入:** \\((N, in\\_features)\\) 2023 | - **输出:** \\((N, out\\_features)\\) 2024 | 2025 | **变量:** 2026 | 2027 | - **weight** -形状为(out_features x in_features)的模块中可学习的权值 2028 | - **bias** -形状为(out_features)的模块中可学习的偏置 2029 | 2030 | **例子:** 2031 | 2032 | ```python 2033 | >>> m = nn.Linear(20, 30) 2034 | >>> input = autograd.Variable(torch.randn(128, 20)) 2035 | >>> output = m(input) 2036 | >>> print(output.size()) 2037 | ``` 2038 | 2039 | ## Dropout layers 2040 | ``` python 2041 | class torch.nn.Dropout(p=0.5, inplace=False) 2042 | ``` 2043 | 2044 | 随机将输入张量中部分元素设置为0。对于每次前向调用,被置0的元素都是随机的。 2045 | 2046 | **参数:** 2047 | 2048 | - **p** - 将元素置0的概率。默认值:0.5 2049 | - **in-place** - 若设置为True,会在原地执行操作。默认值:False 2050 | 2051 | **形状:** 2052 | 2053 | - **输入:** 任意。输入可以为任意形状。 2054 | - **输出:** 相同。输出和输入形状相同。 2055 | 2056 | **例子:** 2057 | 2058 | ```python 2059 | >>> m = nn.Dropout(p=0.2) 2060 | >>> input = autograd.Variable(torch.randn(20, 16)) 2061 | >>> output = m(input) 2062 | ``` 2063 | 2064 | ``` python 2065 | class torch.nn.Dropout2d(p=0.5, inplace=False) 2066 | ``` 2067 | 随机将输入张量中整个通道设置为0。对于每次前向调用,被置0的通道都是随机的。 2068 | 2069 | *通常输入来自Conv2d模块。* 2070 | 2071 | 像在论文[Efficient Object Localization Using Convolutional Networks](https://arxiv.org/abs/1411.4280),如果特征图中相邻像素是强相关的(在前几层卷积层很常见),那么iid dropout不会归一化激活,而只会降低学习率。 2072 | 2073 | 在这种情形,`nn.Dropout2d()`可以提高特征图之间的独立程度,所以应该使用它。 2074 | 2075 | **参数:** 2076 | 2077 | - **p**(*[float](), optional*) - 将元素置0的概率。 2078 | - **in-place**(*[bool,]() optional*) - 若设置为True,会在原地执行操作。 2079 | 2080 | **形状:** 2081 | 2082 | - **输入:** \\((N, C, H, W)\\) 2083 | - **输出:** \\((N, C, H, W)\\)(与输入形状相同) 2084 | 2085 | **例子:** 2086 | 2087 | ``` python 2088 | >>> m = nn.Dropout2d(p=0.2) 2089 | >>> input = autograd.Variable(torch.randn(20, 16, 32, 32)) 2090 | >>> output = m(input) 2091 | ``` 2092 | ``` python 2093 | class torch.nn.Dropout3d(p=0.5, inplace=False) 2094 | ``` 2095 | 2096 | 随机将输入张量中整个通道设置为0。对于每次前向调用,被置0的通道都是随机的。 2097 | 2098 | *通常输入来自Conv3d模块。* 2099 | 2100 | 像在论文[Efficient Object Localization Using Convolutional Networks](https://arxiv.org/abs/1411.4280),如果特征图中相邻像素是强相关的(在前几层卷积层很常见),那么iid dropout不会归一化激活,而只会降低学习率。 2101 | 2102 | 在这种情形,`nn.Dropout3d()`可以提高特征图之间的独立程度,所以应该使用它。 2103 | 2104 | **参数:** 2105 | 2106 | - **p**(*[float](), optional*) - 将元素置0的概率。 2107 | - **in-place**(*[bool,]() optional*) - 若设置为True,会在原地执行操作。 2108 | 2109 | **形状:** 2110 | 2111 | - **输入:** \\(N, C, D, H, W)\\) 2112 | - **输出:** \\((N, C, D, H, W)\\)(与输入形状相同) 2113 | 2114 | **例子:** 2115 | 2116 | ``` python 2117 | >>> m = nn.Dropout3d(p=0.2) 2118 | >>> input = autograd.Variable(torch.randn(20, 16, 4, 32, 32)) 2119 | >>> output = m(input) 2120 | ``` 2121 | 2122 | ## Sparse layers 2123 | ```python 2124 | class torch.nn.Embedding(num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=2, scale_grad_by_freq=False, sparse=False) 2125 | ``` 2126 | 2127 | 一个保存了固定字典和大小的简单查找表。 2128 | 2129 | 这个模块常用来保存词嵌入和用下标检索它们。模块的输入是一个下标的列表,输出是对应的词嵌入。 2130 | 2131 | **参数:** 2132 | 2133 | - **num_embeddings** (*[int]()*) - 嵌入字典的大小 2134 | - **embedding_dim** (*[int]()*) - 每个嵌入向量的大小 2135 | - **padding_idx ** (*[int](), optional*) - 如果提供的话,输出遇到此下标时用零填充 2136 | - **max_norm** (*[float](), optional*) - 如果提供的话,会重新归一化词嵌入,使它们的范数小于提供的值 2137 | - **norm_type** (*[float](), optional*) - 对于max_norm选项计算p范数时的p 2138 | - **scale_grad_by_freq** (*boolean, optional*) - 如果提供的话,会根据字典中单词频率缩放梯度 2139 | 2140 | **变量:** 2141 | 2142 | - **weight (*[Tensor](http://pytorch.org/docs/tensors.html#torch.Tensor)*) ** -形状为(num_embeddings, embedding_dim)的模块中可学习的权值 2143 | 2144 | **形状:** 2145 | 2146 | - **输入:** LongTensor *(N, W)*, N = mini-batch, W = 每个mini-batch中提取的下标数 2147 | - **输出:** *(N, W, embedding_dim)* 2148 | 2149 | **例子:** 2150 | 2151 | ```python 2152 | >>> # an Embedding module containing 10 tensors of size 3 2153 | >>> embedding = nn.Embedding(10, 3) 2154 | >>> # a batch of 2 samples of 4 indices each 2155 | >>> input = Variable(torch.LongTensor([[1,2,4,5],[4,3,2,9]])) 2156 | >>> embedding(input) 2157 | 2158 | Variable containing: 2159 | (0 ,.,.) = 2160 | -1.0822 1.2522 0.2434 2161 | 0.8393 -0.6062 -0.3348 2162 | 0.6597 0.0350 0.0837 2163 | 0.5521 0.9447 0.0498 2164 | 2165 | (1 ,.,.) = 2166 | 0.6597 0.0350 0.0837 2167 | -0.1527 0.0877 0.4260 2168 | 0.8393 -0.6062 -0.3348 2169 | -0.8738 -0.9054 0.4281 2170 | [torch.FloatTensor of size 2x4x3] 2171 | 2172 | >>> # example with padding_idx 2173 | >>> embedding = nn.Embedding(10, 3, padding_idx=0) 2174 | >>> input = Variable(torch.LongTensor([[0,2,0,5]])) 2175 | >>> embedding(input) 2176 | 2177 | Variable containing: 2178 | (0 ,.,.) = 2179 | 0.0000 0.0000 0.0000 2180 | 0.3452 0.4937 -0.9361 2181 | 0.0000 0.0000 0.0000 2182 | 0.0706 -2.1962 -0.6276 2183 | [torch.FloatTensor of size 1x4x3] 2184 | ``` 2185 | 2186 | ## Distance functions 2187 | ``` python 2188 | class torch.nn.PairwiseDistance(p=2, eps=1e-06) 2189 | ``` 2190 | 按批计算向量v1, v2之间的距离: 2191 | 2192 | 2193 | $$\Vert x \Vert _p := \left( \sum\_{i=1}^n \vert x_i \vert ^ p \right) ^ {1/p}$$ 2194 | 2195 | 2196 | **参数:** 2197 | 2198 | - **x** (*Tensor*): 包含两个输入batch的张量 2199 | - **p** (real): 范数次数,默认值:2 2200 | 2201 | **形状:** 2202 | 2203 | - **输入:** \\((N, D)\\),其中D=向量维数 2204 | - **输出:** \\((N, 1)\\) 2205 | 2206 | ```python 2207 | >>> pdist = nn.PairwiseDistance(2) 2208 | >>> input1 = autograd.Variable(torch.randn(100, 128)) 2209 | >>> input2 = autograd.Variable(torch.randn(100, 128)) 2210 | >>> output = pdist(input1, input2) 2211 | ``` 2212 | 2213 | ## Loss functions 2214 | 基本用法: 2215 | ```python 2216 | criterion = LossCriterion() #构造函数有自己的参数 2217 | loss = criterion(x, y) #调用标准时也有参数 2218 | ``` 2219 | 计算出来的结果已经对`mini-batch`取了平均。 2220 | ### class torch.nn.L1Loss(size_average=True)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#L1Loss) 2221 | 创建一个衡量输入`x`(`模型预测输出`)和目标`y`之间差的绝对值的平均值的标准。 2222 | $$ 2223 | loss(x,y)=1/n\sum|x_i-y_i| 2224 | $$ 2225 | 2226 | - `x` 和 `y` 可以是任意形状,每个包含`n`个元素。 2227 | 2228 | - 对`n`个元素对应的差值的绝对值求和,得出来的结果除以`n`。 2229 | 2230 | - 如果在创建`L1Loss`实例的时候在构造函数中传入`size_average=False`,那么求出来的绝对值的和将不会除以`n` 2231 | 2232 | 2233 | ### class torch.nn.MSELoss(size_average=True)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#MSELoss) 2234 | 创建一个衡量输入`x`(`模型预测输出`)和目标`y`之间均方误差标准。 2235 | $$ 2236 | loss(x,y)=1/n\sum(x_i-y_i)^2 2237 | $$ 2238 | 2239 | - `x` 和 `y` 可以是任意形状,每个包含`n`个元素。 2240 | 2241 | - 对`n`个元素对应的差值的绝对值求和,得出来的结果除以`n`。 2242 | 2243 | - 如果在创建`MSELoss`实例的时候在构造函数中传入`size_average=False`,那么求出来的平方和将不会除以`n` 2244 | 2245 | ### class torch.nn.CrossEntropyLoss(weight=None, size_average=True)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#CrossEntropyLoss) 2246 | 此标准将`LogSoftMax`和`NLLLoss`集成到一个类中。 2247 | 2248 | 当训练一个多类分类器的时候,这个方法是十分有用的。 2249 | 2250 | - weight(tensor): `1-D` tensor,`n`个元素,分别代表`n`类的权重,如果你的训练样本很不均衡的话,是非常有用的。默认值为None。 2251 | 2252 | 调用时参数: 2253 | 2254 | - input : 包含每个类的得分,`2-D` tensor,`shape`为 `batch*n` 2255 | 2256 | - target: 大小为 `n` 的 `1—D` `tensor`,包含类别的索引(`0到 n-1`)。 2257 | 2258 | 2259 | Loss可以表述为以下形式: 2260 | $$ 2261 | \begin{aligned} 2262 | loss(x, class) &= -\text{log}\frac{exp(x[class])}{\sum_j exp(x[j]))}\\ 2263 | &= -x[class] + log(\sum_j exp(x[j])) 2264 | \end{aligned} 2265 | $$ 2266 | 当`weight`参数被指定的时候,`loss`的计算公式变为: 2267 | $$ 2268 | loss(x, class) = weights[class] * (-x[class] + log(\sum_j exp(x[j]))) 2269 | $$ 2270 | 计算出的`loss`对`mini-batch`的大小取了平均。 2271 | 2272 | 形状(`shape`): 2273 | 2274 | - Input: (N,C) `C` 是类别的数量 2275 | 2276 | - Target: (N) `N`是`mini-batch`的大小,0 <= targets[i] <= C-1 2277 | 2278 | ### class torch.nn.NLLLoss(weight=None, size_average=True)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#NLLLoss) 2279 | 负的`log likelihood loss`损失。用于训练一个`n`类分类器。 2280 | 2281 | 如果提供的话,`weight`参数应该是一个`1-D`tensor,里面的值对应类别的权重。当你的训练集样本不均衡的话,使用这个参数是非常有用的。 2282 | 2283 | 输入是一个包含类别`log-probabilities`的`2-D` tensor,形状是`(mini-batch, n)` 2284 | 2285 | 可以通过在最后一层加`LogSoftmax`来获得类别的`log-probabilities`。 2286 | 2287 | 如果您不想增加一个额外层的话,您可以使用`CrossEntropyLoss`。 2288 | 2289 | 此`loss`期望的`target`是类别的索引 (0 to N-1, where N = number of classes) 2290 | 2291 | 此`loss`可以被表示如下: 2292 | $$ 2293 | loss(x, class) = -x[class] 2294 | $$ 2295 | 如果`weights`参数被指定的话,`loss`可以表示如下: 2296 | $$ 2297 | loss(x, class) = -weights[class] * x[class] 2298 | $$ 2299 | 参数说明: 2300 | 2301 | - weight (Tensor, optional) – 手动指定每个类别的权重。如果给定的话,必须是长度为`nclasses` 2302 | 2303 | - size_average (bool, optional) – 默认情况下,会计算`mini-batch``loss`的平均值。然而,如果`size_average=False`那么将会把`mini-batch`中所有样本的`loss`累加起来。 2304 | 2305 | 形状: 2306 | 2307 | - Input: (N,C) , `C`是类别的个数 2308 | 2309 | - Target: (N) , `target`中每个值的大小满足 `0 <= targets[i] <= C-1` 2310 | 2311 | 例子: 2312 | ```python 2313 | m = nn.LogSoftmax() 2314 | loss = nn.NLLLoss() 2315 | # input is of size nBatch x nClasses = 3 x 5 2316 | input = autograd.Variable(torch.randn(3, 5), requires_grad=True) 2317 | # each element in target has to have 0 <= value < nclasses 2318 | target = autograd.Variable(torch.LongTensor([1, 0, 4])) 2319 | output = loss(m(input), target) 2320 | output.backward() 2321 | ``` 2322 | 2323 | ### class torch.nn.NLLLoss2d(weight=None, size_average=True)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#NLLLoss2d) 2324 | 2325 | 对于图片的 `negative log likehood loss`。计算每个像素的 `NLL loss`。 2326 | 2327 | 参数说明: 2328 | 2329 | - weight (Tensor, optional) – 用来作为每类的权重,如果提供的话,必须为`1-D`tensor,大小为`C`:类别的个数。 2330 | 2331 | - size_average – 默认情况下,会计算 `mini-batch` loss均值。如果设置为 `False` 的话,将会累加`mini-batch`中所有样本的`loss`值。默认值:`True`。 2332 | 2333 | 形状: 2334 | 2335 | - Input: (N,C,H,W) `C` 类的数量 2336 | 2337 | - Target: (N,H,W) where each value is 0 <= targets[i] <= C-1 2338 | 2339 | 例子: 2340 | ```python 2341 | m = nn.Conv2d(16, 32, (3, 3)).float() 2342 | loss = nn.NLLLoss2d() 2343 | # input is of size nBatch x nClasses x height x width 2344 | input = autograd.Variable(torch.randn(3, 16, 10, 10)) 2345 | # each element in target has to have 0 <= value < nclasses 2346 | target = autograd.Variable(torch.LongTensor(3, 8, 8).random_(0, 4)) 2347 | output = loss(m(input), target) 2348 | output.backward() 2349 | ``` 2350 | ### class torch.nn.KLDivLoss(weight=None, size_average=True)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#KLDivLoss) 2351 | 2352 | 计算 KL 散度损失。 2353 | 2354 | KL散度常用来描述两个分布的距离,并在输出分布的空间上执行直接回归是有用的。 2355 | 2356 | 与`NLLLoss`一样,给定的输入应该是`log-probabilities`。然而。和`NLLLoss`不同的是,`input`不限于`2-D` tensor,因为此标准是基于`element`的。 2357 | 2358 | `target` 应该和 `input`的形状相同。 2359 | 2360 | 此loss可以表示为: 2361 | $$ 2362 | loss(x,target)=\frac{1}{n}\sum_i(target_i*(log(target_i)-x_i)) 2363 | $$ 2364 | 默认情况下,loss会基于`element`求平均。如果 `size_average=False` `loss` 会被累加起来。 2365 | 2366 | ### class torch.nn.BCELoss(weight=None, size_average=True)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#BCELoss) 2367 | 2368 | 计算 `target` 与 `output` 之间的二进制交叉熵。 2369 | $$ 2370 | loss(o,t)=-\frac{1}{n}\sum_i(t[i]* log(o[i])+(1-t[i])* log(1-o[i])) 2371 | $$ 2372 | 如果`weight`被指定 : 2373 | $$ 2374 | loss(o,t)=-\frac{1}{n}\sum_iweights[i]* (t[i]* log(o[i])+(1-t[i])* log(1-o[i])) 2375 | $$ 2376 | 2377 | 这个用于计算 `auto-encoder` 的 `reconstruction error`。注意 0<=target[i]<=1。 2378 | 2379 | 默认情况下,loss会基于`element`平均,如果`size_average=False`的话,`loss`会被累加。 2380 | 2381 | ### class torch.nn.MarginRankingLoss(margin=0, size_average=True)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#MarginRankingLoss) 2382 | 2383 | 创建一个标准,给定输入 $x1$,$x2$两个1-D mini-batch Tensor's,和一个$y$(1-D mini-batch tensor) ,$y$里面的值只能是-1或1。 2384 | 2385 | 如果 `y=1`,代表第一个输入的值应该大于第二个输入的值,如果`y=-1`的话,则相反。 2386 | 2387 | `mini-batch`中每个样本的loss的计算公式如下: 2388 | 2389 | $$loss(x, y) = max(0, -y * (x1 - x2) + margin)$$ 2390 | 2391 | 如果`size_average=True`,那么求出的`loss`将会对`mini-batch`求平均,反之,求出的`loss`会累加。默认情况下,`size_average=True`。 2392 | 2393 | ### class torch.nn.HingeEmbeddingLoss(size_average=True)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#HingeEmbeddingLoss) 2394 | 2395 | 给定一个输入 $x$(2-D mini-batch tensor)和对应的 标签 $y$ (1-D tensor,1,-1),此函数用来计算之间的损失值。这个`loss`通常用来测量两个输入是否相似,即:使用L1 成对距离。典型是用在学习非线性 `embedding`或者半监督学习中: 2396 | 2397 | $$ 2398 | loss(x,y)=\frac{1}{n}\sum_i 2399 | \begin{cases} 2400 | x_i, &\text if~y_i==1 \\ 2401 | max(0, margin-x_i), &if ~y_i==-1 2402 | \end{cases} 2403 | $$ 2404 | $x$和$y$可以是任意形状,且都有`n`的元素,`loss`的求和操作作用在所有的元素上,然后除以`n`。如果您不想除以`n`的话,可以通过设置`size_average=False`。 2405 | 2406 | `margin`的默认值为1,可以通过构造函数来设置。 2407 | 2408 | ### class torch.nn.MultiLabelMarginLoss(size_average=True)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#MultiLabelMarginLoss) 2409 | 计算多标签分类的 `hinge loss`(`margin-based loss`) ,计算`loss`时需要两个输入: input x(`2-D mini-batch Tensor`),和 output y(`2-D tensor`表示mini-batch中样本类别的索引)。 2410 | 2411 | $$ 2412 | loss(x, y) = \frac{1}{x.size(0)}\sum_{i=0,j=0}^{I,J}(max(0, 1 - (x[y[j]] - x[i]))) 2413 | $$ 2414 | 其中 `I=x.size(0),J=y.size(0)`。对于所有的 `i`和 `j`,满足 $y[j]\neq0, i \neq y[j]$ 2415 | 2416 | `x` 和 `y` 必须具有同样的 `size`。 2417 | 2418 | 这个标准仅考虑了第一个非零 `y[j] targets` 2419 | 此标准允许了,对于每个样本来说,可以有多个类别。 2420 | 2421 | ### class torch.nn.SmoothL1Loss(size_average=True)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#SmoothL1Loss) 2422 | 平滑版`L1 loss`。 2423 | 2424 | loss的公式如下: 2425 | $$ 2426 | loss(x, y) = \frac{1}{n}\sum_i 2427 | \begin{cases} 2428 | 0.5*(x_i-y_i)^2, & if~|x_i - y_i| < 1\\ 2429 | |x_i - y_i| - 0.5, & otherwise 2430 | \end{cases} 2431 | $$ 2432 | 此loss对于异常点的敏感性不如`MSELoss`,而且,在某些情况下防止了梯度爆炸,(参照 `Fast R-CNN`)。这个`loss`有时也被称为 `Huber loss`。 2433 | 2434 | x 和 y 可以是任何包含`n`个元素的tensor。默认情况下,求出来的`loss`会除以`n`,可以通过设置`size_average=True`使loss累加。 2435 | 2436 | ### class torch.nn.SoftMarginLoss(size_average=True)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#SoftMarginLoss) 2437 | 2438 | 创建一个标准,用来优化2分类的`logistic loss`。输入为 `x`(一个 2-D mini-batch Tensor)和 目标`y`(一个包含1或-1的Tensor)。 2439 | $$ 2440 | loss(x, y) = \frac{1}{x.nelement()}\sum_i (log(1 + exp(-y[i]* x[i]))) 2441 | $$ 2442 | 如果求出的`loss`不想被平均可以通过设置`size_average=False`。 2443 | 2444 | ### class torch.nn.MultiLabelSoftMarginLoss(weight=None, size_average=True)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#MultiLabelSoftMarginLoss) 2445 | 2446 | 创建一个标准,基于输入x和目标y的 `max-entropy`,优化多标签 `one-versus-all` 的损失。`x`:2-D mini-batch Tensor;`y`:binary 2D Tensor。对每个mini-batch中的样本,对应的loss为: 2447 | $$ 2448 | loss(x, y) = - \frac{1}{x.nElement()}\sum_{i=0}^I y[i]\text{log}\frac{exp(x[i])}{(1 + exp(x[i])} 2449 | + (1-y[i])\text{log}\frac{1}{1+exp(x[i])} 2450 | $$ 2451 | 其中 `I=x.nElement()-1`, $y[i] \in \{0,1\}$,`y` 和 `x`必须要有同样`size`。 2452 | 2453 | ### class torch.nn.CosineEmbeddingLoss(margin=0, size_average=True)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/loss.html#CosineEmbeddingLoss) 2454 | 2455 | 给定 输入 `Tensors`,`x1`, `x2` 和一个标签Tensor `y`(元素的值为1或-1)。此标准使用`cosine`距离测量两个输入是否相似,一般用来用来学习非线性`embedding`或者半监督学习。 2456 | 2457 | `margin`应该是-1到1之间的值,建议使用0到0.5。如果没有传入`margin`实参,默认值为0。 2458 | 2459 | 每个样本的loss是: 2460 | $$ 2461 | loss(x, y) = 2462 | \begin{cases} 2463 | 1 - cos(x1, x2), &if~y == 1 \\ 2464 | max(0, cos(x1, x2) - margin), &if~y == -1 2465 | \end{cases} 2466 | $$ 2467 | 如果`size_average=True` 求出的loss会对batch求均值,如果`size_average=False`的话,则会累加`loss`。默认情况`size_average=True`。 2468 | 2469 | ### 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) 2470 | 用来计算multi-class classification的hinge loss(magin-based loss)。输入是 `x`(2D mini-batch Tensor), `y`(1D Tensor)包含类别的索引, `0 <= y <= x.size(1))`。 2471 | 2472 | 对每个mini-batch样本: 2473 | $$ 2474 | loss(x, y) = \frac{1}{x.size(0)}\sum_{i=0}^I(max(0, margin - x[y] + x[i])^p) 2475 | $$ 2476 | 其中 `I=x.size(0)` $i\neq y$。 2477 | 可选择的,如果您不想所有的类拥有同样的权重的话,您可以通过在构造函数中传入`weights`参数来解决这个问题,`weights`是一个1D权重Tensor。 2478 | 2479 | 传入weights后,loss函数变为: 2480 | $$ 2481 | loss(x, y) = \frac{1}{x.size(0)}\sum_imax(0, w[y] * (margin - x[y] - x[i]))^p 2482 | $$ 2483 | 默认情况下,求出的loss会对mini-batch取平均,可以通过设置`size_average=False`来取消取平均操作。 2484 | 2485 | ## Vision layers 2486 | 2487 | ### class torch.nn.PixelShuffle(upscale_factor)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/pixelshuffle.html#PixelShuffle) 2488 | 2489 | 将shape为$[N, C*r^2, H, W]$的`Tensor`重新排列为shape为$[N, C, H*r, W*r]$的Tensor。 2490 | 当使用`stride=1/r` 的sub-pixel卷积的时候,这个方法是非常有用的。 2491 | 2492 | 请看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) 获取详细信息。 2493 | 2494 | 参数说明: 2495 | 2496 | - upscale_factor (int) – 增加空间分辨率的因子 2497 | 2498 | Shape: 2499 | 2500 | - Input: $[N,C*upscale\_factor^2,H,W$] 2501 | 2502 | - Output: $[N,C,H*upscale\_factor,W*upscale\_factor]$ 2503 | 2504 | 例子: 2505 | ```python 2506 | >>> ps = nn.PixelShuffle(3) 2507 | >>> input = autograd.Variable(torch.Tensor(1, 9, 4, 4)) 2508 | >>> output = ps(input) 2509 | >>> print(output.size()) 2510 | torch.Size([1, 1, 12, 12]) 2511 | ``` 2512 | 2513 | 2514 | ### class torch.nn.UpsamplingNearest2d(size=None, scale_factor=None)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/upsampling.html#UpsamplingNearest2d) 2515 | 2516 | 对于多channel 输入 进行 `2-D` 最近邻上采样。 2517 | 2518 | 可以通过`size`或者`scale_factor`来指定上采样后的图片大小。 2519 | 2520 | 当给定`size`时,`size`的值将会是输出图片的大小。 2521 | 2522 | 参数: 2523 | 2524 | - size (tuple, optional) – 一个包含两个整数的元组 (H_out, W_out)指定了输出的长宽 2525 | - scale_factor (int, optional) – 长和宽的一个乘子 2526 | 2527 | 形状: 2528 | 2529 | - Input: (N,C,H_in,W_in) 2530 | - Output: (N,C,H_out,W_out) Hout=floor(H_in∗scale_factor) Wout=floor(W_in∗scale_factor) 2531 | 2532 | 例子: 2533 | ```python 2534 | >>> inp 2535 | Variable containing: 2536 | (0 ,0 ,.,.) = 2537 | 1 2 2538 | 3 4 2539 | [torch.FloatTensor of size 1x1x2x2] 2540 | 2541 | >>> m = nn.UpsamplingNearest2d(scale_factor=2) 2542 | >>> m(inp) 2543 | Variable containing: 2544 | (0 ,0 ,.,.) = 2545 | 1 1 2 2 2546 | 1 1 2 2 2547 | 3 3 4 4 2548 | 3 3 4 4 2549 | [torch.FloatTensor of size 1x1x4x4] 2550 | ``` 2551 | 2552 | ### class torch.nn.UpsamplingBilinear2d(size=None, scale_factor=None)[[source]](http://pytorch.org/docs/_modules/torch/nn/modules/upsampling.html#UpsamplingBilinear2d) 2553 | 2554 | 对于多channel 输入 进行 `2-D` `bilinear` 上采样。 2555 | 2556 | 可以通过`size`或者`scale_factor`来指定上采样后的图片大小。 2557 | 2558 | 当给定`size`时,`size`的值将会是输出图片的大小。 2559 | 2560 | 参数: 2561 | 2562 | - size (tuple, optional) – 一个包含两个整数的元组 (H_out, W_out)指定了输出的长宽 2563 | - scale_factor (int, optional) – 长和宽的一个乘子 2564 | 2565 | 形状: 2566 | 2567 | - Input: (N,C,H_in,W_in) 2568 | - Output: (N,C,H_out,W_out) Hout=floor(H_in∗scale_factor) Wout=floor(W_in∗scale_factor) 2569 | 2570 | 例子: 2571 | ```python 2572 | >>> inp 2573 | Variable containing: 2574 | (0 ,0 ,.,.) = 2575 | 1 2 2576 | 3 4 2577 | [torch.FloatTensor of size 1x1x2x2] 2578 | 2579 | >>> m = nn.UpsamplingBilinear2d(scale_factor=2) 2580 | >>> m(inp) 2581 | Variable containing: 2582 | (0 ,0 ,.,.) = 2583 | 1.0000 1.3333 1.6667 2.0000 2584 | 1.6667 2.0000 2.3333 2.6667 2585 | 2.3333 2.6667 3.0000 3.3333 2586 | 3.0000 3.3333 3.6667 4.0000 2587 | [torch.FloatTensor of size 1x1x4x4] 2588 | ``` 2589 | ## Multi-GPU layers 2590 | ### 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) 2591 | 2592 | 在模块级别上实现数据并行。 2593 | 2594 | 此容器通过将`mini-batch`划分到不同的设备上来实现给定`module`的并行。在`forward`过程中,`module`会在每个设备上都复制一遍,每个副本都会处理部分输入。在`backward`过程中,副本上的梯度会累加到原始`module`上。 2595 | 2596 | batch的大小应该大于所使用的GPU的数量。还应当是GPU个数的整数倍,这样划分出来的每一块都会有相同的样本数量。 2597 | 2598 | 请看: [Use nn.DataParallel instead of multiprocessing]() 2599 | 2600 | 除了`Tensor`,任何位置参数和关键字参数都可以传到DataParallel中。所有的变量会通过指定的`dim`来划分(默认值为0)。原始类型将会被广播,但是所有的其它类型都会被浅复制。所以如果在模型的`forward`过程中写入的话,将会被损坏。 2601 | 2602 | 参数说明: 2603 | 2604 | - module – 要被并行的module 2605 | - device_ids – CUDA设备,默认为所有设备。 2606 | - output_device – 输出设备(默认为device_ids[0]) 2607 | 2608 | 例子: 2609 | ```python 2610 | net = torch.nn.DataParallel(model, device_ids=[0, 1, 2]) 2611 | output = net(input_var) 2612 | ``` 2613 | 2614 | ## Utilities 2615 | 工具函数 2616 | ### 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) 2617 | Clips gradient norm of an iterable of parameters. 2618 | 2619 | 正则項的值由所有的梯度计算出来,就像他们连成一个向量一样。梯度被`in-place operation`修改。 2620 | 2621 | 参数说明: 2622 | - parameters (Iterable[Variable]) – 可迭代的`Variables`,它们的梯度即将被标准化。 2623 | - max_norm (float or int) – `clip`后,`gradients` p-norm 值 2624 | - norm_type (float or int) – 标准化的类型,p-norm. 可以是`inf` 代表 infinity norm. 2625 | 2626 | [关于norm](https://rorasa.wordpress.com/2012/05/13/l0-norm-l1-norm-l2-norm-l-infinity-norm/) 2627 | 2628 | 返回值: 2629 | 2630 | 所有参数的p-norm值。 2631 | 2632 | ### torch.nn.utils.rnn.PackedSequence(\_cls, data, batch_sizes)[[source]](http://pytorch.org/docs/_modules/torch/nn/utils/rnn.html#PackedSequence) 2633 | Holds the data and list of batch_sizes of a packed sequence. 2634 | 2635 | All RNN modules accept packed sequences as inputs. 2636 | 所有的`RNN`模块都接收这种被包裹后的序列作为它们的输入。 2637 | 2638 | `NOTE:` 2639 | 这个类的实例不能手动创建。它们只能被 `pack_padded_sequence()` 实例化。 2640 | 2641 | 参数说明: 2642 | 2643 | - data (Variable) – 包含打包后序列的`Variable`。 2644 | 2645 | - batch_sizes (list[int]) – 包含 `mini-batch` 中每个序列长度的列表。 2646 | 2647 | ### torch.nn.utils.rnn.pack_padded_sequence(input, lengths, batch_first=False)[[source]](http://pytorch.org/docs/_modules/torch/nn/utils/rnn.html#PackedSequence) 2648 | 2649 | 这里的`pack`,理解成压紧比较好。 2650 | 将一个 填充过的变长序列 压紧。(填充时候,会有冗余,所以压紧一下) 2651 | 2652 | 输入的形状可以是(T×B×* )。`T`是最长序列长度,`B`是`batch size`,`*`代表任意维度(可以是0)。如果`batch_first=True`的话,那么相应的 `input size` 就是 `(B×T×*)`。 2653 | 2654 | `Variable`中保存的序列,应该按序列长度的长短排序,长的在前,短的在后。即`input[:,0]`代表的是最长的序列,`input[:, B-1]`保存的是最短的序列。 2655 | 2656 | `NOTE:` 2657 | 只要是维度大于等于2的`input`都可以作为这个函数的参数。你可以用它来打包`labels`,然后用`RNN`的输出和打包后的`labels`来计算`loss`。通过`PackedSequence`对象的`.data`属性可以获取 `Variable`。 2658 | 2659 | 参数说明: 2660 | 2661 | - input (Variable) – 变长序列 被填充后的 batch 2662 | 2663 | - lengths (list[int]) – `Variable` 中 每个序列的长度。 2664 | 2665 | - batch_first (bool, optional) – 如果是`True`,input的形状应该是`B*T*size`。 2666 | 2667 | 返回值: 2668 | 2669 | 一个`PackedSequence` 对象。 2670 | 2671 | ### 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) 2672 | 2673 | 填充`packed_sequence`。 2674 | 2675 | 上面提到的函数的功能是将一个填充后的变长序列压紧。 这个操作和pack_padded_sequence()是相反的。把压紧的序列再填充回来。 2676 | 2677 | 返回的Varaible的值的`size`是 `T×B×*`, `T` 是最长序列的长度,`B` 是 batch_size,如果 `batch_first=True`,那么返回值是`B×T×*`。 2678 | 2679 | Batch中的元素将会以它们长度的逆序排列。 2680 | 2681 | 2682 | 参数说明: 2683 | 2684 | - sequence (PackedSequence) – 将要被填充的 batch 2685 | 2686 | - batch_first (bool, optional) – 如果为True,返回的数据的格式为 `B×T×*`。 2687 | 2688 | 返回值: 2689 | 一个tuple,包含被填充后的序列,和batch中序列的长度列表。 2690 | 2691 | 例子: 2692 | ```python 2693 | import torch 2694 | import torch.nn as nn 2695 | from torch.autograd import Variable 2696 | from torch.nn import utils as nn_utils 2697 | batch_size = 2 2698 | max_length = 3 2699 | hidden_size = 2 2700 | n_layers =1 2701 | 2702 | tensor_in = torch.FloatTensor([[1, 2, 3], [1, 0, 0]]).resize_(2,3,1) 2703 | tensor_in = Variable( tensor_in ) #[batch, seq, feature], [2, 3, 1] 2704 | seq_lengths = [3,1] # list of integers holding information about the batch size at each sequence step 2705 | 2706 | # pack it 2707 | pack = nn_utils.rnn.pack_padded_sequence(tensor_in, seq_lengths, batch_first=True) 2708 | 2709 | # initialize 2710 | rnn = nn.RNN(1, hidden_size, n_layers, batch_first=True) 2711 | h0 = Variable(torch.randn(n_layers, batch_size, hidden_size)) 2712 | 2713 | #forward 2714 | out, _ = rnn(pack, h0) 2715 | 2716 | # unpack 2717 | unpacked = nn_utils.rnn.pad_packed_sequence(out) 2718 | print(unpacked) 2719 | ``` 2720 | 2721 | [关于packed_sequence](https://discuss.pytorch.org/t/how-can-i-compute-seq2seq-loss-using-mask/861) 2722 | --------------------------------------------------------------------------------