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 ?