Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

YOLOv5 Classification Model Training Metrics - II / Yolov5 Classify with torch.load() #13108

Open
1 task done
pdlje82 opened this issue Jun 19, 2024 · 6 comments
Open
1 task done
Labels
question Further information is requested

Comments

@pdlje82
Copy link

pdlje82 commented Jun 19, 2024

Search before asking

Question

I am trying to set up a some yolov5 classification performance test metrics, using the yolov5 repo tagged v7.

coming from #11509 -> I used the code given by @glenn-jocher in the code in 11509 to write up this:

import os
import torch
import logging
from pathlib import Path
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

logger = logging.getLogger(__name__)

class ModelTest:
    def __init__(self, data_path, imgsz, batch_size, test_model_path):
        self.data_path = Path(data_path)
        self.imgsz = imgsz
        self.batch_size = batch_size
        self.test_model_path = test_model_path
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.model = None
        self.class_names = None

    def load_model(self):
        checkpoint = torch.load(self.test_model_path, map_location=self.device)
        self.model = checkpoint['model']
        self.model.eval()
        self.model.to(self.device)
        self.model = self.model.float()  # convert to full precision

    def load_data(self):
        # Load data
        transform = transforms.Compose([
            transforms.Resize((self.imgsz, self.imgsz)),
            transforms.ToTensor(),
        ])
        dataset = datasets.ImageFolder(root=self.data_path / 'test', transform=transform)
        val_loader = DataLoader(dataset, batch_size=self.batch_size, shuffle=False)
        self.class_names = dataset.classes
        return val_loader

    def test_model(self):
        val_loader = self.load_data()
        y_true = []
        y_pred = []

        with torch.no_grad():
            for idx, (batch, labels) in enumerate(val_loader):
                batch = batch.to(self.device)
                labels = labels.to(self.device)
                outputs = self.model(batch)
                _, predicted = torch.max(outputs.data, 1)
                # here comes the metrics calculation
                ...

tester = ModelTest(...)
tester.load_model()
tester.test_model()

during model test it turned out that while my labels tensor is
tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], device='cuda:0')

my predicted tensor yields
indices=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], device='cuda:0'))

This looks as the model predicted only class 0, while it should have predicted 50% class 0 and 50% class 1. In the beginning I thought the model wasn't trained properly, but then I used the 'classify/val.py' code from the yolov5 repo to test my model and got

Fusing layers... 
Model summary: 166 layers, 11668754 parameters, 0 gradients, 30.6 GFLOPs
testing: 100%|██████████| 1/1 00:00
                   Class      Images    top1_acc    top5_acc
                     all          50           1           1
                 class 0          25           1           1
                 class 1          25           1           1

With the accuracies being 1, the model must work correctly. So my code has a problem either in

  • loading the model
  • loading the data
  • something else

Does somebody have a clue and could point out what the problem might be?
Thanks in advance!

Additional

No response

@pdlje82 pdlje82 added the question Further information is requested label Jun 19, 2024
Copy link
Contributor

👋 Hello @pdlje82, thank you for your interest in YOLOv5 🚀! Please visit our ⭐️ Tutorials to get started, where you can find quickstart guides for simple tasks like Custom Data Training all the way to advanced concepts like Hyperparameter Evolution.

If this is a 🐛 Bug Report, please provide a minimum reproducible example to help us debug it.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset image examples and training logs, and verify you are following our Tips for Best Training Results.

Requirements

Python>=3.8.0 with all requirements.txt installed including PyTorch>=1.8. To get started:

git clone https://github.com/ultralytics/yolov5  # clone
cd yolov5
pip install -r requirements.txt  # install

Environments

YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):

Status

YOLOv5 CI

If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training, validation, inference, export and benchmarks on macOS, Windows, and Ubuntu every 24 hours and on every commit.

Introducing YOLOv8 🚀

We're excited to announce the launch of our latest state-of-the-art (SOTA) object detection model for 2023 - YOLOv8 🚀!

Designed to be fast, accurate, and easy to use, YOLOv8 is an ideal choice for a wide range of object detection, image segmentation and image classification tasks. With YOLOv8, you'll be able to quickly and accurately detect objects in real-time, streamline your workflows, and achieve new levels of accuracy in your projects.

Check out our YOLOv8 Docs for details and get started with:

pip install ultralytics

@pdlje82 pdlje82 changed the title YOLOv5 Classification Model Training Metrics - II YOLOv5 Classification Model Training Metrics - II / Yolov5 Classify with torch.load() Jun 19, 2024
@glenn-jocher
Copy link
Member

@pdlje82 hello,

Thank you for your detailed report and for sharing your code. It’s great to see your proactive approach in diagnosing the issue. Let's work through this together.

Firstly, to ensure we can effectively reproduce and investigate the issue, could you please confirm that you are using the latest versions of torch and the YOLOv5 repository? If not, I recommend upgrading your packages and trying again. You can update YOLOv5 with the following commands:

git pull
pip install -U -r requirements.txt

Regarding your code, it looks well-structured, but there are a few areas we can investigate further:

  1. Model Loading: Ensure that the model is loaded correctly and that it matches the architecture expected by the checkpoint. Sometimes, discrepancies in model architecture can lead to unexpected behavior.

  2. Data Loading: Verify that the data is being loaded correctly and that the transformations applied are appropriate for your model.

  3. Inference and Metrics Calculation: Ensure that the inference logic and metrics calculation are correctly implemented.

Here’s a slightly modified version of your test_model method to include some additional checks and logging:

def test_model(self):
    val_loader = self.load_data()
    y_true = []
    y_pred = []

    with torch.no_grad():
        for idx, (batch, labels) in enumerate(val_loader):
            batch = batch.to(self.device)
            labels = labels.to(self.device)
            outputs = self.model(batch)
            _, predicted = torch.max(outputs.data, 1)
            
            # Log the outputs for debugging
            logger.info(f"Batch {idx}: Outputs: {outputs}, Predicted: {predicted}, Labels: {labels}")
            
            y_true.extend(labels.cpu().numpy())
            y_pred.extend(predicted.cpu().numpy())

    # Calculate metrics here
    # For example, accuracy:
    accuracy = sum(np.array(y_true) == np.array(y_pred)) / len(y_true)
    logger.info(f"Accuracy: {accuracy}")

    return accuracy

Additionally, please ensure that your model is in evaluation mode (self.model.eval()) and that the data transformations are consistent with those used during training.

If the issue persists, could you provide a minimum reproducible example, including a small subset of your dataset, so we can further investigate? You can refer to our guidelines on creating a minimum reproducible example here: Minimum Reproducible Example.

Thank you for your cooperation, and I look forward to your response.

@pdlje82
Copy link
Author

pdlje82 commented Jun 20, 2024

Hi @glenn-jocher,

thanks a lot for your quick answer.

From my code example follows that only the weights.pt file was used from yolov5, the rest is torch-only. Why would upgrading yolov5 make any difference? Or should I retrain the model with the upgraded yolov5 version? The training was done in v7 (tag)

@glenn-jocher
Copy link
Member

Hello @pdlje82,

Thank you for your follow-up and for providing additional context regarding your setup.

Given that your training was done using YOLOv5 v7 and you're now encountering issues during inference with a torch-only implementation, it's crucial to ensure compatibility between the model weights and the inference code. While upgrading YOLOv5 might not directly impact your current torch-only inference code, it can help ensure that any potential bugs or improvements in the model architecture and weight handling are addressed.

Here are a few steps to help diagnose and resolve the issue:

  1. Verify Model Compatibility: Ensure that the model architecture in your torch-only code matches exactly with the one used during training. Any discrepancies can lead to unexpected behavior.

  2. Upgrade YOLOv5: Although your inference code is torch-only, upgrading YOLOv5 ensures that any improvements or bug fixes in the model architecture are included. You can upgrade YOLOv5 with:

    git pull
    pip install -U -r requirements.txt
  3. Re-evaluate with YOLOv5 Tools: To isolate the issue, you might want to re-evaluate your model using the built-in YOLOv5 tools (e.g., classify/val.py). This can help confirm whether the issue lies within the model weights or the torch-only implementation.

  4. Provide a Minimum Reproducible Example: If the issue persists, please provide a minimum reproducible example, including a small subset of your dataset and the exact steps to reproduce the issue. This will help us investigate further. You can refer to our guidelines here: Minimum Reproducible Example.

Here's a snippet to ensure your model is correctly loaded and evaluated:

def test_model(self):
    val_loader = self.load_data()
    y_true = []
    y_pred = []

    with torch.no_grad():
        for idx, (batch, labels) in enumerate(val_loader):
            batch = batch.to(self.device)
            labels = labels.to(self.device)
            outputs = self.model(batch)
            _, predicted = torch.max(outputs.data, 1)
            
            # Log the outputs for debugging
            logger.info(f"Batch {idx}: Outputs: {outputs}, Predicted: {predicted}, Labels: {labels}")
            
            y_true.extend(labels.cpu().numpy())
            y_pred.extend(predicted.cpu().numpy())

    # Calculate metrics here
    # For example, accuracy:
    accuracy = sum(np.array(y_true) == np.array(y_pred)) / len(y_true)
    logger.info(f"Accuracy: {accuracy}")

    return accuracy

By following these steps, we can better understand the root cause of the issue and work towards a solution. Thank you for your cooperation, and I look forward to your response.

@pdlje82
Copy link
Author

pdlje82 commented Jun 21, 2024

Dear @glenn-jocher GPT,

the solution to my problem was that the data transform is incorrect:

def load_data(self):
    # Load data
    transform = transforms.Compose([
        transforms.Resize((self.imgsz, self.imgsz)),
        transforms.ToTensor(),

In order to do work, Yolov5 needs the images in a form normalized to a certain mean and certain std dev. The simplest way to achieve the correct transformation is to use the yolov5 dataloader, instead of using the torch loader directly

sys.path.append('/.../yolov5/')
from utils.dataloaders import create_classification_dataloader

dataloader = create_classification_dataloader(path=self.data_path / 'test',
                                              imgsz=self.imgsz,
                                              batch_size=self.batch_size,
                                              augment=False
                                             )

@glenn-jocher
Copy link
Member

Hello @pdlje82,

Thank you for sharing the solution to your issue! It's great to hear that you were able to identify the problem with the data transformation and resolve it by using the YOLOv5 dataloader.

Indeed, proper normalization is crucial for achieving accurate results with YOLOv5 models. Using the create_classification_dataloader function from the YOLOv5 repository ensures that the images are preprocessed correctly, matching the expectations of the model.

For anyone else encountering similar issues, here's a quick summary of the solution:

Issue:

The data transformation was not normalizing the images correctly, leading to inaccurate predictions.

Solution:

Use the YOLOv5 dataloader to ensure proper normalization:

import sys
sys.path.append('/path/to/yolov5/')
from utils.dataloaders import create_classification_dataloader

def load_data(self):
    dataloader = create_classification_dataloader(
        path=self.data_path / 'test',
        imgsz=self.imgsz,
        batch_size=self.batch_size,
        augment=False
    )
    return dataloader

This approach ensures that the images are normalized to the mean and standard deviation expected by the YOLOv5 model, leading to accurate predictions.

If you encounter any further issues or have additional questions, please feel free to ask. The YOLOv5 community and the Ultralytics team are always here to help! 😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants