Difference between MeanSquaredError & Loss (where loss = mse)

username: pytorchnewbie
cooked: <p>Hi!</p>
<p>So I am trying to calculate the average mean squared error over my validation dataset. I’ve done this in two ways: using Ignite’s Loss metric, where the loss_fn = nn.MSELoss() and then using Ignite’s MeanSquaredError metric, as can be seen in the code snippets below:</p>
<pre><code class="lang-auto">
loss_fn = torch.nn.MSELoss()

metrics = {
        "mse": Loss(
            loss_fn,
            output_transform=lambda infer_dict: (infer_dict["y_pred"], infer_dict["y"]),
        ),
    }

    for name, metric in metrics.items():
        metric.attach(engine, name)
</code></pre>
<p>vs.</p>
<pre><code class="lang-auto">metrics = {
        "mse": MeanSquaredError(
            output_transform=lambda infer_dict: (infer_dict["y_pred"], infer_dict["y"]),
        ),
    }

    for name, metric in metrics.items():
        metric.attach(engine, name)
</code></pre>
<p>I obtain two different results, as can be sceen from the two images below.</p>
<p>MeanSquaredError (the top left is evaluation MSE error, and top right is training MSE error):</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/e/a/eae94b8610d9467f615e2752b87c73895dd93915.png" data-download-href="https://discuss.pytorch.org/uploads/default/eae94b8610d9467f615e2752b87c73895dd93915" title="meansquarederror"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/e/a/eae94b8610d9467f615e2752b87c73895dd93915_2_529x500.png" alt="meansquarederror" data-base62-sha1="xw7yJYGItGjbVgplutzc8HiUdbT" width="529" height="500" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/e/a/eae94b8610d9467f615e2752b87c73895dd93915_2_529x500.png, https://discuss.pytorch.org/uploads/default/optimized/3X/e/a/eae94b8610d9467f615e2752b87c73895dd93915_2_793x750.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/e/a/eae94b8610d9467f615e2752b87c73895dd93915_2_1058x1000.png 2x" data-dominant-color="EAECF1"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">meansquarederror</span><span class="informations">1568×1482 246 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>Loss:</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/9/7/970ae2450248c2389d2d7b154feeaa5b68b8c6b0.png" data-download-href="https://discuss.pytorch.org/uploads/default/970ae2450248c2389d2d7b154feeaa5b68b8c6b0" title="loss"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/9/7/970ae2450248c2389d2d7b154feeaa5b68b8c6b0_2_524x500.png" alt="loss" data-base62-sha1="lybpPsk5o6iebsE2dMIXQoxmKNW" width="524" height="500" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/9/7/970ae2450248c2389d2d7b154feeaa5b68b8c6b0_2_524x500.png, https://discuss.pytorch.org/uploads/default/optimized/3X/9/7/970ae2450248c2389d2d7b154feeaa5b68b8c6b0_2_786x750.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/9/7/970ae2450248c2389d2d7b154feeaa5b68b8c6b0_2_1048x1000.png 2x" data-dominant-color="EEF0F3"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">loss</span><span class="informations">1532×1460 243 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>We can see that MSE has an error of the order of “M” whereas Loss has an error of the order of “K”. What accounts for this difference?</p>
<p>Initially I thought that its probably because Loss() probably calculates the average mean squared error per batch, and then takes the average of the averages, whereas MeanSquaredError (from what I saw in the source code) keeps track of all squared errors, and takes the average of all the squared errors across all the batches (so it only does one average, not average of averages). However, since the batch size is constant, the two results should be numerically equivalent. For example:</p>
<p>( (((7^2) + (8^2) + (13^2))/3) + (((3^2) + (6^2) + (11^2))/3)  )  / 2</p>
<p>is the same as:</p>
<p>(7^2) + (8^2) + (13^2) + (3^2) + (6^2) + (11^2)/6</p>
<p>because both groups in the first example have 3 elements in them.</p>
<p>Therefore, what accounts for the difference in magnitudes of the error functions?</p>
<p>Thanks so much!</p>

username: vfdev-5
cooked: <p>Ignite’s Metric API allows to inspect what happens batch by batch. All metrics allow to do the following:</p>
<pre><code class="lang-auto">mse_metric = MeanSquaredError()

mse_metric.reset()

mse_metric.update((y_pred1, y1))
# check result of the 1st batch
print(mse_metric.compute())

mse_metric.update((y_pred2, y2))
# check result of the 1st and 2nd batch
print(mse_metric.compute())
</code></pre>
<p>In this way you can compare both on your predictions and targets and see where comes from the difference.</p>
<p>HTH</p>
<p>PS.<br>
Shouldn’t <code>loss_fn = torch.nn.MSELoss()</code> have reduction “sum” ?</p>

username: pytorchnewbie
cooked: <p>So I did that and it turns out that MeanSquaredError metric has a different output than the Loss = torch.nn.MSELoss() even on the first batch.</p>
<p>From running:</p>
<pre><code class="lang-auto">        loss.backward()
        optimizer.step()

        mse_metric.reset()
        loss_metric.reset()

        mse_metric.update((y_pred, y))
        loss_metric.update((y_pred, y))

        print(mse_metric.compute())
        print(loss_metric.compute())
</code></pre>
<p>I got :</p>
<p>8.566025390625<br>
0.05948628857731819</p>

username: pytorchnewbie
cooked: <p>I have printed both update() steps after one iteration. They both have the same # _num_examples but loss has a different ._sum (37521646.875) than MeanSquaredErrors’ _sum_of_squared_errors (5403117056.0)… Is there a way to inspect even deeper the reason for this?</p>
<p>On a separate note, the _num_examples is wrong. In both cases, Loss and MeanSquaredError, te _num_examples is just the first element of the y.shape[0]. However, I want to do MSE on a tensor of [200,144], so the num_examples shouldn’t be 200, it should be 200*144. Is there a reason for why Ignite metrics only include the batch # as the num_examples?</p>

username: pytorchnewbie
cooked: <p>Also no it should not be “sum” because “Loss” documentation specifically says that it expects it to be the average loss. The source code then explains why it says: self._sum += average_loss.item() * n</p>

username: pytorchnewbie
cooked: <p>Ok i finally solved it . Loss uses torch.nn.MSELoss() which takes the sum of the errors of the (200,144) and then divides by 144, and this is then the ._sum value. The MeanSquaredError also takes the sum of the error of the (200,144), giving the _sum_of_squared_errors  value. But then, during compute(), both consider the num_of_examples to be 200 so then they both divide by 200. So Loss is basically = MeanSquaredError/144. I think this is probably something alot of people could get confused about  -  it might be worth specifying that MeanSquaredError only divides by the batch size to get the mean…</p>

username: vfdev-5
cooked: <p>Thanks for pointing out this difference ! Yes, both metrics should be definitely made coherent between each other and the result of <code>nn.MSELoss</code> … and we also need to update the docs.</p>
<p>If you would like to help us by opening an issue on that, it would be great !</p>

username: pytorchnewbie
cooked: <p>Sure!! Ill have to learn how to do that first though haha.</p>
<p>Just a last thought: I do think the way MeanSquaredError does it is superior to the way Loss (well, pytorch’s torch.nn.MSELoss) does it. The assumption makes more sense. If I have a tensor of (200,144) and take the total squared error, it is more likely that the user wants the mean error w respect to the batch than w respect to the dimensions of 144…</p>