PyTorch中“模块”的定义到底是什么?

Mon*_*eck 15 python class pytorch

请原谅新问题,但这Module和说的一样model吗?

当文档说:

每当您想要一个比现有模块的简单序列更复杂的模型时,都需要定义模型(作为自定义Module子类)。

或者...当他们提到时Module,他们指的是更正式和计算机科学的东西,例如协议/接口类型的东西吗?

iac*_*ppo 10

这是一个简单的容器。

来自的文档 nn.Module

Base class for all neural network modules.
Your models should also subclass this class.
Modules can also contain other Modules, allowing to nest them in a tree structure. 
You can assign the submodules as regular attributes.
Submodules assigned in this way will be registered, 
and will have their parameters converted too when you call `.cuda()`, etc.
Run Code Online (Sandbox Code Playgroud)

教程

All network components should inherit from nn.Module and override the forward() method. 
That is about it, as far as the boilerplate is concerned. 
Inheriting from nn.Module provides functionality to your component. 
For example, it makes it keep track of its trainable parameters, 
you can swap it between CPU and GPU with the .to(device) method, 
where device can be a CPU device torch.device("cpu") or CUDA device torch.device("cuda:0").
Run Code Online (Sandbox Code Playgroud)

模块是一个容器,层,模型子部分(例如BasicBlockin resnettorchvision)和模型应从中继承。为什么要这样?因为从继承nn.Module允许你调用类似的方法to("cuda:0").eval().parameters()或轻松注册挂钩。

  • 为什么不只是将“模块”称为模型,而将图层称为“图层”?我想这可能只是语义和头发的分裂,但仍然...

这是API设计的选择,我发现只有一个Module类而不是两个单独的类,Model并且Layers更加整洁并具有更大的自由度(将模型的一部分发送到GPU以便仅获取某些层的参数会更容易...) 。


Jus*_*yul 5

我没有成为pytorch专家,我的理解是pytorch上下文中的模块只是一个容器,该容器将接收张量作为输入并计算张量作为输出。

因此,总而言之,您的模型很可能由多个模块组成,例如,您可能有3个模块,每个模块代表一个神经网络层。因此,它们在某种意义上是相关的,您需要模块来实现您的模型,但是它们不是一回事。

希望能有所帮助