Compute loss for each pixel individually

Cross entropy and BCELoss give average over all pixels. How can I compute a loss having same shape as the class prediction matrix where each pixel has loss value.

I want to get a loss output of shape (H,W) where each pixel has loss for thst particular pixel.

You can define your own loss function by extending nn.Module class.


import torch.nn as nn
import torch


class Loss(nn.Module):
    def __init__(self):
        
        super(Loss, self).__init__()
        

    def forward(self, y, y_pred):
        loss = # DO YOUR CALCULATION ON THE TENSOR OF YOUR IMAGE
        return loss

Is there any way or attribute available in the predefined loss functions?

Redution parameter does the job!

Based on BCELoss documentation, it seems if you set reduction ='none', you will get your output.
And as you mentioned in your question, the BCELoss averages, because the default value of reduction is mean.

So here is the code you should use:

criterion = BCELoss(reduction='none')