Repository: ultralytics/yolov5

Issue:
AttributeError: 'list' object has no attribute 'size'
## ❔Question
Hey @glenn-jocher, 
After pulling the code to the last commit, I cannot train the model anymore! It was fine before and I was able to train without any problem on my custom dataset. Now, I'm getting this error during the validation `"AttributeError: 'list' object has no attribute 'size'`. I can get rid of the error with `try` and `expect` but I don't know why I am getting the error. 

## Additional context
```Traceback (most recent call last):
  File "train.py", line 508, in <module>
    train(hyp, opt, device, tb_writer, wandb)
  File "train.py", line 348, in train
    results, maps, times = test.test(opt.data,
  File "/home/detection/test.py", line 99, in test
    for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)):
  File "/home/anaconda3/envs/lib/python3.8/site-packages/tqdm/std.py", line 1171, in __iter__
    for obj in iterable:
  File "/home/detection/utils/datasets.py", line 105, in __iter__
    yield next(self.iterator)
  File "/home/anaconda3/envs/lib/python3.8/site-packages/torch/utils/data/dataloader.py", line 435, in __next__
    data = self._next_data()
  File "/home/anaconda3/envs/lib/python3.8/site-packages/torch/utils/data/dataloader.py", line 1085, in _next_data
    return self._process_data(data)
  File "/home/anaconda3/envs/lib/python3.8/site-packages/torch/utils/data/dataloader.py", line 1111, in _process_data
    data.reraise()
  File "/home/anaconda3/envs/lib/python3.8/site-packages/torch/_utils.py", line 428, in reraise
    raise self.exc_type(msg)
AttributeError: Caught AttributeError in DataLoader worker process 1.
Original Traceback (most recent call last):
  File "/home/anaconda3/envs/lib/python3.8/site-packages/torch/utils/data/_utils/worker.py", line 198, in _worker_loop
    data = fetcher.fetch(index)
  File "/home/anaconda3/envs/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py", line 44, in fetch
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "/home/anaconda3/envs/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py", line 44, in <listcomp>
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "/home/detection/utils/datasets.py", line 571, in __getitem__
    if x.size > 0:
AttributeError: 'list' object has no attribute 'size'
```


Discussion:

Resolving patch:
diff --git a/utils/datasets.py b/utils/datasets.py
--- a/utils/datasets.py
+++ b/utils/datasets.py
@@ -443,7 +443,6 @@ def cache_labels(self, path=Path('./labels.cache')):
                 assert (shape[0] > 9) & (shape[1] > 9), 'image size <10 pixels'
 
                 # verify labels
-                l = []
                 if os.path.isfile(lb_file):
                     nf += 1  # label found
                     with open(lb_file, 'r') as f:
@@ -458,6 +457,7 @@ def cache_labels(self, path=Path('./labels.cache')):
                         l = np.zeros((0, 5), dtype=np.float32)
                 else:
                     nm += 1  # label missing
+                    l = np.zeros((0, 5), dtype=np.float32)
                 x[im_file] = [l, shape]
             except Exception as e:
                 nc += 1
@@ -470,7 +470,7 @@ def cache_labels(self, path=Path('./labels.cache')):
             print(f'WARNING: No labels found in {path}. See {help_url}')
 
         x['hash'] = get_hash(self.label_files + self.img_files)
-        x['results'] = [nf, nm, ne, nc, i]
+        x['results'] = [nf, nm, ne, nc, i + 1]
         torch.save(x, path)  # save for next time
         logging.info(f"New cache created: {path}")
         return x
diff --git a/utils/plots.py b/utils/plots.py
--- a/utils/plots.py
+++ b/utils/plots.py
@@ -86,25 +86,12 @@ def plot_wh_methods():  # from utils.plots import *; plot_wh_methods()
     fig.savefig('comparison.png', dpi=200)
 
 
-def output_to_target(output, width, height):
+def output_to_target(output):
     # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
-    if isinstance(output, torch.Tensor):
-        output = output.cpu().numpy()
-
     targets = []
     for i, o in enumerate(output):
-        if o is not None:
-            for pred in o:
-                box = pred[:4]
-                w = (box[2] - box[0]) / width
-                h = (box[3] - box[1]) / height
-                x = box[0] / width + w / 2
-                y = box[1] / height + h / 2
-                conf = pred[4]
-                cls = int(pred[5])
-
-                targets.append([i, cls, x, y, w, h, conf])
-
+        for *box, conf, cls in o.cpu().numpy():
+            targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])
     return np.array(targets)
 
 
@@ -153,9 +140,7 @@ def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max
             labels = image_targets.shape[1] == 6  # labels if no conf column
             conf = None if labels else image_targets[:, 6]  # check for confidence presence (label vs pred)
 
-            boxes[[0, 2]] *= w
             boxes[[0, 2]] += block_x
-            boxes[[1, 3]] *= h
             boxes[[1, 3]] += block_y
             for j, box in enumerate(boxes.T):
                 cls = int(classes[j])


Test patch:
diff --git a/test.py b/test.py
--- a/test.py
+++ b/test.py
@@ -209,7 +209,7 @@ def test(data,
             f = save_dir / f'test_batch{batch_i}_labels.jpg'  # filename
             plot_images(img, targets, paths, f, names)  # labels
             f = save_dir / f'test_batch{batch_i}_pred.jpg'
-            plot_images(img, output_to_target(output, width, height), paths, f, names)  # predictions
+            plot_images(img, output_to_target(output), paths, f, names)  # predictions
 
     # Compute statistics
     stats = [np.concatenate(x, 0) for x in zip(*stats)]  # to numpy