分享
三行代码  ›  专栏  ›  技术社区  ›  Zhubarb

Pythorch训练丢失函数抛出:“TypeError:'Tensor'对象不可调用”

  •  0
  • Zhubarb  · 技术社区  · 1 周前

    TypeError: 'Tensor' object is not callable 该错误不会出现在循环的第一次迭代中,但对于第二批,我得到以下完整错误:

    Traceback (most recent call last):
      File "/snap/pycharm-community/207/plugins/python-ce/helpers/pydev/pydevd.py", line 1448, in _exec
        pydev_imports.execfile(file, globals, locals)  # execute the script
      File "/snap/pycharm-community/207/plugins/python-ce/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
        exec(compile(contents+"\n", file, 'exec'), glob, loc)
      File "/home/pytorch_tutorial/Pytorch_feed_fwd_310720.py", line 78, in <module>
        loss = loss(preds,ys)
    TypeError: 'Tensor' object is not callable
    

    loss = nn.CrossEntropyLoss() . 完整代码如下。任何建议都是非常欢迎的。

        for epoch in range(5):
    
            running_loss = 0.0
            for i, data in enumerate(trainloader, 0):
                xs, ys = data
                opt.zero_grad()
                preds = net(xs)
                loss = loss(preds,ys)
                loss.backward()
                opt.step()
    
                # print statistics
                running_loss += loss.item()
                if i % 1000 == 999:  # print every 1000 mini-batches
                    print('[%d, %5d] loss: %.3f' %
                          (epoch + 1, i + 1, running_loss / 2000))
                    running_loss = 0.0
    
            print('epoch {}, loss {}'.format(epoch, loss.item()))
    
        a=1
    
    1 回复  |  直到 1 周前
        1
  •  1
  •   BenedictWilkinsAI    1 周前

    这是因为你正在设置 loss 本地循环。

    改变 loss = loss(preds, ys) _loss = loss(preds, ys)