gpt4 book ai didi

model - 为什么 model.forward(input) 和 model(input) 之间有不同的输出

转载 作者:行者123 更新时间:2023-12-05 00:10:58 41 4
gpt4 key购买 nike

我正在使用pytorch构建一个像VGG16这样的简单模型,并且我已经重载了函数forward在我的模型中。

我发现每个人都倾向于使用 model(input)得到输出而不是 model.forward(input) ,我对它们之间的区别很感兴趣。我尝试输入相同的数据,但结果不同。我很困惑。

我在输入数据之前已经输出了layer_weight,权重没有改变,我知道我们什么时候使用model(input)它使用 __call__函数,这个函数会调用model.forward .

   vgg = VGG()
vgg.double()
for layer in vgg.modules():
if isinstance(layer,torch.nn.Linear):
print(layer.weight)
print(" use model.forward(input) ")
result = vgg.forward(array)

for layer in vgg.modules():
if isinstance(layer,torch.nn.Linear):
print(layer.weight)
print(" use model(input) ")
result_2 = vgg(array)
print(result)
print(result_2)

输出:
    Variable containing:1.00000e-02 *
-0.2931 0.6716 -0.3497 -2.0217 -0.0764 1.2162 1.4983 -1.2881
[torch.DoubleTensor of size 1x8]

Variable containing:
1.00000e-02 *
0.5302 0.4494 -0.6866 -2.1657 -0.9504 1.0211 0.8308 -1.1665
[torch.DoubleTensor of size 1x8]

最佳答案

model.forward正如你提到的,只是调用前向操作,但是 __call__做了一点额外的工作。

如果您深入了解 codenn.Module您将看到的类(class)__call__最终调用 forward 但在内部处理 forward 或 back 钩子(Hook)并管理 pytorch 允许的一些状态。当调用像 MLP 这样的简单模型时,可能并不需要它,但更复杂的模型(如光谱归一化层)有钩子(Hook),因此您应该使用 model(.)尽可能多地签名,除非您明确地只想调用 model.forward
另见 Calling forward function without .forward()

然而,在这种情况下,差异可能是由于某些 dropout 层,您应该调用 vgg.eval()确保在比较输出之前关闭网络中的所有随机性。

关于model - 为什么 model.forward(input) 和 model(input) 之间有不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55338756/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com