一般情况下,nn.Module
可以由子类继承,如下所示。
def init_weights(m):
if type(m) == nn.Linear:
torch.nn.init.xavier_uniform(m.weight) #
class LinearRegression(nn.Module):
def __init__(self):
super(LinearRegression, self).__init__()
self.fc1 = nn.Linear(20, 1)
self.apply(init_weights)
def forward(self, x):
x = self.fc1(x)
return x
我的第一个问题是,为什么我甚至可以简单地运行下面的代码
__init__
training_signals
没有任何定位参数它看起来像 training_signals
传递给 forward()
方法。它是如何工作的?model = LinearRegression()
training_signals = torch.rand(1000,20)
model(training_signals)
第二个问题是
self.apply(init_weights)
内部工作?是否在调用 forward
之前执行方法?
最佳答案
Q1: Why I can simply run the code below even my
__init__
doesn't have any positional arguments fortraining_signals
and it looks like thattraining_signals
is passed toforward()
method. How does it work?
一、
__init__
运行此行时调用:model = LinearRegression()
如您所见,您不传递任何参数,也不应该传递。您的签名
__init__
与基类之一相同(运行时调用 super(LinearRegression, self).__init__()
)。如您所见here , nn.Module
的初始化签名只是 def __init__(self)
(就像你的一样)。二、
model
现在是一个对象。当您运行以下行时:model(training_signals)
您实际上是在调用
__call__
方法和传递training_signals
作为位置参数。如您所见here ,除此之外,__call__
方法调用 forward
方法:result = self.forward(*input, **kwargs)
传递
__call__
的所有参数(位置和命名)到forward
.Q2: How does
self.apply(init_weights)
internally work? Is it executed before calling forward method?
PyTorch 是开源的,所以你可以简单地去源代码并检查它。如您所见here ,实现非常简单:
def apply(self, fn):
for module in self.children():
module.apply(fn)
fn(self)
return self
引用该函数的文档:它“将
fn
递归地应用于每个子模块(由 .children()
返回)以及 self
”。基于实现,还可以理解需求:fn
必须是可调用的; fn
仅接收 Module
作为输入目的; 关于python - Pytorch:了解 nn.Module 类如何在内部工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58795601/