Hello,
I am trying to implement a loss function for an FCN. My output is a tensor of shape (n, c, h, w). My target is of shape (h, w). I would like to calculate a loss between the output and the tensor but the problem is that I have a mask. There is only a certain portion of the image that I am interested in calculating the loss for. I am trying to achieve my goal by unwrapping the image channels into arrays and then applying the mask on it. When I do this, I receive an error:
RuntimeError: Assertion `cur_target >= 0 && cur_target < n_classes’ failed.  at /pytorch/aten/src/THNN/generic/ClassNLLCriterion.c:93
Please see my code (There may be an easier way to do this as I am new to this):
def Loss(inp, target, mask):
    mask=torch.from_numpy(np.array(mask, dtype=np.uint8))
    target=target.contiguous().view(-1,1) #Flattening the Target Image
    mask = mask.contiguous().view(-1, 1)
    target = target[~mask] #Masking Target
    n, c, h, w = inp.size()
    inp1=np.zeros((target.shape[0],c)) #Creating new empty array with dimensions of (masked_region, c)
    inp1=torch.from_numpy(inp1)
    for i in range(c):
        inp1[:,i]=inp[0,i,:,:].view(-1,1)[~mask] #Masking the input and filling in the array created
    log_p = F.log_softmax(inp1, dim=1)
    criterion=nn.NLLLoss()
    loss = criterion(log_p, target)
    return loss

Thanks!