Multi-Class Cross Entropy Loss function implementation in PyTorch

edowson: <p>I’m trying to implement a multi-class cross entropy loss function in pytorch, for a 10 class semantic segmentation problem. The shape of the predictions and labels are both [4, 10, 256, 256] where 4 is the batch size, 10 the number of channels, 256x256 the height and width of the images.</p>
<p>The following implementation in numpy works, but I’m having difficulty trying to get a pure PyTorch implementation working, or even a hybrid (less performant one) working whereby I transfer the tensor out from PyTorch, calculate the loss in numpy, and return the tensor back to PyTorch.</p>
<p>Here is the working numpy version:</p>
<pre><code class="lang-auto">import numpy as np


def multi_class_cross_entropy_loss(predictions, labels):
    """
    Calculate multi-class cross entropy loss for every pixel in an image, for every image in a batch.

    In the implementation,
    - the first sum is over all classes,
    - the second sum is over all rows of the image,
    - the third sum is over all columns of the image
    - the last mean is over the batch of images.

    :param predictions: Output prediction of the neural network.
    :param labels: Correct labels.
    :return: Computed multi-class cross entropy loss.
    """

    loss = -np.mean(np.sum(np.sum(np.sum(labels * np.log(predictions), axis=1), axis=1), axis=1))

    return loss
</code></pre>
<p>This is an attempt at implementing the same function in PyTorch:</p>
<pre><code class="lang-auto">def multi_class_cross_entropy_loss_torch(predictions, labels):
    """
    Calculate multi-class cross entropy loss for every pixel in an image, for every image in a batch.

    In the implementation,
    - the first sum is over all classes,
    - the second sum is over all rows of the image,
    - the third sum is over all columns of the image
    - the last mean is over the batch of images.
    
    :param predictions: Output prediction of the neural network.
    :param labels: Correct labels.
    :return: Computed multi-class cross entropy loss.
    """

    loss = -torch.mean(torch.sum(torch.sum(torch.sum(labels * torch.log(predictions), dim=1), dim=1), dim=1))
    return loss
</code></pre>
<p>for which I get the following error:</p>
<pre><code class="lang-auto">line 34, in multi_class_cross_entropy_loss_torch
    loss = -torch.mean(torch.sum(torch.sum(torch.sum(labels * torch.log(predictions), dim=1), dim=1), dim=1))
RuntimeError: Expected object of type torch.LongTensor but found type torch.FloatTensor for argument #2 'other'
</code></pre>

ptrblck: <p>Are <code>labels</code> of type <code>torch.long</code>?<br>
If so, could you transform them to float with <code>labels.float()</code> and run it again?</p>

edowson: <p>Hi <a class="mention" href="/u/ptrblck">@ptrblck</a></p>
<p>Yes  <code>labels</code> were of type <code>torch.long</code>.  I converted them to float() from the output of the dataset, and I no longer get the type error.</p>

edowson: <p>Hi <a class="mention" href="/u/ptrblck">@ptrblck</a></p>
<p>How should I go about converting following numpy expression to an equivalent one using torch.sum() or torch.view().sum()?</p>
<p><code>loss = -np.mean(np.sum(np.sum(np.sum(labels * np.log(predictions), axis=1), axis=1), axis=1))</code></p>
<p>There was a discussion here <a href="https://discuss.pytorch.org/t/sum-mul-over-multiple-axes/1882">Sum / Mul over multiple axes</a> but I’m still trying to figure out the syntax.</p>

ptrblck: <p>You could try the following code:</p>
<pre><code class="lang-auto">batch_size = 4
-torch.mean(torch.sum(labels.view(batch_size, -1) * torch.log(preds.view(batch_size, -1)), dim=1))
</code></pre>

edowson: <p>That is compact, I’ll try it out.</p>
<p>What I came up was a simple one, just to get it working, one using just sum()</p>
<pre><code class="lang-auto">    n, c, h, w = predictions.size()
    nt, ct, ht, wt = labels.size()

    loss = (labels * torch.log(predictions)).sum(2).sum(2)  # for all pixels in an image
    loss = loss.sum(1)            # for all classes
    loss = -torch.mean(loss)  # for the entire batch
</code></pre>
<p>and the other using view().sum(), which was only different for the first line below:</p>
<pre><code class="lang-auto">    loss = (labels * torch.log(predictions)).view(n, c, -1).sum(2)  # for all pixels in an image
    loss = loss.sum(1)            # for all classes
    loss = -torch.mean(loss)  # for the entire batch
</code></pre>

edowson: <p>Hi <a class="mention" href="/u/ptrblck">@ptrblck</a></p>
<p>When I try to use the loss function in a train loop, the results come out as <code>nan</code></p>
<pre><code class="lang-auto">loss = loss_fn(output_batch, labels_batch)
logger.info("loss shape: {}, loss data: {}".format(loss.shape, loss.data.item()))
</code></pre>
<p><code>train_unet:train:87: loss shape: torch.Size([]), loss data: nan</code></p>
<p>I unit tested the implementation using some test matrices for predictions and labels, the implementation is okay.</p>
<p>Any idea what could cause this? It should be some large value at the start of training.</p>

ptrblck: <p>Are your predictions negative?<br>
You could check if with</p>
<pre><code class="lang-auto">(output_batch &lt; 0.0).any()
</code></pre>
<p>If so, <code>torch.log</code> will return <code>tensor(nan.)</code>.</p>

edowson: <p>Hi <a class="mention" href="/u/ptrblck">@ptrblck</a></p>
<p>Yes predictions are negative, <code>(output_batch &lt; 0.0).any()</code> returns <code>1</code></p>
<p>What should I do? The input image to a U-Net model is a set of RGB images, and training mask is a 10-channel mask corresponding to the 10 different classes that I want to segment in the image.</p>

ptrblck: <p>You could apply <code>F.sigmoid</code> on your predictions before passing it to the loss function.</p>
<p>However, maybe I misunderstood your use case.<br>
You said you are implementing a multi-class cross entropy. From the shape of your targets it looks like you would like to use a multi-label classification, i.e. each pixel location might have more than one class. Is this right or is every pixel belonging to one class only?</p>

edowson: <p>Hi <a class="mention" href="/u/ptrblck">@ptrblck</a></p>
<p>I have a set of 3-ch RGB images from the Kaggle DSTL Satellite Imagery Feature detection dataset. In it is has labelled polygonal data for 10 classes, ranging from buildings to trees, roads, waterways and vehicles.</p>
<p>I generated a binary mask for each of the classes, where each pixel value corresponds to a 1 if it contains a building or a 0 if it does not. I’ve stacked the individual marks into a single 10-ch mask.</p>
<p>Both the 3-ch image and 10-ch mask have been converted from numpy to torch float tensors, in the Dataset class.</p>
<p>For the NN model, I am using a U-Net model from <a href="https://github.com/minerva-ml/steppy-toolkit/blob/master/steppy_toolkit/pytorch/architectures/unet.py" rel="nofollow noopener">https://github.com/minerva-ml/steppy-toolkit/blob/master/steppy_toolkit/pytorch/architectures/unet.py</a></p>
<p>and configured the U-Net model to output 10 channels:</p>
<pre><code class="lang-auto">class UNet(nn.Module):
    def __init__(self, conv_kernel=3,
                 pool_kernel=3, pool_stride=2,
                 repeat_blocks=2, n_filters=8,
                 batch_norm=True, dropout=0.1,
                 in_channels=3, out_channels=10,
                 kernel_scale=3,
                 **kwargs):
</code></pre>
<p>I’m then passing the output_batch and labels_batch to the multi-class cross entropy loss function in my training loop, which is where I am getting the nan error.</p>

edowson: <p>This is the entire train loop:</p>
<pre><code class="lang-auto">
def train(model, optimizer, loss_fn, dataloader, metrics, params):
    """Train the model on `num_steps` batches

    Args:
        model: (torch.nn.Module) the neural network
        optimizer: (torch.optim) optimizer for parameters of model
        loss_fn: a function that takes batch_output and batch_labels and computes the loss for the batch
        dataloader: (DataLoader) a torch.utils.data.DataLoader object that fetches training data
        metrics: (dict) a dictionary of functions that compute a metric using the output and labels of each batch
        params: (Params) hyperparameters
        num_steps: (int) number of batches to train on, each of size params.batch_size
    """

    # set model to training mode
    model.train()

    # summary for current training loop and a running average object for loss
    summ = []
    loss_avg = RunningAverage()

    # Use tqdm for progress bar
    with tqdm(total=len(dataloader)) as t:
        for i, (train_batch, labels_batch) in enumerate(dataloader):
            # move to GPU if available
            if params.cuda:
                train_batch, labels_batch = train_batch.cuda(async=True), labels_batch.cuda(async=True)
            # convert to torch Variables
            train_batch, labels_batch = Variable(train_batch), Variable(labels_batch)

            # compute model output and loss
            output_batch = model(train_batch)
            #logger.debug("train output_batch.shape = {}. labels_batch.shape = {}".format(output_batch.shape, labels_batch.shape))

            # check if predictions are negative
            logger.info("negative predictions: {}".format((output_batch &lt; 0.0).any()))

            # compute loss
            loss = loss_fn(output_batch, labels_batch)
            logger.debug("loss: {}".format(loss.data.item()))

            # clear previous gradients, compute gradients of all variables wrt loss
            optimizer.zero_grad()
            loss.backward()

            # performs updates using calculated gradients
            optimizer.step()

            # Evaluate summaries only once in a while
            if i % params.save_summary_steps == 0:
                # extract data from torch Variable, move to cpu, convert to numpy arrays
                output_batch = output_batch.data.cpu().numpy()
                labels_batch = labels_batch.data.cpu().numpy()

                # compute all metrics on this batch
                summary_batch = {metric:metrics[metric](output_batch, labels_batch)
                                 for metric in metrics}
                summary_batch['loss'] = loss.data.item()
                summ.append(summary_batch)

            # update the average loss
            loss_avg.update(loss.data.item())

            t.set_postfix(loss='{:05.3f}'.format(loss_avg()))
            t.update()

    # compute mean of all metrics in summary
    metrics_mean = {metric:np.mean([x[metric] for x in summ]) for metric in summ[0]}
    metrics_string = " ; ".join("{}: {:05.3f}".format(k, v) for k, v in metrics_mean.items())
    logger.info("- Train metrics: " + metrics_string)


def train_and_evaluate(model, train_dataloader, val_dataloader, optimizer, loss_fn, metrics, params, model_dir,
                       restore_file=None):
    """Train the model and evaluate every epoch.

    Args:
        model: (torch.nn.Module) the neural network
        train_dataloader: (DataLoader) a torch.utils.data.DataLoader object that fetches training data
        val_dataloader: (DataLoader) a torch.utils.data.DataLoader object that fetches validation data
        optimizer: (torch.optim) optimizer for parameters of model
        loss_fn: a function that takes batch_output and batch_labels and computes the loss for the batch
        metrics: (dict) a dictionary of functions that compute a metric using the output and labels of each batch
        params: (Params) hyperparameters
        model_dir: (string) directory containing config, weights and log
        restore_file: (string) optional- name of file to restore from (without its extension .pth.tar)
    """

    # reload weights from restore_file if specified
    if restore_file is not None:
        restore_path = os.path.join(model_dir, restore_file + '.pth.tar')
        logger.info("Restoring parameters from {}".format(restore_path))
        load_checkpoint(restore_path, model, optimizer)

    best_val_acc = 0.0

    for epoch in range(params.num_epochs):
        # Run one epoch
        logger.info("Epoch {}/{}".format(epoch + 1, params.num_epochs))

        # compute number of batches in one epoch (one full pass over the training set)
        train(model, optimizer, loss_fn, train_dataloader, metrics=metrics, params=params)

        # Evaluate for one epoch on validation set
        val_metrics = evaluate(model, loss_fn, val_dataloader, metrics=metrics, params=params)

        # TODO: Fix TypeError: 'NoneType' object is not subscriptable
        val_acc = val_metrics['accuracy']
        is_best = val_acc&gt;=best_val_acc

        # Save weights
        save_checkpoint({'epoch': epoch + 1,
                         'state_dict': model.state_dict(),
                         'optim_dict' : optimizer.state_dict()},
                          is_best=is_best,
                          checkpoint=model_dir)

        # If best_eval, best_save_path
        if is_best:
            logger.info("- Found new best accuracy")
            best_val_acc = val_acc

            # Save best val metrics in a json file in the model directory
            best_json_path = os.path.join(model_dir, "metrics_val_best_weights.json")
            save_dict_to_json(val_metrics, best_json_path)

        # Save latest val metrics in a json file in the model directory
        last_json_path = os.path.join(model_dir, "metrics_val_last_weights.json")
        save_dict_to_json(val_metrics, last_json_path)

def main():
    # print some log messages
    logger.info("DSTL Satellite Imagery Feature Detection - Train U-Net Model")

    # load parameters
    # load parameters from configuration file
    params = Params('experiment/unet_model/params_3ch.yaml', ParameterFileType.YAML, ctx=None)

    # parameters
    logger.debug("parameters: \n{}\n".format(pformat(params.dict)))

    # use GPU if available
    params.cuda = torch.cuda.is_available()

    # Set the random seed for reproducible experiments
    torch.manual_seed(230)
    if params.cuda:
        torch.cuda.manual_seed(230)

    # dataset parameters, which includes download, input, output and mask generation parameters.
    dataset_params = params.dataset
    logger.debug("dataset parameters: \n{}\n".format(pformat(dataset_params)))

    # dataset
    logger.info("loading datasets...")
    train_set = DSTLSIFDDataset(dataset_params=dataset_params,
                                mode='train',
                                transform=True,
                                transform_mask=None,
                                download=False)

    dev_set   = DSTLSIFDDataset(dataset_params=dataset_params,
                                mode='dev',
                                transform=True,
                                transform_mask=None,
                                download=False)

    # dataloader
    logger.debug("train dataloader, batch size: {}, num workers: {}, cuda: {}".format(
        params.train['batch_size'],
        params.train['num_workers'],
        params.cuda));

    train_dl = DataLoader(dataset=train_set,
                          batch_size=params.train['batch_size'],
                          shuffle=True,
                          num_workers=params.train['num_workers'],
                          pin_memory=params.cuda)

    logger.debug("dev dataloader, batch size: {}, num workers: {}, cuda: {}".format(
        params.valid['batch_size'],
        params.valid['num_workers'],
        params.cuda));

    valid_dl = DataLoader(dataset=dev_set,
                          batch_size=params.valid['batch_size'],
                          shuffle=True,
                          num_workers=params.valid['num_workers'],
                          pin_memory=params.cuda)

    logger.info("- done.")

    # define the model and optimizer
    #model = UNet()
    model = UNet().cuda() if params.cuda else UNet()
    logger.info("using adam optimized with lr = {}".format(float(params.learning_rate)))
    optimizer = optim.Adam(model.parameters(), lr=float(params.learning_rate))

    # loss function
    loss_fn = multi_class_cross_entropy_loss  # nn.MSELoss()  # nn.L1Loss() # nn.CrossEntropyLoss()

    # maintain all metrics required in this dictionary- these are used in the training and evaluation loops
    metrics = {
        'accuracy': accuracy,
        # could add more metrics such as accuracy for each token type
    }

    # train the model
    logger.info("Starting training for {} epoch(s)".format(params.num_epochs))

    data_dir = "data/"
    model_dir = "experiment/unet_model"

    train_and_evaluate(model=model,
                       train_dataloader=train_dl,
                       val_dataloader=valid_dl,
                       optimizer=optimizer,
                       loss_fn=loss_fn,
                       metrics=metrics,
                       params=params,
                       model_dir=data_dir,
                       restore_file=None)


if __name__ == '__main__':
    main()
</code></pre>

ptrblck: <p>Ah ok, thanks for the info.<br>
It looks like a standard segmentation task.</p>
<p>I would suggest to use <code>nn.CrossEntropyLoss</code> for your use case.<br>
Have a look at the following code snippet:</p>
<pre><code class="lang-auto">n_class = 10
preds = torch.randn(4, n_class, 24, 24)
labels = torch.empty(4, 24, 24, dtype=torch.long).random_(n_class)

criterion = nn.CrossEntropyLoss()
loss = criterion(preds, labels)
</code></pre>
<p>You don’t have to save the target as a “one-hot encoded” tensor, but can just use the class indices for the criterion.</p>
<p>Maybe I misunderstood your question, but what is your goal of implementing the criterion manually?</p>

edowson: <p>Hi <a class="mention" href="/u/ptrblck">@ptrblck</a></p>
<p>I tried to use nn.CrossEntropyLoss() initially like so, with image set to float() and mask set to long() type:</p>
<pre><code class="lang-auto">    # loss function
    loss_fn = nn.CrossEntropyLoss() 
</code></pre>
<p>but it gave me this error:</p>
<pre><code class="lang-auto">  File "/tool/python/conda/env/gis36/lib/python3.6/site-packages/torch/nn/functional.py", line 1334, in nll_loss
    return torch._C._nn.nll_loss2d(input, target, weight, size_average, ignore_index, reduce)
RuntimeError: invalid argument 1: only batches of spatial targets supported (3D tensors) but got targets of dimension: 4 at /opt/conda/conda-bld/pytorch_1524590031827/work/aten/src/THCUNN/generic/SpatialClassNLLCriterion.cu:14
</code></pre>
<p>I attempted to write my own cross entropy loss function, thinking that I had to, because of the shape of my label outputs.</p>
<p>Is there a way to adapt and use the existing nn.CrossEntropyLoss() to work with the shape of my prediction and labels <code>[batch, channels, height, width]</code> ?</p>
<p>I think I’m missing something quite fundamental here. Is it okay to have my label masks with 10-channels, with each channel corresponding to a class (e.g. buildings)?</p>
<p>In your code snippet, labels is of shape [batch, height, width], whereas my labels are of shape [batch, channel, height, width]:<br>
<code>labels = torch.empty(4, 24, 24, dtype=torch.long).random_(n_class)</code></p>

ptrblck: <p>Yes, sure. You just have to get rid of the channel dimension in your targets, since you don’t need them.<br>
The targets are encoded as indices in the pixel positions. Have a look at my sample code. My target doesn’t have the channel dim and it’s working.<br>
Could you try that?</p>

edowson: <p>Hi <a class="mention" href="/u/ptrblck">@ptrblck</a></p>
<p>I’m not sure I follow where to drop the channels. Is it at the time of generating the mask? and have the mask generated as [batch, width, height]?</p>
<p>If so, how should I encode and generate the mask?</p>

ptrblck: <p>I’m not sure how the targets are saved in the kaggle data.<br>
Do you have target images with the “colors” encoding the classes?<br>
Could you post a sample?</p>

edowson: <p>This is an example 3-ch RGB image:</p>
<p><img src="https://discuss.pytorch.org/uploads/default/original/2X/a/a96aa82a135ac4abe4ecf06339b37dee926d928f.png" alt="6100_2_2_rgb" data-base62-sha1="oaJcDzx6HldbvM8jbmVR79LKNhd" width="240" height="240"></p>
<p>and this is a binary mask for buildings (class 0). A pixel value is set to 1 if it belongs to a building, and a 0 if it doesnt.</p>
<p><img src="https://discuss.pytorch.org/uploads/default/original/2X/9/9a22137e3548f8a583d4165c408437f5debd8583.png" alt="6100_2_2_mask_class_1_buildings" data-base62-sha1="lZwxn2y0FLNLcXir7gWdtBGUopl" width="320" height="240"></p>
<p>There are 10 channels in the mask, corresponding to the different classes. The mask shape is therefore [batch=4, channels=10, height=256, width=256].</p>
<p>This example shows the mask overlaid with the RGB image, to check for registration:</p>
<p><img src="https://discuss.pytorch.org/uploads/default/original/2X/a/ab828059d2cfd3bd62dab06a0500c294c17fea80.png" alt="6100_2_2_rgb_with_mask_class_1_buildings" data-base62-sha1="otffd6irSriESKaVgFqWKtGwyLm" width="240" height="240"></p>
<p>Some of the original papers on using Fully Convolutional Networks (FCN) for semantic segmentation shown a per-pixel wise prediction layer with 21 channels in the pixelwise prediction image, for a 20 class pascal voc dataset.</p>
<p>So this is the part that I don’t quite understand, should the output mask be a 10 or 11-channel image if the number of classes are 10?</p>
<p>[Edit: The earlier paper that used FCN on the PASCAL VOC dataset had an additional channel for background pixels, which is why it had 21 channels. The DSTL dataset has 10 labelled classes. Therefore, a mask should be generated for the background plus 10 channels, means that the total number of channels for the DSTL dataset, when using a single U-Net model should be 11.]</p>
<p><img src="https://discuss.pytorch.org/uploads/default/original/2X/e/e3b3d17a3b58e737bbb7a4b6efbcbba54ccd87fb.png" alt="fcn-semantic-segmentation-on-pascal-voc" data-base62-sha1="wulDY4TluZv8t8OVEwRBIfeIt5N" width="632" height="322"></p>
<p>I assumed that the color coding was done after the per-pixel wise prediction output, so that you take the detected pixels in each channel, color code it and generate a final colored mask.</p>

ptrblck: <p>Ok, so each channel corresponds to a class in your target images.<br>
Now we have to get the class and just save the indices.<br>
I created a small example where <code>target</code> is your target image and <code>labels</code> is the tensor we are using for the criterion:</p>
<pre><code class="lang-auto">target = torch.randn(1, 10, 24, 24)
target = F.softmax(target, dim=1) &gt; 0.5
# target has now a 1 in channel c if the pixel location belongs
# to that class (like your target images)

labels = torch.argmax(target, dim=1)
# labels has now indices for the corresponding class
</code></pre>

edowson: <p>Hi <a class="mention" href="/u/ptrblck">@ptrblck</a></p>
<p>I did some training yesterday and the NN seems to be learning, the loss keeps going down steadily and appears to be converging.</p>
<pre><code class="lang-auto">Epoch 1/100
100% 5/5 [00:05&lt;00:00,  1.80s/it, loss=2.325]
100% 5/5 [00:05&lt;00:00,  1.90s/it, loss=2.281]
100% 5/5 [00:05&lt;00:00,  1.78s/it, loss=2.242]


100% 5/5 [00:04&lt;00:00,  1.41s/it, loss=0.075]
100% 5/5 [00:05&lt;00:00,  1.95s/it, loss=0.072]

Epoch 100/100
100% 5/5 [00:04&lt;00:00,  1.50s/it, loss=0.070]
</code></pre>
<p>I’ll now need to look at the output masks and see if it is working correctly.</p>
<p>I must admit, I don’t quite follow what’s happening here. How does the class to index mapping work? I understand the part about taking the 10 classes and running it through the softmax to work as an activation for the 10 classes, but what happens to a batch of say [4, 10, 24, 24], do we just drop the batches when doing <code>F.softmax(target, dim=1) &gt; 0.5</code> ?</p>
<p>Don’t we somehow lose the correspondence between the loss per channel, when doing this, during back propagation? i.e. the loss is finally a single scalar value, but is the framework able to keep track of the loss per channel during back propagation?</p>