Pytorch training loss function throws: "TypeError: 'Tensor' object is not callable"
I use Python 3.x, and pytorch 1.5.0 with a GPU. I am trying to write a simple multinomial logistic regression using mnist data.
My issue is the loss() function throws a TypeError: 'Tensor' object is not callable while looping through the training batches. The thing that baffles me is that the error does not show up in the first iteration of the loop, but for the second batch, I get the full error below:
Traceback (most recent call last):
  File &quot;/snap/pycharm-community/207/plugins/python-ce/helpers/pydev/pydevd.py&quot;, line 1448, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File &quot;/snap/pycharm-community/207/plugins/python-ce/helpers/pydev/_pydev_imps/_pydev_execfile.py&quot;, line 18, in execfile
    exec(compile(contents+&quot;\n&quot;, file, 'exec'), glob, loc)
  File &quot;/home/pytorch_tutorial/Pytorch_feed_fwd_310720.py&quot;, line 78, in &lt;module&gt;
    loss = loss(preds,ys)
TypeError: 'Tensor' object is not callable

The loss() function here is simply loss = nn.CrossEntropyLoss(). The full code is below. Any pointers would be very welcome.
    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


it is because you are setting loss locally in the loop.
change loss = loss(preds, ys) to _loss = loss(preds, ys)
