title: PyTorch Loss for Binary Semantic Segmentation with Sparse Input
body: <p>I have a semantic segmentation task of an image with only 2 classes: 1 and 0.</p>
  <p>The target is of shape <code>NxHxW</code>. Each sample on the batch is a binary image with size <code>HxW</code> with pixel values of 0 or 1.
  The output of the net is <code>Nx2xHxW</code> as we have 2 classes and the net output is the probability per class. So basically each channel is the probability of the class.</p>
  <p>How can I use Pytorch's <code>binary_cross_entropy()</code> and <code>binary_cross_entropy_with_logits()</code> in this case?</p>
  <p>In PyTorch, for the multi class case, I can use the <a href="https://pytorch.org/docs/stable/generated/torch.nn.functional.cross_entropy.html" rel="nofollow noreferrer">Cross Entropy Loss</a>. As described in <a href="https://stackoverflow.com/questions/67451818/pytorch-semantic-segmentation-loss-function">Pytorch semantic segmentation loss function</a> it can be used with the target including only the class index.</p>
  <p>Is there something equivalent for the binary case?
  Both <code>binary_cross_entropy()</code> and <code>binary_cross_entropy_with_logits()</code> requires both the input and the target to have the exact shape.</p>
  <p>What would be the recommended way to handle this, performance wise?</p>