Custom loss function for accounting outliers as non-outliers

ttsesm: <p>I am working on a regression problem, where I want to modify the loss function so that to address a set of data which has outliers with high importance. This characteristic can be seen in the following images of two sample cases (on the left the raw values and on the right the sorted ones):</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/7/5/753ec18ce051738396e7fb532acffd42607d8b9c.png" data-download-href="https://discuss.pytorch.org/uploads/default/753ec18ce051738396e7fb532acffd42607d8b9c" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/7/5/753ec18ce051738396e7fb532acffd42607d8b9c_2_649x500.png" alt="image" data-base62-sha1="gJcjJr9xsAziXEN3YHJ74yXLL9W" width="649" height="500" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/7/5/753ec18ce051738396e7fb532acffd42607d8b9c_2_649x500.png, https://discuss.pytorch.org/uploads/default/original/3X/7/5/753ec18ce051738396e7fb532acffd42607d8b9c.png 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/7/5/753ec18ce051738396e7fb532acffd42607d8b9c.png 2x" data-dominant-color="E6EDF2"><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">image</span><span class="informations">695×535 114 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>So as you can see, usually the majority of the values are within a specific lower range and then I have a couple ones with a much higher intensity.</p>
<p>I’ve tried quite a few different common losses, e.g. MAE, MSE, RMSE, normal/reverse Huber loss which are failing to model the high range values since as I guess they consider them as outliers. Thus, I’ve tried to create a custom loss where for the low error it uses MAE and for the higher error MSE (which is know to be sensitive to outliers):</p>
<pre><code class="lang-auto">class CustomLoss(torch.nn.Module):
    def __init__(self):
        super(CustomLoss, self).__init__()

    def forward(self, predicted, true):
        errors = torch.abs(predicted - true)
        mask = errors &gt; 250
        return torch.mean((0.5 * mask * (errors ** 2)) + ~mask * errors)
</code></pre>
<p>However, this one still did not help much. More or less in all cases I am getting a poor prediction at the high range values (a bit better with MSE).</p>
<p>Thus I would like to ask whether someone has any idea how I could modify my loss so that it can address these high range values without considering them as outliers.</p>
<p>Thanks.</p>

ttsesm: <p>Also to visualize the output of the prediction values for the first sample case from each loss, check the following image:<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/3/1/31e63a36c7b32c9c2686fa32458f33f0aaded02b.png" data-download-href="https://discuss.pytorch.org/uploads/default/31e63a36c7b32c9c2686fa32458f33f0aaded02b" title="all_losses"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/3/1/31e63a36c7b32c9c2686fa32458f33f0aaded02b_2_627x500.png" alt="all_losses" data-base62-sha1="77qEFzXmGXc3Pd8z6piqdBIoeX9" width="627" height="500" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/3/1/31e63a36c7b32c9c2686fa32458f33f0aaded02b_2_627x500.png, https://discuss.pytorch.org/uploads/default/original/3X/3/1/31e63a36c7b32c9c2686fa32458f33f0aaded02b.png 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/3/1/31e63a36c7b32c9c2686fa32458f33f0aaded02b.png 2x" data-dominant-color="F0EAE8"><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">all_losses</span><span class="informations">643×512 110 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>

ttsesm: <p><a class="mention" href="/u/ptrblck">@ptrblck</a> what you describe in <a href="https://discuss.pytorch.org/t/dealing-with-imbalanced-datasets-in-pytorch/22596/36">this post</a>. Do you think it would work for my case scenario?</p>

ptrblck: <p>It could work and I think it’s worth a try at least.<br>
Let us know, if it helped in any way if you have the chance to try out this approach!</p>

ttsesm: <p><a class="mention" href="/u/ptrblck">@ptrblck</a> Thanks for the response. Some questions just to clarify, I will have to apply the clustering to my whole training dataset (I guess I do not need to do that for the testing dataset) or only to each corresponding batch size points each time?</p>
<p>For creating the clusters and getting the weights for each cluster the procedure is kind of straight forward:</p>
<blockquote>
<p>import torch<br>
import numpy as np<br>
from kmeans_pytorch import kmeans</p>
<p>data_size, dims, num_clusters = 7000, 1, 10 # this is for one sample (set of values/points to be regressed) with 7000 points, my batch size can vary from 4-12 samples while my whole training dataset is 400 samples<br>
x = np.random.randn(data_size, dims)<br>
x = torch.from_numpy(x)<br>
cluster_ids_x, cluster_centers = kmeans(X=x, num_clusters=num_clusters, distance=‘euclidean’, device=torch.device(‘cuda:0’))<br>
classes, class_counts = np.unique(cluster_ids_x, return_counts=True)</p>
<p>weight = 1. / class_counts</p>
</blockquote>
<p>Now do I need to assign these weights to each value separately or what? I do not understand that part, and also when you say:</p>
<p><em>“After creating the weights, you could write a function, which accepts the current output batch with the regression prediction, as well as your cluster centers (k-means dict), and returns a batch of weights, which can then be multiplied to create the final loss.”</em></p>
<p>This is gonna be in my “CustomLoss()” function, right?</p>

ptrblck: <aside class="quote no-group" data-username="ttsesm" data-post="5" data-topic="110376">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ttsesm/48/34005_2.png" class="avatar"> ttsesm:</div>
<blockquote>
<p>I will have to apply the clustering to my whole training dataset (I guess I do not need to do that for the testing dataset) or only to each corresponding batch size points each time?</p>
</blockquote>
</aside>
<p>I would perform the clustering on the training dataset to reuse the same cluster indices for the input samples. If you use it on the batch-level the clusters would “move around”.<br>
You wouldn’t need it for the test set, as the weighting should be only applied during training, if I understand the use case correctly.</p>
<aside class="quote no-group" data-username="ttsesm" data-post="5" data-topic="110376">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ttsesm/48/34005_2.png" class="avatar"> ttsesm:</div>
<blockquote>
<p>Now do I need to assign these weights to each value separately or what?</p>
</blockquote>
</aside>
<p>Yes, now you would need to map the contiguous input features to each cluster and select the corresponding weight for this input feature. This weight can then be multiplied with the unreduced loss before calculating the gradients.</p>

ttsesm: <p>Ok, after extracting and applying the weights on the values, I used a fair enough number of 50 clusters over my training dataset values, what I am noticing is that now my regressed values are generally overestimated:</p>
<p><img src="https://discuss.pytorch.org/uploads/default/original/3X/5/9/599b2c44927c7a8668b76b4de433a12d1ba66deb.png" alt="Picture1" data-base62-sha1="cMGWYSlqg1tEfVzR9S4YaliQa9R" width="498" height="405"></p>
<p>The custom loss that I’ve used is based on MAE:</p>
<pre><code class="lang-auto">
class L1Weighted(torch.nn.Module):
    def __init__(self):
        super(L1Weighted, self).__init__()

    def forward(self, predicted, true, weights):
        errors = torch.abs(predicted - true)
        return torch.mean(errors*weights)
</code></pre>
<p>I am trying to think if there is any other approach that I could try.</p>

googlebot: <p>try scaling targets down (say, divide by 1000), or log transform.</p>

ttsesm: <p>Is there any background idea behind this or just from what you see in the example graph (btw the overestimation can vary)?</p>

googlebot: <p>I think your issue is specific to MLP regression via mini-batch gradient descent - I wouldn’t expect this bias from GLM/robust regression methods, esp. if training data is homoscedastic.</p>
<p>So, you have a hidden layer that is prone to “forget” outliers due to mini-batching, plus MLPs are biased to output values in region around zero (in fact, outputs like 10000 may even be unreachable with vanilla SGD and low learning rate). Taken together, these things may explain the underfitting in your plots.</p>

ttsesm: <p>I see, your thinking is actually quite interesting. So as I understand you believe that the loss is not that a problem but rather the network architecture.</p>
<p>Actually to give some more details regarding the architecture that I am using I am working on 3D deep analysis and point clouds. Imagine that each value that you see on the graph corresponds to an intensity value for each point in the 3D space, and these intensity values are what I am trying to regress. For example check on the image below:</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/e/2/e2c6651c0b7a08ba25000ea1daf283cbd7de3e5b.png" data-download-href="https://discuss.pytorch.org/uploads/default/e2c6651c0b7a08ba25000ea1daf283cbd7de3e5b" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/e/2/e2c6651c0b7a08ba25000ea1daf283cbd7de3e5b_2_690x476.png" alt="image" data-base62-sha1="wm8XZiV3shJhSyAmrywFyzdEn7t" width="690" height="476" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/e/2/e2c6651c0b7a08ba25000ea1daf283cbd7de3e5b_2_690x476.png, https://discuss.pytorch.org/uploads/default/optimized/3X/e/2/e2c6651c0b7a08ba25000ea1daf283cbd7de3e5b_2_1035x714.png 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/e/2/e2c6651c0b7a08ba25000ea1daf283cbd7de3e5b.png 2x" data-dominant-color="23204F"><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">image</span><span class="informations">1062×734 182 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>The red points are emitting elements and then I am trying to regress the effect of this emission to each point in the space respectively. As you can see the higher error is in the points closer to the emitting elements due to the smaller distance.</p>
<p>Currently the model that I am using is the <a href="https://yochengliu.github.io/Relation-Shape-CNN/" rel="noopener nofollow ugc">RSConv</a> implementation from <a href="https://github.com/nicolas-chaulet/torch-points3d" rel="noopener nofollow ugc">torch-points3d</a> with <a href="https://github.com/nicolas-chaulet/torch-points3d/blob/9966f2350e03165158ba40b9f203aae7a16d31aa/torch_points3d/applications/rsconv.py#L149" rel="noopener nofollow ugc">a “unet” architecture</a> and the corresponding <a href="https://github.com/nicolas-chaulet/torch-points3d/blob/master/torch_points3d/applications/conf/rsconv/unet_4.yaml" rel="noopener nofollow ugc">config file</a>. The model initially is used for segmentation but I am trying to use it for regression. It indeed includes some MLPs and my batch size is quite relatively small imagine that for 400 point clouds my batch-size each time is 12 (maximum point clouds I can load in my gpu with the current size of 7000 points for each point cloud). Trying to downsample my point clouds and increase the batch size could help though.</p>
<p>Scaling/normalizing my values in the range 0-1 (initially my values can vary from 0-46000) is something I’ve tried but it doesn’t seem to work. At the end in the normalization the discripancy gap remains, so for example values that were before in the range of 0-1000 will go to the range 0-0.02 with the majority being in the 3 digits precision i.e. 0.00x so I am not sure whether this could help.</p>

googlebot: <aside class="quote no-group" data-username="ttsesm" data-post="11" data-topic="110376">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ttsesm/48/34005_2.png" class="avatar"> ttsesm:</div>
<blockquote>
<p>I see, your thinking is actually quite interesting. So as I understand you believe that the loss is not that a problem but rather the network architecture.</p>
</blockquote>
</aside>
<p>Huber loss or some similar step balancing method may still be necessary, but yea, I said “MLP” but meant deep networks in general; and more complex architectures are more prone to introduce bias.</p>
<aside class="quote no-group" data-username="ttsesm" data-post="11" data-topic="110376">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ttsesm/48/34005_2.png" class="avatar"> ttsesm:</div>
<blockquote>
<p>batch-size each time is 12 (maximum point clouds I can load in my gpu</p>
</blockquote>
</aside>
<p>Note that you can do gradient accumulation (i.e. do backward() without optimizer.step()), to increase effective batch size. Scheduled increasing may be optimal for faster convergence.</p>
<aside class="quote no-group">
<blockquote>
<p>Scaling/normalizing my values in the range 0-1</p>
</blockquote>
</aside>
<p>Scaling is not ideal here, as you’re using symmetric losses with positive only values, good thing about it is that it makes optimization paths shorter. So, log transform is the simplest correcting (and variance stabilizing) transformation for positive values, not necessarily the best one though…</p>

ttsesm: <aside class="quote no-group" data-username="googlebot" data-post="12" data-topic="110376">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/g/ba8739/48.png" class="avatar"> googlebot:</div>
<blockquote>
<p>Huber loss or some similar step balancing method may still be necessary, but yea, I said “MLP” but meant deep networks in general; and more complex architectures are more prone to introduce bias.</p>
</blockquote>
</aside>
<p>I was also trying the reverse <a href="https://arxiv.org/pdf/1606.00373.pdf" rel="noopener nofollow ugc">huber loss</a> (go to the loss function section) which seems to perform quite nicely so far, except of course the high range values.</p>
<aside class="quote no-group" data-username="googlebot" data-post="12" data-topic="110376">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/g/ba8739/48.png" class="avatar"> googlebot:</div>
<blockquote>
<p>Note that you can do gradient accumulation (i.e. do backward() without optimizer.step()), to increase effective batch size. Scheduled increasing may be optimal for faster convergence.</p>
</blockquote>
</aside>
<p>That’s actually a good point <img src="https://discuss.pytorch.org/images/emoji/apple/wink.png?v=12" title=":wink:" class="emoji" alt=":wink:" loading="lazy" width="20" height="20"></p>
<aside class="quote no-group" data-username="googlebot" data-post="12" data-topic="110376">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/g/ba8739/48.png" class="avatar"> googlebot:</div>
<blockquote>
<p>So, log transform is the simplest correcting (and variance stabilizing) transformation for positive values, not necessarily the best one though…</p>
</blockquote>
</aside>
<p>I didn’t understand that part clearly, where and when I should apply this transformation. You also suggested it in one of your previous messages. Should I apply this before I get the error between my targets and the regressed values in my loss function or elsewhere <img src="https://discuss.pytorch.org/images/emoji/apple/thinking.png?v=12" title=":thinking:" class="emoji" alt=":thinking:" loading="lazy" width="20" height="20"></p>

googlebot: <aside class="quote no-group" data-username="ttsesm" data-post="13" data-topic="110376">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ttsesm/48/34005_2.png" class="avatar"> ttsesm:</div>
<blockquote>
<p>I didn’t understand that part clearly, where and when I should apply this transformation. You also suggested it in one of your previous messages. Should I apply this before I get the error between my targets and the regressed values in my loss function or elsewhere</p>
</blockquote>
</aside>
<p>Yes, you change targets, so that their distribution is more similar to uniform. Actually, uniformity is also one of the reasons to use per-cluster regression for inhomogeneous targets (like you tried above IIUC)</p>

ttsesm: <aside class="quote no-group" data-username="googlebot" data-post="14" data-topic="110376">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/g/ba8739/48.png" class="avatar"> googlebot:</div>
<blockquote>
<p>Yes, you change targets, so that their distribution is more similar to uniform. Actually, uniformity is also one of the reasons to use per-cluster regression for inhomogeneous targets (like you tried above IIUC)</p>
</blockquote>
</aside>
<p>I see, thank a lot for the feedback.</p>
<p>Actually just for clarification, if I understand it correctly the use of weights is still reasonable to use after the transformation, right. I mean, in my loss function I first apply the log (or any other uniformity) transform to my target values, then I subtract them from the regressed ones and then I apply the weights, am I grasping it correctly?</p>

googlebot: <p>let’s say weights are as good as before <img src="https://discuss.pytorch.org/images/emoji/apple/wink.png?v=9" title=":wink:" class="emoji" alt=":wink:"> , as I’m not sure how such weights affect local bias with deep networks…</p>
<p>note that target tranformation has the same effect as adding an inverse transformation as activation function after the output layer - i.e. exp() and other smooth monotonic functions with positive outputs.</p>
<p>basically, you’re modulating gradient magnitudes per sample; custom loss, weights and transformations are just different (possibly complementary) methods for that.</p>

ttsesm: <p>Ok, after playing a bit with almost all the proposals (weights, transformations e.g. log and scaling (dividing by a value), gradient accumulation of mini-batches) for modulating the gradient magnitudes per sample I am still facing more or less the same behavior, still the network cannot handle this discrepancy to the high range values.</p>
<p>I’ve tried to make a better visualization of the problem. I’ve split my data in 10 clusters, and this is how my whole testing dataset looks like:<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/8/5/851f41911403eb96d302d3e7a2919a9358c6292a.png" data-download-href="https://discuss.pytorch.org/uploads/default/851f41911403eb96d302d3e7a2919a9358c6292a" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/8/5/851f41911403eb96d302d3e7a2919a9358c6292a_2_690x378.png" alt="image" data-base62-sha1="iZEt6KuSwRyEdu3UlRDFx0niglQ" width="690" height="378" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/8/5/851f41911403eb96d302d3e7a2919a9358c6292a_2_690x378.png, https://discuss.pytorch.org/uploads/default/optimized/3X/8/5/851f41911403eb96d302d3e7a2919a9358c6292a_2_1035x567.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/8/5/851f41911403eb96d302d3e7a2919a9358c6292a_2_1380x756.png 2x" data-dominant-color="F2F2F2"><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">image</span><span class="informations">2560×1406 113 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>and this is the amount of values per cluster:</p>
<pre><code>       1      165197
       2      187126
       3      137637
       4       94646
       5       65813
       6       40318
       7       19070
       8        6263
       9         651
      10          79
</code></pre>
<p>as it can be noticed the majority of my values apply within the first more or less 7 clusters.</p>
<p>Then as you can see below my estimated values are capped more or less to the limit of the values of these 7 clusters:</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/0/c/0c2d28fdcd74af40cef8ddf412e80fc3efa73bdd.png" data-download-href="https://discuss.pytorch.org/uploads/default/0c2d28fdcd74af40cef8ddf412e80fc3efa73bdd" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/0/c/0c2d28fdcd74af40cef8ddf412e80fc3efa73bdd_2_690x378.png" alt="image" data-base62-sha1="1JIu3qnsB2mDbYARZlIE5BoeRGJ" width="690" height="378" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/0/c/0c2d28fdcd74af40cef8ddf412e80fc3efa73bdd_2_690x378.png, https://discuss.pytorch.org/uploads/default/optimized/3X/0/c/0c2d28fdcd74af40cef8ddf412e80fc3efa73bdd_2_1035x567.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/0/c/0c2d28fdcd74af40cef8ddf412e80fc3efa73bdd_2_1380x756.png 2x" data-dominant-color="D1D0D0"><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">image</span><span class="informations">2560×1406 632 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>end especially on the last cluster the values are underestimated, something that can be seen clearer in the following graph (green=overestimation, red=underestimation):</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/b/0/b019c80761d73adcf6ec885941fc0acdd062f230.png" data-download-href="https://discuss.pytorch.org/uploads/default/b019c80761d73adcf6ec885941fc0acdd062f230" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/b/0/b019c80761d73adcf6ec885941fc0acdd062f230_2_690x378.png" alt="image" data-base62-sha1="p7RgO9ZR1EG3zma6BQDOolF8opi" width="690" height="378" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/b/0/b019c80761d73adcf6ec885941fc0acdd062f230_2_690x378.png, https://discuss.pytorch.org/uploads/default/optimized/3X/b/0/b019c80761d73adcf6ec885941fc0acdd062f230_2_1035x567.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/b/0/b019c80761d73adcf6ec885941fc0acdd062f230_2_1380x756.png 2x" data-dominant-color="F3F1EF"><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">image</span><span class="informations">2560×1406 70 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>The above graphs made based on the L1 loss.</p>
<p>Now if I apply a log transform for example though it seems to be following the pattern better it is kind of amplified by a lot:<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/e/3/e3f63475f586a7b2745e3099c80016adeac3f31a.png" data-download-href="https://discuss.pytorch.org/uploads/default/e3f63475f586a7b2745e3099c80016adeac3f31a" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/e/3/e3f63475f586a7b2745e3099c80016adeac3f31a_2_690x378.png" alt="image" data-base62-sha1="wwDSoLyIRSx5cYedydjn98E5M9k" width="690" height="378" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/e/3/e3f63475f586a7b2745e3099c80016adeac3f31a_2_690x378.png, https://discuss.pytorch.org/uploads/default/optimized/3X/e/3/e3f63475f586a7b2745e3099c80016adeac3f31a_2_1035x567.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/e/3/e3f63475f586a7b2745e3099c80016adeac3f31a_2_1380x756.png 2x" data-dominant-color="F4F6F4"><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">image</span><span class="informations">2560×1406 50.6 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>Scaling (dividing targets by 100) seems to work a bit better but still output values are underestimated especially in the last clusters with the high range values:<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/8/3/8379275dd6f3796e20f9c16e0181d837ac5eb66f.png" data-download-href="https://discuss.pytorch.org/uploads/default/8379275dd6f3796e20f9c16e0181d837ac5eb66f" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/8/3/8379275dd6f3796e20f9c16e0181d837ac5eb66f_2_690x378.png" alt="image" data-base62-sha1="iL47oXpbqFYPZloWlHliKqtnqvJ" width="690" height="378" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/8/3/8379275dd6f3796e20f9c16e0181d837ac5eb66f_2_690x378.png, https://discuss.pytorch.org/uploads/default/optimized/3X/8/3/8379275dd6f3796e20f9c16e0181d837ac5eb66f_2_1035x567.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/8/3/8379275dd6f3796e20f9c16e0181d837ac5eb66f_2_1380x756.png 2x" data-dominant-color="F1EFEB"><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">image</span><span class="informations">2560×1406 81.2 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>As I see it, the main problem is the big imbalance of points with high range values.</p>

googlebot: <p>You should understand that with L1 loss (and non-quadaratic loss zones in general) you’re doing gradient descent based on error sign only, this may converge with help from lr scheduler and/or adaptive optimizer, but it is intrinsically harder, and big (compared to LR) initial errors  may be uncorrectable w/o downscaling.</p>
<p>Interesting log-transform results… I’d guess that your optimizer’s steps are too big, if you end up with 10^5 errors. This stuff with clusters may actually be bad, as gradients are scaled ~100-1000 times for your last clusters; this can mess up shared parameters and gradient variance estimates too much. Other possibilities include inappropriate LR &amp; scheduler params or non-quadratic loss issues I’ve mentioned.</p>
<p>You can also try <a href="https://en.wikipedia.org/wiki/Box-Cox_transformation" rel="noopener nofollow ugc">https://en.wikipedia.org/wiki/Box-Cox_transformation</a> to deal with exploding predictions, but that’s rather an auxiliary measure</p>

ttsesm: <p>Thank you Alex for the feedback and your time <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=12" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p>
<aside class="quote no-group" data-username="googlebot" data-post="18" data-topic="110376">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/g/ba8739/48.png" class="avatar"> googlebot:</div>
<blockquote>
<p>You should understand that with L1 loss (and non-quadaratic loss zones in general) you’re doing gradient descent based on error sign only, this may converge with help from lr scheduler and/or adaptive optimizer, but it is intrinsically harder, and big (compared to LR) initial errors may be uncorrectable w/o downscaling.</p>
</blockquote>
</aside>
<p>Ok, got that. So downscaling my values is necessary ;-).</p>
<aside class="quote no-group" data-username="googlebot" data-post="18" data-topic="110376">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/g/ba8739/48.png" class="avatar"> googlebot:</div>
<blockquote>
<p>Interesting log-transform results… I’d guess that your optimizer’s steps are too big, if you end up with 10^5 errors. This stuff with clusters may actually be bad, as gradients are scaled ~100-1000 times for your last clusters; this can mess up shared parameters and gradient variance estimates too much. Other possibilities include inappropriate LR &amp; scheduler params or non-quadratic loss issues I’ve mentioned.</p>
</blockquote>
</aside>
<p>You’ve guessed right that my optimizer steps were big, lowering it though improved the output but not good enough. So far scaling by a factor of 100 seems to perform better than everything else, though not good enough as well.</p>
<p>The main issue, is that my dataset is heavily imbalanced. For example if you consider that almost 90% or more of the values are laying within the range of 0-2000. It is normal that the network will learn to predict this range of values and would consider the rest in a less meaningful way. Weighting though I am not sure yet why it didn’t help, since in principle it should improve.</p>
<p>Another idea that came to my mind is whether it would be better (or it is possible) if I create a separate loss output for each cluster and then either combine them to an overall loss or somehow have a different regression branch for each cluster in the architecture. But I am not sure whether this would make any difference.</p>

googlebot: <aside class="quote no-group" data-username="ttsesm" data-post="19" data-topic="110376">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ttsesm/48/34005_2.png" class="avatar"> ttsesm:</div>
<blockquote>
<p>Weighting though I am not sure yet why it didn’t help, since in principle it should improve.</p>
</blockquote>
</aside>
<p>Well, that’s not proper oversampling - if you would show the network an “outlier” 100 times, 100 small gradient steps would have changing directions, instead of big linear jumps.</p>
<aside class="quote no-group" data-username="ttsesm" data-post="19" data-topic="110376">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ttsesm/48/34005_2.png" class="avatar"> ttsesm:</div>
<blockquote>
<p>Another idea that came to my mind is whether it would be better (or it is possible) if I create a separate loss output for each cluster and then either combine them to an overall loss or somehow have a different regression branch for each cluster in the architecture.</p>
</blockquote>
</aside>
<p>If you rule out numerous “configuration” issues, this leaves “forgetfulness” and “limited memory” as causes for big final errors (for training set, for validation set you may also experience poor generalization). In that case, architecture tweaks with specific intents may indeed help.</p>
<p>I’d suggest to try attention as a way to have non-shared parameter values and deal with “forgetfulness”.</p>
<p>Another (a bit similar) thing to try would be to train network to output quantiles of some  distribution approximating your whole dataset (log-normal perhaps), with non-trainable (0,1)-&gt;Y_domain final transform.</p>