'int' object is not callable on my custom loss funciton

akcaymert: <p>im trying to implement my loss function but having a problem. i tried to implement many different variable types such as long/float/int for ‘‘int’ object is not callable’’ . i cant understand where the problem is caused</p>
<pre><code class="lang-auto">labels.size = torch.Size([4, 11, 224, 224] , &lt;class 'torch.Tensor'&gt;
output.size = ([4, 11, 224, 224]) ,&lt;class 'torch.Tensor'&gt;
</code></pre>
<p>My Custom Loss Function</p>
<pre><code class="lang-auto">DSC = 2|XnY|/(|x|+|y|)

class Dice_Loss(torch.nn.Module):
    
    def __init__(self):
        super(Dice_Loss,self).__init__()
        
    def forward(self,x,y):
        x = x.view(-1,dtype = torch.float)
        y = y.view(-1,dtype = torch.float)
        square_x = torch.sqrt(torch.square(x))
        square_y = torch.sqrt(torch.square(y))
        intersection = 2*torch.mul(square_x,square_y)
        #multipication = torch.sum(torch.sqrt(torch.square(x)),torch.sqrt(torch.square(y)))
        multipication = square_x.add(square_y)
        return (intersection/multipication)
</code></pre>
<p>apply for</p>
<pre><code class="lang-auto">dice_loss = Dice_Loss.apply or Dice_Loss()
</code></pre>
<p>Traceback</p>
<pre><code class="lang-auto">TypeError                                 Traceback (most recent call last)
&lt;ipython-input-47-04945a48ff0c&gt; in &lt;module&gt;()
     14     print(output.size())
     15     print(labels.size())
---&gt; 16     loss_dice = dice_loss(labels,output)
     17     loss_dice.backward()
     18     optim.step()

TypeError: 'int' object is not callable
</code></pre>

Nikronic: <aside class="quote no-group" data-username="akcaymert" data-post="1" data-topic="104107">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/a/7c8e57/48.png" class="avatar"> akcaymert:</div>
<blockquote>
<p><code>loss_dice = dice_loss(labels,output)</code></p>
</blockquote>
</aside>
<p>Hi,</p>
<p>It is not about data types you are using, I think it’s just a  typo. Somewhere else in your code you are using <code>dice_loss</code> but it is no longer referring to <code>Dice_Loss</code> class.<br>
Error says <code>dice_loss</code> should be an instance of <code>Dice_Loss</code> is a <code>int</code>.</p>
<p>It is pretty simple to find errors like this, just run your code in debug mode and add <code>dice_loss</code> to watch and check its type after <code> dice_loss = Dice_Loss.apply or Dice_Loss()</code></p>
<p>Bests</p>

akcaymert: <p>Hİ nikronic, thanks for comment. Actually i referred to this;</p>
<pre><code class="lang-auto">dice_loss = Dice_Loss()
</code></pre>
<p>and used this</p>
<pre><code class="lang-auto">print(output.size(),type(output))
print(labels.size(),type(labels))
loss_dice= dice_loss(labels,output)
loss_dice.backward()
</code></pre>
<p>When I debug it by eyes again i couldn’t find any problem or i am quite  careless</p>

Nikronic: <p>Maybe I am missing something but for sure your loss class is correct (at least in case of your error) and another point is that you have syntax error in your class, <code>view</code> does not support <code>dtype</code>. So, if you pass anything to <code>dice_loss</code> then you should get error in the first line or even in a simpler scenario, if you pass nothing to <code>dice_loss</code> like:</p>
<pre><code class="lang-auto">loss = dice_loss()
</code></pre>
<p>you should get missing argument error but you are not getting it because somehow somewhere you are changing <code>dice_loss</code>.</p>

akcaymert: <p>You are right.</p>
<p>i changed that ; (i specified the place with “**”)</p>
<pre><code class="lang-auto">class Dice_Loss(torch.nn.Module):
    
    **def __init__(self,x,y):**
**        super(Dice_Loss,self).__init__()**
**        self.x = x**
**        self.y = y**
    def forward(self,x,y):
        self.x = x.view(-1)
        self.y = y.view(-1)
        square_x = torch.sqrt(torch.square(self.x))
        square_y = torch.sqrt(torch.square(self.y))
        intersection = 2*torch.mul(square_x,square_y)
        #multipication = torch.sum(torch.sqrt(torch.square(x)),torch.sqrt(torch.square(y)))
        multipication = square_x.add(square_y)
        return (intersection/multipication)
</code></pre>
<p>and</p>
<pre><code class="lang-auto">loss_dice = Dice_Loss(labels,output)
loss_dice.backward()
</code></pre>
<p>new trace</p>
<pre><code class="lang-auto">ModuleAttributeError                      Traceback (most recent call last)
&lt;ipython-input-16-41ead3ef64fb&gt; in &lt;module&gt;()
     15     print(labels.size(),type(labels))
     16     loss_dice = Dice_Loss(labels,output)
---&gt; 17     loss_dice.backward()
     18     optim.step()
     19     running_loss += (loss.item()/len(images))

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in __getattr__(self, name)
    777                 return modules[name]
    778         raise ModuleAttributeError("'{}' object has no attribute '{}'".format(
--&gt; 779             type(self).__name__, name))
    780 
    781     def __setattr__(self, name: str, value: Union[Tensor, 'Module']) -&gt; None:

ModuleAttributeError: 'Dice_Loss' object has no attribute 'backward'
</code></pre>
<p>i directly used Dice_Loss function in traning process but now that Dice_Loss object has no attribute backward. That is true but should i use backward method in new version of pytorch ? (i have seen a few comments without backward method  ) i can’t find example about this method .  Do you have an example about custom loss function backward method ?</p>

Nikronic: <aside class="quote no-group" data-username="akcaymert" data-post="5" data-topic="104107">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/a/7c8e57/48.png" class="avatar"> akcaymert:</div>
<blockquote>
<p>directly used Dice_Loss function</p>
</blockquote>
</aside>
<p>You should not do that!<br>
You only need to define <code>forward</code> method and pytorch will take care of backward for you.</p>
<p>I am still insisting on the point that you are having a small typo or something because I can use your first code and everything is just fine!</p>

akcaymert: <p>I’m sorry I misunderstood nikronic .I’ll check my code over and over again. Can you let me know if you see a mistake?</p>

Nikronic: <p>Frankly I do not see any errors with the lines you have shared. I just ran your first post and it works. Do you want to create a notebook on google colab with a toy example and share the link so I can take a deeper look?</p>