Per-class and per-sample weighting

apytorch: <p>How could one do both per-class weighting (probably CrossEntropyLoss) -and- per-sample weighting while training in pytorch?</p>
<p>The use case is classification of individual sections of time series data (think 1000s of sections per recording). The classes are very imbalanced, but given the continuous nature of the signal, I cannot over or under sample. And, they cannot be analyzed in isolation, as information from surrounding sections is necessary for classification of each section.</p>
<p>The other problem is sometimes individual sections of the time series will be junk (think: pure noise, or no signal -which I can easily quantify during pre-processing). Therefore, although the network will try to classify that section, I want to give it a weight of zero, so that no error is propagated for the network being unable to classify an unclassifiable section.</p>

ptrblck: <p>For the class weighting I would indeed use the <code>weight</code> argument in the loss function, e.g. <code>CrossEntropyLoss</code>.<br>
I assume you could save a tensor with the sample weight during your preprocessing step.<br>
If so, you could create your loss function using <code>reduction='none'</code>, which would return the loss for each sample. Using this you could return your sample weights with your data and target for the current batch, multiply it with the loss, and finally calculate the average before calling <code>backward()</code>.</p>

apytorch: <aside class="quote no-group" data-username="ptrblck" data-post="2" data-topic="25530">
<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/ptrblck/48/1823_2.png" class="avatar"> ptrblck:</div>
<blockquote>
<p>reduction</p>
</blockquote>
</aside>
<p>Ah, that sounds right. Let me repeat this back to make sure I’m on the same page.</p>
<p>I’d have a network output 3D tensor of (R recordings, C classes, S samples). CrossEntropyLoss, with reduction=‘none’ and a class_weight tensor of C classes, would return a 2D tensor of losses in (R recordings, S samples). Then I would multiply each R by the the unique sample_weight 1D tensor for that R. And finally average this before calling backward().</p>
<p>Does that sound correct? Btw, each recording has a different number of samples. Which, if I understand the benefits of the dynamic graph in pytorch, shouldn’t matter.</p>
<p>I’m still wrapping my head around moving from keras to pytorch. Thank you.</p>

ptrblck: <p>That sounds right!<br>
I’m not sure, what <code>S samples</code> are in your example, but here is a small dummy code snippet showing, what I mean:</p>
<pre><code class="lang-python">batch_size = 10
nb_classes = 2

model = nn.Linear(10, nb_classes)
weight = torch.empty(nb_classes).uniform_(0, 1)
criterion = nn.CrossEntropyLoss(weight=weight, reduction='none')

# This would be returned from your DataLoader
x = torch.randn(batch_size, 10)
target = torch.empty(batch_size, dtype=torch.long).random_(nb_classes)
sample_weight = torch.empty(batch_size).uniform_(0, 1)

output = model(x)
loss = criterion(output, target)
loss = loss * sample_weight
loss.mean().backward()
</code></pre>
<p>Do you mean each batch has a different size or what exactly are your samples?<br>
Could you post a random tensor showing one sample batch?</p>
<p>EDIT: Probably it’s also a good idea to normalize the sample weights so that the range of the loss will approx. have the same range and won’t depend on the current sample distribution in your batch.</p>
<pre><code class="lang-python">loss =(loss * sample_weight / sample_weight.sum()).sum()
</code></pre>
<p>I’m not sure in what range your weights are, so maybe it’s not necessary.</p>

apytorch: <aside class="quote no-group" data-username="ptrblck" data-post="4" data-topic="25530">
<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/ptrblck/48/1823_2.png" class="avatar"> ptrblck:</div>
<blockquote>
<p>Do you mean each batch has a different size or what exactly are your samples?<br>
Could you post a random tensor showing one sample batch?</p>
</blockquote>
</aside>
<p>Wow, thank you. The code helps me understand better what you were saying about how to actually implement the operation at the end.</p>
<p>Let’s see… I’m trying to think ahead to the final model, so bear with me. Also, I shouldn’t have used the word sample the way I did. Hopefully I explain it better below.</p>
<p>For each of the N samples (each individual recording), there are D divisions (the number of chunks that the recording is divided into (given that each recording is a different length, this number will vary), and four 1D features (each feature is a different length, and enter the graph at a different location - at least, that’s the plan). So, I see that as 4 input tensors for each sample/recording: (D,w), (D,x), (D,y), (D,z).</p>
<p>For each sample/recording, the output would be a 2D tensor after the softmax of (D, C).</p>
<p>Then, I would have a 1D class-weight tensor of 1xC classes, and for each sample, a 1D division(sample)-weight tensor of 1xD divisions.</p>

ptrblck: <p>Exactly! The 1D division(sample)-weight tensor would be also returned from the <code>DataLoader</code> or do you need to calculate and load it from “somewhere else”?<br>
As far as I understand the divisions vary based on some criteria of your recording.<br>
Would you want to process all divisions of a recording in a single batch or is a “windowed” approach plausible?<br>
A sliding window approach can sometimes be a bit tricky so don’t hesitate to ask here for some hints. <img src="https://discuss.pytorch.org/images/emoji/apple/wink.png?v=6" title=":wink:" class="emoji" alt=":wink:"></p>

apytorch: <p>The division(sample)-weight will be calculated for every sample/recording ahead of time, so I guess it can also be returned with DataLoader.</p>
<p>The division count varies just because each recording is a different length, with the largest being about 60% longer than the smallest. It’s just the nature of the data.</p>
<p>So, in my previous models using keras, I did use a windowed approach. However, because tensorflow requires the complete tensor to exist ahead of time, this was a massive waste of memory, since almost all of the data is duplicated using a sliding window. And this massive waste is what led to keeping the windows smaller than I would’ve liked; since the model could only see a small window at a time, it could never grasp the long-range trends and cycles that happen in the data. I’m exploring a combination of spatial pyramid pooling (SPP) and the [TCN] architecture as a possible solution to the issue that the 1st feature for each division is very long (and in its unprocessed form, also varies in length (the sampling rate is different)), and I would also like the network to train on the entire recording at the same time, so it can “see” the long-range cycles.</p>
<p>Hopefully that all made sense.</p>
<p>(<a href="https://github.com/locuslab/TCN/tree/master/TCN" rel="nofollow noopener">https://github.com/locuslab/TCN/tree/master/TCN</a>)</p>

Rakshit_Kothari: <p>Hi again <a class="mention" href="/u/ptrblck">@ptrblck</a><br>
I have been thinking about this answer and I’m confused about a few situations where this solution could potentially be problematic.<br>
Consider a situation where a few samples have a weight of 0. That is, intuitively, those samples (or observations or entries) are meaningless.</p>
<p><code>loss = loss * sample_weight</code> could result in a loss of 0 for those particular samples. Hence during gradient computation, wouldn’t the network technically be looking at a loss of 0 (perfect classification / regression) for samples which we weren’t confident to begin with? Do you think backprop on a loss of 0 could result in network crashes?</p>
<p>Furthermore, wouldn’t <code>sample_weight.requires_grad</code> be <code>true</code>? Do you think it could create complications during backprop?</p>
<p>I’ve been doing something similar and my network almost always crashes mid training.</p>

apytorch: <p><a class="mention" href="/u/rakshit_kothari">@Rakshit_Kothari</a>, I cannot speak to if this -could- cause a crash, or if sample_weight -should- require_grad. However, I am confident, as I trained several hundred networks using this method, that it worked for me.</p>

Rakshit_Kothari: <p>Hi <a class="mention" href="/u/apytorch">@apytorch</a>, is it possible that some of your sample weights during training could have a value of 0?</p>

apytorch: <p><a class="mention" href="/u/rakshit_kothari">@Rakshit_Kothari</a> I’m positive that at least 10% of my weights were 0.</p>

John1231983: <aside class="quote no-group" data-username="ptrblck" data-post="4" data-topic="25530">
<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/ptrblck/48/1823_2.png" class="avatar"> ptrblck:</div>
<blockquote>
<p>loss =(loss * sample_weight / sample_weight.sum()).sum()</p>
</blockquote>
</aside>
<p><a class="mention" href="/u/ptrblck">@ptrblck</a>: How to multiple the sample weight size of 4 and loss size of 4x8x8. This is an example</p>
<pre><code class="lang-auto">import torch
import numpy as np
import torch.nn as nn
num_class =2
b,h,w =4,8,8
input = torch.randn((b, 1, h, w), requires_grad=True)
target = torch.empty((b, h, w), dtype=torch.long).random_(num_class)
pred = torch.rand((b, num_class, h, w), dtype=torch.float)
criterion = nn.CrossEntropyLoss(reduction='none')
loss = criterion(pred, target)
sample_weight = torch.empty(b).uniform_(0, 1)

print (sample_weight.shape, loss.shape)
loss =(loss * sample_weight / sample_weight.sum()).sum()
loss.mean().backward()
</code></pre>

ptrblck: <p>You could unsqueeze the additional dimension and use broadcasting for the multiplication:</p>
<pre><code class="lang-python">sample_weight = sample_weight.view(-1, 1, 1)
loss =(loss * sample_weight / sample_weight.sum()).sum()
</code></pre>

John1231983: <aside class="quote no-group" data-username="ptrblck" data-post="13" data-topic="25530">
<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/ptrblck/48/1823_2.png" class="avatar"> ptrblck:</div>
<blockquote>
<p>sample_weight = sample_weight.view(-1, 1, 1) loss =(loss * sample_weight / sample_weight.sum()).sum()</p>
</blockquote>
</aside>
<p>Thanks. I used above code and it got error in backward()</p>
<pre><code class="lang-auto">---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
&lt;ipython-input-22-88aafe38e0f1&gt; in &lt;module&gt;()
     15 loss =(loss * sample_weight / sample_weight.sum()).sum()
     16 print (sample_weight.shape, loss.shape)
---&gt; 17 loss.mean().backward()
     18 
     19 #loss_total = torch.mean(loss * weights)

1 frames
/usr/local/lib/python3.6/dist-packages/torch/autograd/__init__.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables)
     91     Variable._execution_engine.run_backward(
     92         tensors, grad_tensors, retain_graph, create_graph,
---&gt; 93         allow_unreachable=True)  # allow_unreachable flag
     94 
     95 

RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
</code></pre>

ptrblck: <p>Your code snippet doesn’t include a tensor with <code>requires_grad=True</code> in the loss calculation.<br>
This would make the code work:</p>
<pre><code class="lang-python">pred = torch.rand((b, num_class, h, w), dtype=torch.float, requires_grad=True)
</code></pre>

John1231983: <aside class="quote no-group" data-username="John1231983" data-post="12" data-topic="25530">
<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/john1231983/48/4040_2.png" class="avatar"> John1231983:</div>
<blockquote>
<p>loss =(loss * sample_weight / sample_weight.sum()).sum() loss.mean().backward()</p>
</blockquote>
</aside>
<p>OMG, it worked. But I think</p>
<pre><code class="lang-auto">loss =(loss * sample_weight / sample_weight.sum()).sum()
loss.mean().backward()
</code></pre>
<p>Should be</p>
<pre><code class="lang-auto">loss =torch.mean(loss * sample_weight)
loss.backward()
</code></pre>
<p>By removing .sum() in the last and use torch.mean(). Am I correct?</p>
<p>To verify it, I used same_weight is 1 then it should be same as reduction=‘mean’</p>
<pre><code class="lang-auto">import torch
import numpy as np
import torch.nn as nn
num_class =2
b,h,w =4,8,8
input = torch.randn((b, 1, h, w), requires_grad=True)
target = torch.empty((b, h, w), dtype=torch.long).random_(num_class)
pred = torch.rand((b, num_class, h, w), dtype=torch.float, requires_grad=True)
criterion = nn.CrossEntropyLoss(reduction='none')
loss = criterion(pred, target)

sample_weight = torch.from_numpy(np.asarray([1, 1, 1, 1])).float()
sample_weight = sample_weight.view(-1, 1, 1)
loss1 =torch.mean((loss * sample_weight))
print (loss1)

loss2 =(loss * sample_weight / sample_weight.sum()).sum()
loss2 = loss2.mean()
print (loss2)

criterion = nn.CrossEntropyLoss()
loss = criterion(pred, target)
print (loss)
</code></pre>
<p>Output</p>
<pre><code class="lang-auto">tensor(0.7202, grad_fn=&lt;MeanBackward0&gt;)
tensor(46.0946, grad_fn=&lt;MeanBackward0&gt;)
tensor(0.7202, grad_fn=&lt;NllLoss2DBackward&gt;)
</code></pre>

YASJAY: <p>Does this ‘per-class per-sample weighing’ approach improve performance on imbalanced dataset compared to static weighing?</p>

ptrblck: <aside class="quote no-group quote-post-not-found" data-username="francistran" data-post="18" data-topic="25530">
<div class="title">
<div class="quote-controls"></div>
 francistran:</div>
<blockquote>
<p>Do you need to have ‘weight=weight’ when initializing the criterion?</p>
</blockquote>
</aside>
<p>No, the <code>weight</code> argument is optional.</p>
<aside class="quote no-group quote-post-not-found" data-username="francistran" data-post="18" data-topic="25530">
<div class="title">
<div class="quote-controls"></div>
 francistran:</div>
<blockquote>
<p>and if we do, what’s the purpose?</p>
</blockquote>
</aside>
<p>It will be used to weight the class losses as given by the formula in the docs.</p>
<aside class="quote no-group quote-post-not-found" data-username="francistran" data-post="18" data-topic="25530">
<div class="title">
<div class="quote-controls"></div>
 francistran:</div>
<blockquote>
<p>Can you just have criterion = nn.CrossEntropyLoss(reduction=‘none’)</p>
</blockquote>
</aside>
<p>Yes, this should work but would of course not add weighting what this topic was about.</p>
<aside class="quote no-group quote-post-not-found" data-username="francistran" data-post="18" data-topic="25530">
<div class="title">
<div class="quote-controls"></div>
 francistran:</div>
<blockquote>
<p>Especially with nb_classes = 1. I guess it’s not really needed…</p>
</blockquote>
</aside>
<p><code>nb_classes=1</code> in <code>nn.CrossEntropyLoss</code> wouldn’t make sense since your model would only predict a single class and could thus never be wrong. <code>nn.CrossEntropyLoss</code> is used for multi-class classification/segmentation use cases.</p>

gk123: <p>How can the per sample weighting be implemented if you have a test set?<br>
Would it be something like:<br>
pred = model(X)<br>
test_loss += loss_fn(pred, y).item()<br>
test_loss += (test_loss * sample_weight / sample_weight.sum()).sum()</p>

gk123: <p><code>Can you just have criterion = nn.CrossEntropyLoss(reduction='none')</code><br>
Am I right in thinking this would apply just the per sample weighting (and not the per class weighting)?</p>
<p>And for per sample weighting, do the weights need to be appended to the input data / X?:<br>
x = torch.cat((x, sample_weight), dim=1)</p>