Use YOLO after train

tetelevm: <p>I need to train YOLOv5 on my data and then use it in a program. I trained it from a <a href="https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data" rel="noopener nofollow ugc">tutorial</a> on their github:</p>
<pre><code class="lang-auto"># download .zip from github
cd /yolo/yolov5/
!python train.py --batch 10 --epochs 40 --data ./data.yaml --cfg ./models/yolov5m.yaml --weights '' --name yolo_m --nosave --cache
</code></pre>
<p>I replaced the parameters  in training.</p>
<pre><code class="lang-auto">nc: 7  # &lt;- on yolov5m.yaml
parser.add_argument('--img-size', default=[504, 378], ...)  # &lt;- on train.py
</code></pre>
<p>Then in ‘./runs/train/’ the script saved the models that were there during training. In the other script I take the best model and try to use it:</p>
<pre><code class="lang-auto">device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
weigths = torch.load('./runs/train/yolo_m-12/weights/best.pt')
model = weigths['model']
model = model.to(device)
_ = model.eval()

# terrible translation of the image into the input data :)
image = cv2.imread('image.jpg')  # 504x378 image
image = transforms.ToTensor()(image)
image = torch.tensor(np.array([img.numpy()]))
image = image.to(device)
image = image.half()

model(image)
</code></pre>
<p>And this causes the following error:</p>
<pre><code class="lang-auto">~/wf/env/lib/python3.9/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1049         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1050                 or _global_forward_hooks or _global_forward_pre_hooks):
-&gt; 1051             return forward_call(*input, **kwargs)
   1052         # Do not call functions when jit is used
   1053         full_backward_hooks, non_full_backward_hooks = [], []

~/yolo/yolov5/models/yolo.py in forward(self, x, augment, profile)
    121             return self.forward_augment(x)  # augmented inference, None
    122         else:
--&gt; 123             return self.forward_once(x, profile)  # single-scale inference, train
    124 
    125     def forward_augment(self, x):

~/yolo/yolov5/models/yolo.py in forward_once(self, x, profile)
    152                 logger.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f}  {m.type}')
    153 
--&gt; 154             x = m(x)  # run
    155             y.append(x if m.i in self.save else None)  # save output
    156 

~/wf/env/lib/python3.9/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1049         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1050                 or _global_forward_hooks or _global_forward_pre_hooks):
-&gt; 1051             return forward_call(*input, **kwargs)
   1052         # Do not call functions when jit is used
   1053         full_backward_hooks, non_full_backward_hooks = [], []

~/yolo/yolov5/models/common.py in forward(self, x)
    208 
    209     def forward(self, x):
--&gt; 210         return torch.cat(x, self.d)
    211 
    212 

RuntimeError: Sizes of tensors must match except in dimension 2. Got 63 and 64 (The offending index is 0)
</code></pre>
<p>How do I fix the error or how do I load the model/weights correctly to make predictions normally?</p>

tetelevm: <p>To be honest, I’m wrong to ask it here and not in their github, but maybe someone has encountered this problem.</p>

ptrblck: <p>Usually this type of error is raised if you have some skip connections in the model (or anything similar where you are concatenating activations) and are using an “unsupported” spatial shape for the input.<br>
“Unsupported” means that the model wasn’t designed to work with any arbitrary shape, but often well defined shapes (or at least shapes which are divisible by 2).<br>
E.g. while inputs in the shape <code>[batch_size, 3, 224, 224]</code> might work, the concatenation could fail if you change it to <code>[batch_size, 3, 227, 227]</code> or so.<br>
The error message also points to a mismatch of a single row/column (63 vs 64) so I would recommend to check the input shape and make sure it’s supposed to work.</p>

tetelevm: <p>I figured out the problem and explained it on <a href="https://github.com/ultralytics/yolov5/issues/3661" rel="noopener nofollow ugc">YOLO github</a>, but I will duplicate it here for web-search.</p>
<p>Indeed, the error was in the mismatch of tensor size. I was feeding the input <code>tensor</code> (<code>ToTensor()(image_like_nparray)</code>). And if you enter a tensor, it should be by size <code>(imgsz, imgsz)</code> (512 for me), and my tensor was <code>(504, 378)</code>, which led to the error.</p>
<p>And to make it all right, you need to load <code>numpy.array</code>, and then model will bring everything to the tensor and the required sizes by itself.</p>
<p>P.S. <a class="mention" href="/u/ptrblck">@ptrblck</a> Thanks, you’re cool.</p>