Predicting objects outside dataset using FasterRCNN

natxo: <p>Hello!!!</p>
<p>Im new to pytorch and im trying to do transfer learning over a faster rcnn torchvision model.</p>
<p>I read several tutorials and tried for days but i allways get same result but im not able to find whats wrong, sure more experiece people will detect error easy.</p>
<p>I have two classes (cat,dog), cat is class 1 and dog is class 2. so according doc i create my model as follow</p>
<pre><code class="lang-auto">num_clases = 3 # two classes plus background
model = fasterrcnn_resnet50_fpn(pretrained=True)
in_features = model.roi_heads.box_predictor.cls_score.in_features
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_clases)
</code></pre>
<p>I have created my dataset, later a dataloader… etc etc and i also printed some random dataset and dataloader entries for sanity check… all looks ok.</p>
<p>I also plotted to tensorboard train loss and test loss and train for 20 epochs… sure can be better<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/b/5/b50c9192e3e83653be0e01b636ecb64661950a30.png" data-download-href="https://discuss.pytorch.org/uploads/default/b50c9192e3e83653be0e01b636ecb64661950a30" title="plot"><img src="https://discuss.pytorch.org/uploads/default/original/3X/b/5/b50c9192e3e83653be0e01b636ecb64661950a30.png" alt="plot" data-base62-sha1="pPDlILjoPYt6bOHGqwaFvdzjVxm" width="690" height="295" data-dominant-color="FAF9F9"><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">plot</span><span class="informations">697×298 19.8 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>Save the model</p>
<pre><code class="lang-auto">torch.save(model.state_dict(), f"models/"+MODEL_NAME+"/"+MODEL_NAME+"_final.pth")
</code></pre>
<p>And when i do inference, any object detected is a cat or a dog, i mean if i use a cow image, model says its a cat or a dog. So it works perfect with any image of test set but as soon as i use any image that not contains a dog or a cat… problem appears as any object will be cat or dog.</p>
<p>Is like any bbox that comes from the backbone will be setted as one of the two classes, but as i read it should have a class 0 to put all background (anything that is not a cat or a dog).</p>
<p>Sure is something dumb but im not able to find the cause.</p>
<p>Any help will be wellcome!!!</p>
<p>Thanks a lot</p>

oke-aditya: <p>Hi <a class="mention" href="/u/natxo">@natxo</a></p>
<p>Seems like you are trying to do a Out of sample prediction. So say currently you have a correctly trained FasterRCNN. And it will of course work well on cats / dogs. What you are trying to do is an out of sample prediction. That is trying to predict something that wasn’t part of your dataset.</p>
<p>You have 2 options, let me illustrate them <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>
<h3>
<a name="set-confidence-levels-1" class="anchor" href="#set-confidence-levels-1"></a>Set confidence levels</h3>
<p>So any such image of Cow, etc should have a low accuracy and you can probably set a threshold so that it ignores such predictions with low accuracy.</p>
<p>For e.g see  <a href="https://pytorch.org/vision/main/auto_examples/plot_visualization_utils.html#visualizing-bounding-boxes" class="inline-onebox" rel="noopener nofollow ugc">Visualization utilities — Torchvision main documentation</a></p>
<p>Where we use FasterRCNN and set threshold to ignore low confidence results. That should help as an image of cow or an image of fridge, will probably have low confidence and you can just filter that out.</p>
<h3>
<a name="hard-negative-sampling-2" class="anchor" href="#hard-negative-sampling-2"></a>Hard negative sampling.</h3>
<p>Well you remember you told of background class which is class index 0. This will help you to train model that specifically ignores particular data. You can try passing images of cow, and a zero tensor<br>
<code>torch.tensor([0.0, 0.0, 0.0, 0.0], dtype=torchf.float)</code> as an image of cow that you want to be supplied as background. The model will learn to ignore this (thanks to class index being 0 and the box tensor too being with 0 cordinates)</p>
<p>Hope this helps you.</p>
<p>Aditya Oke</p>

natxo: <p>Hi <a class="mention" href="/u/oke-aditya">@oke-aditya</a></p>
<p>Thanks for your detailed reply, i understand what you mean, let me add some info.</p>
<p><strong>1)</strong> Im currently only drawing detection with a score &gt;0.7 so setting confidence levels dont seems to work for me.</p>
<p><strong>2)</strong> To do negative samples… not only those samples images i told like cow are detected as dog/cats, everything that is not a dog/cat is mattched to one of those two categories… seems like nothing is background. Would i need to add negatives sample for anything that is not a dog or a cat¿</p>
<p>So i think i’m doing something wrong, i have do the same on tf and yolo in the past and no issues.</p>
<p>Please let me ellaborate as maybe i dont understand correctly how transfer learning works here</p>
<p>Im using a pretrained model with a backbone trained with coco, this backbone will feed head the bbox of what model detects.</p>
<p>And i replaced a new head to classify those detections that backbone sent</p>
<pre><code class="lang-auto">model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_clases)
</code></pre>
<p>in that case, possible classes are (“dog”,“cat”), those are in my dataset as index 1 and 2, i have no backgound class in my dataset.</p>
<p>When i set num_classes to 3 classes then are (0,1,2) so first is the “background”, i was expecting that the model will mark all things that are not a cat or a dog as background… but seems everything is feeded to box_predictor is set as 1 or 2, so a cat or a dog</p>
<p>I followed several tutorials like this one</p><aside class="onebox allowlistedgeneric" data-onebox-src="https://debuggercafe.com/custom-object-detection-using-pytorch-faster-rcnn/">
  <header class="source">
      <img src="https://debuggercafe.com/wp-content/uploads/2020/03/cropped-Facebook-32x32.png" class="site-icon" width="32" height="32">

      <a href="https://debuggercafe.com/custom-object-detection-using-pytorch-faster-rcnn/" target="_blank" rel="noopener nofollow ugc" title="12:30AM - 25 October 2021">DebuggerCafe – 25 Oct 21</a>
  </header>

  <article class="onebox-body">
    <div class="aspect-image" style="--aspect-ratio:690/388;"><img src="https://debuggercafe.com/wp-content/uploads/2021/10/Custom-Object-Detection-using-PyTorch-Faster-RCNN-e1633223630270.png" class="thumbnail" width="690" height="388"></div>

<h3><a href="https://debuggercafe.com/custom-object-detection-using-pytorch-faster-rcnn/" target="_blank" rel="noopener nofollow ugc">Custom Object Detection using PyTorch Faster RCNN - DebuggerCafe</a></h3>

  <p>Learn to carry out custom object detection using the PyTorch Faster RCNN deep learning model. A simple pipeline for training and inference.</p>

  <p>
    <span class="label1">Est. reading time: 27 minutes</span>
  </p>

  </article>

  <div class="onebox-metadata">
    
    
  </div>

  <div style="clear: both"></div>
</aside>

<p>That use a much smaller dataset than mine, i have 1330 images for train and 168 for test</p><aside class="onebox allowlistedgeneric" data-onebox-src="https://www.kaggle.com/datasets/tannergi/microcontroller-detection">
  <header class="source">
      <img src="https://www.kaggle.com/static/images/favicon.ico" class="site-icon" width="32" height="32">

      <a href="https://www.kaggle.com/datasets/tannergi/microcontroller-detection" target="_blank" rel="noopener nofollow ugc">kaggle.com</a>
  </header>

  <article class="onebox-body">
    <img src="https://storage.googleapis.com/kaggle-datasets-images/426242/811766/8fcbe577a762bc698d0c3fe03ce1ed98/dataset-card.jpg?t=2019-11-26-10-06-34" class="thumbnail onebox-avatar" width="500" height="500">

<h3><a href="https://www.kaggle.com/datasets/tannergi/microcontroller-detection" target="_blank" rel="noopener nofollow ugc">Microcontroller Detection</a></h3>

  <p>Microcontroller Object Detection Dataset</p>


  </article>

  <div class="onebox-metadata">
    
    
  </div>

  <div style="clear: both"></div>
</aside>

<p>Thanks for your time!!!</p>

oke-aditya: <p>Ok so confidence level is kind of hard to work for similar objects.</p>
<blockquote>
<p>everything that is not a dog/cat is mattched to one of those two categories</p>
</blockquote>
<p>Correct, that is valid, and hence the confidence. Try passing a fridge or say an apple. Does it say it says its dog with great confidence? Probably not.</p>
<blockquote>
<p>i was expecting that the model will mark all things that are not a cat or a dog as background</p>
</blockquote>
<p>Well not exactly. You need to supply a images with 0 tensors, so that they are marked as background. It won’t happen that model will just predict background for out of dataset objects. If you thought that’s what will happen for cow and you will get 0 as your class, then nope, that’s not how it will work.<br>
It’s slightly complicated as why it won’t.</p>

natxo: <p>Ahh ok!</p>
<p>So to general “discard” things that are not cat and dogs i must play with confidence, even if i need to say &gt;95 and to discard something concrete also provide it to dateset as a negative sample.</p>
<p>Correct?</p>
<p>Thank you!!!</p>

oke-aditya: <p>Yes, these are the two methods as far as I know. <img src="https://discuss.pytorch.org/images/emoji/apple/smile.png?v=12" title=":smile:" class="emoji" alt=":smile:" loading="lazy" width="20" height="20"> (Maybe there is something better, but I have used either of these and they work fine)</p>

oke-aditya: <p>Also let me know if above works <img src="https://discuss.pytorch.org/images/emoji/apple/smile.png?v=12" title=":smile:" class="emoji" alt=":smile:" loading="lazy" width="20" height="20">  and if it does, please mark as solution, so that other people might benefit. (P.S. A nice name for question maybe predicting objects outside dataset using FasterRCNN?)</p>

natxo: <p>Yep, you are right, sure others will have same question, i will confirm for sure but it will work.</p>
<p>I think im going to run test set, and put scores in a list to estimate score threshold… maybe helps</p>

BobPupkin: <p>Hello!<br>
I cannot set negative sample box on an image (for FasterRCNN training, same as the author has). I get the following error when I do:<br>
<code>ValueError: All bounding boxes should have positive height and width. Found invalid box [0.0, 0.0, 0.0, 0.0] for target at index 1.</code><br>
Have you ever encountered the same problem and what did you do to fix it?<br>
Thank you in advance!</p>