VAE loss function (Cross entropy)

yuyaya: <p>Hello, the question is how can I calculate the reconstruct error at VAE in this case.</p>
<p>Now I’m trying to reconstruct inputs of shape (class, height, width) = (20, 100, 100) which I got from segmentation task (before argmax, let’s say logit).</p>
<p>I want to calculate the loss between input(logit) and output logit with cross-entropy but I don’t want to take argmax of both data.<br>
Since taking the argmax will simply ignore other class’s infomation.</p>
<p>Ordinary I have to do approach like below right?</p>
<pre><code class="lang-auto">input.shape = (20, 100, 100)
output.shape = (20, 100, 100)

label = torch.argmax(x, 1)
criterion = nn.CrossEntropyLoss()
loss = criterion()
</code></pre>
<p>But I believe this way just comparing both’s argmax data.<br>
So I come up with these codes.</p>
<pre><code class="lang-auto">def entropy(x, recon_x, h, w, batch, class_num, weight, ignore_id=19):
    
    softmax = nn.Softmax(dim=0)
    losses = torch.empty(h, w).to(device)
    
    for i in range(batch):
        
        loss = (softmax(x[i]) * softmax(recon_x[i]))
        
        for d in range(class_num):
            if d == ignore_id:
                continue
                
            weighted_loss = weight[d] * loss[d]
            torch.cat((losses, weighted_loss))
            
    return torch.sum(losses)

</code></pre>
<p>But I’m not sure if this makes sense.<br>
It’s so helpful if someone gives me an idea.</p>
<p>Thank you</p>

xian_kgx: <p>Cross entropy loss considers all your classes during training/evaluation.</p>
<p>Argmax is used only to get the class prediction (the class with the highest probability), this is used only during inference, not training/evaluation.</p>

yuyaya: <p>Thank you for your reply <a class="mention" href="/u/xian_kgx">@xian_kgx</a> .</p>
<p>And I think I understand what you’re saying.</p>
<p>But the reason I took argmax for input data is that I had to reshape the data size to fit the expected target size for nn.Crossentropyloss.<br>
<a href="https://pytorch.org/docs/stable/nn.html#crossentropyloss" class="onebox" target="_blank" rel="nofollow noopener">https://pytorch.org/docs/stable/nn.html#crossentropyloss</a></p>
<p>So again, <strong>input data’s shape to VAE</strong> is<br>
(Channel=Class, Height, Width) = (20, 100, 100)</p>
<p><strong>Output data’s from VAE</strong> is<br>
(Channel=Class, Height, Width) = (20, 100, 100)<br>
And I want to minimize the loss between those two.</p>
<p>To match the expected target shape for nn.Crossentropyloss, I took argmax.<br>
But the problem is, I don’t want to take argmax for input data since I want to keep each classes information. (Not only class which has the highest probability)</p>
<p>Thank you</p>

xian_kgx: <p>Can you try BCE loss instead? It calculates the probability of a class for each of the 20 classes. Or you could use MSE loss.</p>
<p>Your loss from this line:</p>
<blockquote>
<p>loss = (softmax(x[i]) * softmax(recon_x[i]))</p>
</blockquote>
<p>doesn’t seem correct. For each coordinate you have a value in the range [0, 1] from your softmax function. If your prediction (for a particular coordinate) is 0 and your target is 0, you have 0 loss. And if your prediction is 1 and your target is 1 you have loss of 1.</p>
<p>I suggest a simple MSE or BCE loss will do.</p>

yuyaya: <blockquote>
<p>I suggest a simple MSE or BCE loss will do.</p>
</blockquote>
<p>I tried, but it keeps giving me a huge negative number like below.<br>
Do you have any idea what is actually going on?<br>
Input to VAE is a range of[0 - 1] and output has the same range of number too.</p>
<p>And also, MSE didn’t work.<br>
Reconstructed data is not reproducing input data at all.<br>
With changing the param for KLD, I could get better results.<br>
But I don’t want to take this approach since it won’t be a general solution anymore if I changed the input data.</p>
<pre><code class="lang-auto"> 41%|████      | 13/32 [01:04&lt;01:27,  4.61s/it]
kld :  53.88439178466797 recon :  -53301.86328125
 44%|████▍     | 14/32 [01:08&lt;01:22,  4.58s/it]
kld :  52.833587646484375 recon :  -56408.796875
 47%|████▋     | 15/32 [01:13&lt;01:18,  4.59s/it]
kld :  51.79539489746094 recon :  -59532.7265625
 50%|█████     | 16/32 [01:17&lt;01:12,  4.56s/it]
kld :  50.653541564941406 recon :  -62645.80859375
 53%|█████▎    | 17/32 [01:22&lt;01:08,  4.54s/it]
kld :  49.04255676269531 recon :  -65793.15625
 56%|█████▋    | 18/32 [01:26&lt;01:03,  4.52s/it]
kld :  47.729461669921875 recon :  -68937.03125
 59%|█████▉    | 19/32 [01:31&lt;00:58,  4.51s/it]
kld :  47.20650100708008 recon :  -72088.6171875
 62%|██████▎   | 20/32 [01:35&lt;00:54,  4.51s/it]
kld :  46.273780822753906 recon :  -75279.53125
 66%|██████▌   | 21/32 [01:40&lt;00:49,  4.51s/it]
kld :  44.844871520996094 recon :  -78400.25
 69%|██████▉   | 22/32 [01:44&lt;00:44,  4.49s/it]
kld :  42.69890213012695 recon :  -81610.5
・
・
・
</code></pre>
<p>What do you think about the function below?<br>
Do you have any idea?</p>
<pre><code class="lang-auto">
inputs.shape = (512, 19, 64, 64)
outputs.shape = (512, 19, 64, 64)

def entropy(inputs, outputs, weight,batch=batch_size, h=64, w=64, class_num=19, ignore_id=19):
    
    softmax = nn.Softmax(dim=0)
    losses = torch.empty(h, w).to(device)
    
    for b in range(batch):
        
        loss = - softmax(inputs[b]) * torch.log(softmax(outputs[b]))
        
        for c in range(class_num):
            if c == ignore_id:
                continue
                
            weighted_loss = ((weight[c]) * loss[c]) / batch_size
            torch.cat((losses, weighted_loss))
            
    return torch.sum(losses)
</code></pre>

Shisho_Sama: <p>Why do you use CrossEntropy in a VAE? Arent you trying to reconstruct the input? in that case, either MSE or BCE should be used.</p>

yuyaya: <p><a class="mention" href="/u/shisho_sama">@Shisho_Sama</a></p>
<p>Do you know the theoretical reason why BCE, MSE is suited for VAE / AE loss function.<br>
I found these article or paper saying like</p>
<blockquote>
<p>’ it is usually used ’</p>
</blockquote>
<p>or</p>
<blockquote>
<p>’ There are two common loss functions used for training autoencoders, these include the mean-squared error (MSE) and the binary cross-entropy (BCE) ’</p>
</blockquote>
<p>But I really don’t get why channel-wise cross entropy is not suited in my case.</p>
<aside class="onebox allowlistedgeneric" data-onebox-src="https://arxiv.org/abs/1708.08487">
  <header class="source">
      <img src="https://static.arxiv.org/static/browse/0.3.4/images/icons/favicon-32x32.png" class="site-icon" width="" height="">

      <a href="https://arxiv.org/abs/1708.08487" target="_blank" rel="noopener nofollow ugc">arXiv.org</a>
  </header>

  <article class="onebox-body">
    <div class="aspect-image" style="--aspect-ratio:690/402;"><img src="https://static.arxiv.org/static/browse/0.3.4/images/arxiv-logo-fb.png" class="thumbnail" width="" height=""></div>

<h3><a href="https://arxiv.org/abs/1708.08487" target="_blank" rel="noopener nofollow ugc">On denoising autoencoders trained to minimise binary cross-entropy</a></h3>

  <p>Denoising autoencoders (DAEs) are powerful deep learning models used for feature extraction, data generation and network pre-training. DAEs consist of an encoder and decoder which may be trained simultaneously to minimise a loss (function) between an...</p>


  </article>

  <div class="onebox-metadata">
    
    
  </div>

  <div style="clear: both"></div>
</aside>

<aside class="onebox stackexchange" data-onebox-src="https://stats.stackexchange.com/questions/394582/why-is-binary-cross-entropy-or-log-loss-used-in-autoencoders-for-non-binary-da">
  <header class="source">

      <a href="https://stats.stackexchange.com/questions/394582/why-is-binary-cross-entropy-or-log-loss-used-in-autoencoders-for-non-binary-da" target="_blank" rel="noopener nofollow ugc">stats.stackexchange.com</a>
  </header>

  <article class="onebox-body">
      <a href="https://stats.stackexchange.com/users/38425/flek" target="_blank" rel="noopener nofollow ugc">
    <img alt="Flek" src="https://i.stack.imgur.com/ex30q.jpg?s=256&amp;g=1" class="thumbnail onebox-avatar" width="256" height="256">
  </a>

<h4>
  <a href="https://stats.stackexchange.com/questions/394582/why-is-binary-cross-entropy-or-log-loss-used-in-autoencoders-for-non-binary-da" target="_blank" rel="noopener nofollow ugc">Why is binary cross entropy (or log loss) used in autoencoders for non-binary data</a>
</h4>

<div class="tags">
  <strong>loss-functions, tensorflow, autoencoders, cross-entropy</strong>
</div>

<div class="date">
  asked by
  
  <a href="https://stats.stackexchange.com/users/38425/flek" target="_blank" rel="noopener nofollow ugc">
    Flek
  </a>
  on <a href="https://stats.stackexchange.com/questions/394582/why-is-binary-cross-entropy-or-log-loss-used-in-autoencoders-for-non-binary-da" target="_blank" rel="noopener nofollow ugc">11:51PM - 26 Feb 19 UTC</a>
</div>

  </article>

  <div class="onebox-metadata">
    
    
  </div>

  <div style="clear: both"></div>
</aside>


Shisho_Sama: <p>I think its because In BCE and MSE, everything(all pixel values) is treated equally, whereas in your case, it means there is one true class only. in reconstructing the input, we therefore try to check each pixel value with its respective real value regardless of other pixels.</p>

yuyaya: <p><a class="mention" href="/u/shisho_sama">@Shisho_Sama</a></p>
<p>Thank you for your opinion.</p>
<blockquote>
<p>whereas in your case, it means there is one true class only.</p>
</blockquote>
<p>In this part, what if target wasnt encoded in one-hot, rather than that, what if input and target was continuous number [0 to 1] still model recognize some true class?</p>

Shisho_Sama: <p>in VAE you dont use labels, you compare the actual input with the reconstructed version from decoder unless you want to use the conditional version which incorporates the one hot encoded label in the input and the latent variable z.</p>