在pytorch中使用Optimizer.step或model.step是否有所不同?

时间:2018-11-14 14:39:06

标签: python pytorch

在pytorch中,要更新模型,我应该使用optimizer.step()还是model.step()吗?

以下是示例片段:

import torch
import torch nn
class SomeNeuralNet(nn.Module):
    def __init__(self,hs,es,dropout):
          SomeNeuralNet(ClaimRecognizer, self).__init__()
          # Some initialization here
    def forward(x):
          # forward propagation here

model = SomeNeuralNet(es,hs,dp)
optimizer = optim.Adam(model.parameters())
loss_function = nn.NLLLoss()
for epoch in N:
   for x in data:
      logp = model(x)
      loss = loss_function(logp,gold_outs)
      loss.backward()
       # Which one I should call ? Optimizer.step() or model.step() or both ?
       optimizer.step()
       model.step()

1 个答案:

答案 0 :(得分:2)

要进行梯度下降步骤,通常只使用optimizer.step()
这也是从 documentation (same link at bottom) 中摘录的一个示例,其外观大致如下:

for input, target in dataset:
    optimizer.zero_grad()
    output = model(input)
    loss = loss_fn(output, target)
    loss.backward()
    optimizer.step()

我不知道你在哪里model.step()?你有尝试过吗?

如果您的模型确实具有某种 step()功能,则可能会有所不同。

但是除非您定义其他内容,否则您的modelnn.Module获取其功能,而它没有step的功能!

请参见Pytorch Documentation中的示例:

import torch.nn as nn
import torch.nn.functional as F

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)
        self.conv2 = nn.Conv2d(20, 20, 5)

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

model = Model()
model.step()

尝试致电step()会导致AttributeError

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-41-b032813f7eda> in <module>
     13 
     14 model = Model()
---> 15 model.step()

~/miniconda3/envs/py37/lib/python3.7/site-packages/torch/nn/modules/module.py in __getattr__(self, name)
    530                 return modules[name]
    531         raise AttributeError("'{}' object has no attribute '{}'".format(
--> 532             type(self).__name__, name))
    533 
    534     def __setattr__(self, name, value):

AttributeError: 'Model' object has no attribute 'step'

总结起来,通常您的model应该具有step()函数,如果您想执行< em>优化步骤。

另请参阅此处: https://pytorch.org/docs/stable/optim.html#taking-an-optimization-step