'Tensor' object is not callable.how can i handle this,floks

username: ywr461903285
cooked: <p>TypeError: ‘Tensor’ object is not callable</p>
<p>how can i handle this,floks</p>

username: ptrblck
cooked: <p>Could you post a code snippet throwing this error?</p>
<p>I would generally recommend to use the factory method <code>torch.tensor</code> instead of <code>torch.Tensor</code>, since the latter will return uninitialized values if you provide a tensor shape.</p>

username: ywr461903285
cooked: <p>the code is following:<br>
if(epoch+1 )%20 == 0:<br>
print(‘Epoch[{}/{}], loss: {:.6f}’<br>
.format(epoch+1, num_epochs, loss.data()))</p>

username: ptrblck
cooked: <p><code>.data</code> is an attribute not a method so you would have to remove the parentheses.<br>
However, the usage of <code>.data</code> is generally not recommended anymore and you should use <code>.item()</code> instead.</p>

username: ywr461903285
cooked: <p>wow great. it’s really a great help to me .thanks a lot.<br>
when i remove the parantheses,it’s really worked!! Bravo</p>

username: mamemoryyy111
cooked: <p>When I excute testing code, an error occured.</p>
<pre><code class="lang-auto"> File "/home/mamingrui/code/MyOwn/train_v1.py", line 61, in train
    grad_loss = grad_loss(flow)
TypeError: 'Tensor' object is not callable

</code></pre>
<p>This is the loss function.</p>
<pre><code class="lang-auto">def gradient_loss(s, penalty='l2'):
    dy = torch.abs(s[:, :, 1:, :, :] - s[:, :, :-1, :, :])
    dx = torch.abs(s[:, :, :, 1:, :] - s[:, :, :, :-1, :])
    dz = torch.abs(s[:, :, :, :, 1:] - s[:, :, :, :, :-1])

    if (penalty == 'l2'):
        dy = dy * dy
        dx = dx * dx
        dz = dz * dz

    d = torch.mean(dx) + torch.mean(dy) + torch.mean(dz)
    return d / 3.0

</code></pre>
<p>and this is the train.</p>
<pre><code class="lang-auto">    for epoch in range(iters):
        start_time = time.time()
        loss_batch = 0

        for batch_moving in train_set:
            print("^^^^^^moving size is {}^^^^^^".format(batch_moving.size()))
            wrap, flow = model(batch_moving, fixed)
            recon_loss = similarity_loss(wrap, fixed)
            grad_loss = grad_loss(flow)
            loss = recon_loss + reg_param * grad_loss

      
            loss_batch += loss

            print("The loss without average is {}".format(loss))

            opt.zero_grad()
            loss.backward()
            opt.step()

</code></pre>
<p>How can I fix this bug? very appreciate!</p>

username: ptrblck
cooked: <p>You are reusing the variable name <code>grad_loss</code> which will overwrite the function name here:</p>
<pre><code class="lang-python">grad_loss = grad_loss(flow)
</code></pre>
<p>Change the return value to <code>grad_loss_value</code> or any other unused name.</p>

username: mamemoryyy111
cooked: <p>WOW ! It worked well ! Thanks a lot ^-^</p>

username: PriyankaJain-1998
cooked: <p><a class="mention" href="/u/ptrblck">@ptrblck</a><br>
Facing the same issue while implementing TableNET please help me out.<br>
Reference I took : <a href="https://medium.datadriveninvestor.com/extract-tables-from-images-using-tablenet-249627142e0d" class="inline-onebox" rel="noopener nofollow ugc">Extract Tables from Images Using Tablenet — An End-to-End Solution | by Namratesh Shrivastav | DataDrivenInvestor</a><br>
Here are the code snippets.<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/9/0/903df5239957276023c8493451c00d6666d5ec2a.png" data-download-href="https://discuss.pytorch.org/uploads/default/903df5239957276023c8493451c00d6666d5ec2a" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/9/0/903df5239957276023c8493451c00d6666d5ec2a.png" alt="image" data-base62-sha1="kA1uX3QBzib8hafnL3DVInl4D34" width="690" height="313" data-dominant-color="EFEEEE"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">1081×491 34.7 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>

username: PriyankaJain-1998
cooked: <p>Error when I call it.<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/2/7/27a5731c42b743693f261e276da730493290e677.png" data-download-href="https://discuss.pytorch.org/uploads/default/27a5731c42b743693f261e276da730493290e677" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/2/7/27a5731c42b743693f261e276da730493290e677.png" alt="image" data-base62-sha1="5EJ5VreSYiabA1I3or1UEYc2oVp" width="690" height="302" data-dominant-color="F0F0F0"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">1143×501 40.8 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>

username: ptrblck
cooked: <p>It seems you are using Keras, so I would recommend to post the question in their discussion board or StackOverflow, as you might find Keras experts there. <img src="https://discuss.pytorch.org/images/emoji/apple/wink.png?v=9" title=":wink:" class="emoji" alt=":wink:"><br>
Based on the error message I guess you are trying to cal a module, while it’s a tensor.</p>

username: Mohammedsohil_Shaikh
cooked: <p>The tensor object is not callable. Got an error while trying to calculate accuracy.<br>
I am new to PyTorch.</p>
<pre><code class="lang-auto">def accuracy(outputs, labels):
    _, preds = torch.max(outputs, dim=1)
    return torch.tensor(torch.sum(preds == labels).item() / len(preds))

n_total_steps = len(train_loader)
for epoch in range(epochs):
    for i, (images, labels) in enumerate(train_loader):
       
        images = images.to(DEVICE)
        labels = labels.to(DEVICE)

        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)
        accuracy = accuracy(outputs, labels)
        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i+1) % 185 == 0:
            print (f'Epoch [{epoch+1}/{epochs}], Step [{i+1}/{n_total_steps}], Loss: {loss.item():.4f}, accuracy: {accuracy:.2f}')
</code></pre>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/5/1/51f30b06bf5554579d25d6d9453f743cc8fcfbbd.png" data-download-href="https://discuss.pytorch.org/uploads/default/51f30b06bf5554579d25d6d9453f743cc8fcfbbd" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/5/1/51f30b06bf5554579d25d6d9453f743cc8fcfbbd_2_690x426.png" alt="image" data-base62-sha1="bGXokIoL4g4pOAGCgvkBa3RHGz3" width="690" height="426" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/5/1/51f30b06bf5554579d25d6d9453f743cc8fcfbbd_2_690x426.png, https://discuss.pytorch.org/uploads/default/optimized/3X/5/1/51f30b06bf5554579d25d6d9453f743cc8fcfbbd_2_1035x639.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/5/1/51f30b06bf5554579d25d6d9453f743cc8fcfbbd_2_1380x852.png 2x" data-dominant-color="282828"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">2102×1298 252 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>

username: ptrblck
cooked: <p>You are defining <code>accuracy</code> as a function name and are then assigning the result to a tensor with the same name. In the next iteration <code>accuracy</code> would thus be a tensor (not the function anymore) and the error is raised. Change either the function or tensor name and it should work.</p>

username: Mohammedsohil_Shaikh
cooked: <p>Hey, <a class="mention" href="/u/ptrblck">@ptrblck</a>  Thanks.<br>
I got it.</p>

username: Z_Rezaee
cooked: <p>hello everyone<br>
i get this error when i use from SGD-loss function. plz help me…</p>
<pre><code class="lang-auto">criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.002, momentum=0.9)

num_epochs = 10
losses_SGD = []
for epoch in range(num_epochs):
    for i, (inputs, targets) in enumerate(train_dl):
        inputs = to_var(inputs)
        targets = to_var(targets)
        
         # forwad pass
        optimizer.zero_grad()
        outputs = model(inputs)
        
         # loss
        loss = criterion(outputs, targets)
        losses += [loss.data]
         # backward pass
        loss.backward()
        
         # update parameters
        optimizer.step()
        
         # report
        if (i + 1) % 50 == 0:
             print('Epoch [%2d/%2d], Step [%3d/%3d], Loss: %.4f'
                   % (epoch + 1, num_epochs, i + 1, len(train_ds) // batch_size, loss.data))
</code></pre>

username: ptrblck
cooked: <p>I’m not sure where the “‘Tensor’ object is not callable” error is raised, but your code will fail in:</p>
<pre><code class="lang-python">losses_SGD += [loss.item_()]
</code></pre>
<p>since <code>tensor.item_()</code> is not a valid method:</p>
<pre><code class="lang-python">criterion = nn.CrossEntropyLoss()
output = torch.randn(1, 10, requires_grad=True)
target = torch.randint(0, 10, (1,))
loss = criterion(output, target)
loss.item_()
# &gt; AttributeError: 'Tensor' object has no attribute 'item_'
</code></pre>

username: Z_Rezaee
cooked: <p>Oh! Sorry!! The code was modified. <img src="https://discuss.pytorch.org/images/emoji/apple/point_up_2.png?v=12" title=":point_up_2:" class="emoji" alt=":point_up_2:"><br>
In this code, in line</p>
<pre><code class="lang-auto">losses += [loss.data]
</code></pre>
<p>the error is raised.<br>
Thanks</p>

username: Z_Rezaee
cooked: <p>It was miraculously solved! <img src="https://discuss.pytorch.org/images/emoji/apple/star_struck.png?v=12" title=":star_struck:" class="emoji" alt=":star_struck:" loading="lazy" width="20" height="20"><br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/9/5/95ec5349557791cca66d226b3197a220fdf5910d.png" data-download-href="https://discuss.pytorch.org/uploads/default/95ec5349557791cca66d226b3197a220fdf5910d" title="Capture"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/9/5/95ec5349557791cca66d226b3197a220fdf5910d_2_690x338.png" alt="Capture" data-base62-sha1="loht0dkpriHyChzQLv4onTPxhfv" width="690" height="338" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/9/5/95ec5349557791cca66d226b3197a220fdf5910d_2_690x338.png, https://discuss.pytorch.org/uploads/default/optimized/3X/9/5/95ec5349557791cca66d226b3197a220fdf5910d_2_1035x507.png 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/9/5/95ec5349557791cca66d226b3197a220fdf5910d.png 2x" data-dominant-color="F7F8F8"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">Capture</span><span class="informations">1045×513 47.4 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>

username: Reddie23
cooked: <p>Hi, I am getting this error with an object not being callable.</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/3/9/39c5cab8a913d08f8298cfa7dfd38d27e9075c53.png" data-download-href="https://discuss.pytorch.org/uploads/default/39c5cab8a913d08f8298cfa7dfd38d27e9075c53" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/3/9/39c5cab8a913d08f8298cfa7dfd38d27e9075c53_2_690x246.png" alt="image" data-base62-sha1="8f4YWvY23Q9vvA6f85lr1OUtiRt" width="690" height="246" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/3/9/39c5cab8a913d08f8298cfa7dfd38d27e9075c53_2_690x246.png, https://discuss.pytorch.org/uploads/default/optimized/3X/3/9/39c5cab8a913d08f8298cfa7dfd38d27e9075c53_2_1035x369.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/3/9/39c5cab8a913d08f8298cfa7dfd38d27e9075c53_2_1380x492.png 2x" data-dominant-color="F4F5F4"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">1632×584 79.5 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>

username: carperbr
cooked: <p>Judging by the line, it appears that target is a tensor and not a function/callable that returns a tensor as it is being treated.</p>