Ultralytics YOLOv8 training failed for torch.cat(): expected a non-empty list of Tensors

I am using Ultralytics for YOLOv8. I am getting this error while training the model:

RuntimeError: torch.cat(): expected a non-empty list of Tensors

The images are already converted to 500×500, padded, labelled using LabelImg and converted to YOLO format from Pascal VOC.

model.py looks like:

import os
import random
import shutil
import torch
from torchvision import transforms
from PIL import Image

# Define paths
img_dir = r"locationdataimagestrain"
val_dir = r"locationdataimagesval"
train_file = r"locationdatatrain.txt"
valid_file = r"locationdatavalid.txt"

# Create validation directory if it doesn't exist
if not os.path.exists(val_dir):
    os.makedirs(val_dir)

# Get list of all image files
img_files = [os.path.join(img_dir, img) for img in os.listdir(img_dir) if 
img.endswith('.jpg')]

# Shuffle images to ensure randomness
random.shuffle(img_files)


# Function to clear the directory of all files
def clear_directory(directory):
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        if os.path.isfile(file_path):
            os.remove(file_path)
        else:
            os.path.isdir(file_path)
            shutil.rmtree(file_path)


clear_directory(val_dir)

# Split into training (80%) and validation (20%) sets
split_index = int(len(img_files) * 0.8)
train_files = img_files[:split_index]
valid_files = img_files[split_index:]

# Copy validation images to validation directory
for img in valid_files:
    shutil.copy(img, val_dir)

# Write train.txt with images to be used in training
with open(train_file, 'w') as f:
    for item in train_files:
        f.write(f"{item}n")

# Write valid.txt with images to be used in validation
with open(valid_file, 'w') as f:
    for item in valid_files:
        f.write(f"{item}n")

print(f"TrainTestSplit completed. {len(train_files)} training images and {len(valid_files)} 
validation images.")


# Check if val_dir contains images
def check_images(directory):
    if not os.path.exists(directory):
        print(f"Directory {directory} does not exist.")
        return

    files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
    if len(files) == 0:
        print(f"No images found in {directory}.")
    else:
        print(f"Found {len(files)} images in {directory}.")


# Check contents of valid.txt
def check_valid_file(file):
    if not os.path.exists(file):
        print(f"File {file} does not exist.")
        return

    with open(file, 'r') as f:
        lines = f.readlines()
        if len(lines) == 0:
        print(f"No entries found in {file}.")
    else:
        print(f"Found {len(lines)} entries in {file}.")


check_images(val_dir)
check_valid_file(valid_file)

# Define a transform
transform = transforms.Compose([
    transforms.Resize((640, 640)),
    transforms.ToTensor(),
])


# Load and transform images
def load_and_transform_image(image_path):
    try:
        image = Image.open(image_path).convert('RGB')
        image = transform(image)
        return image
    except Exception as e:
        print(f"Error loading image {image_path}: {e}")
        return None


# Example usage
image_paths = [line.strip() for line in 
open(r"locationdatavalid.txt")]

failed_count = 0
processed_count = 0

# Process each image
for image_path in image_paths:
    img_tensor = load_and_transform_image(image_path)
    if img_tensor is None:
        failed_count += 1
    else:
        processed_count += 1


# Print summary
print(f"Total images processed: {processed_count}")
print(f"Total images failed: {failed_count}")

training.py looks like:

from ultralytics import YOLO


def main():
    model = YOLO('yolov5mu.pt')

model.train(
    data=r'locationdatadata.yaml',
    epochs=50,
    imgsz=512,
    batch=16,
    device='cuda'
)


if __name__ == '__main__':
    main()

Where am I going wrong ?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật