ultralytics / yolov5

YOLOv5 πŸš€ in PyTorch > ONNX > CoreML > TFLite
https://docs.ultralytics.com
GNU Affero General Public License v3.0
50.57k stars 16.31k forks source link

How to finetune only one class? #3913

Closed Stephenfang51 closed 3 years ago

Stephenfang51 commented 3 years ago

❔Question

Thanks for your excellent work in advanced ! what if I want to finetune only one class of my own dataset? if I have[0,1,2,3] classes in my dataset, I want to add more data for "0" class, and do not want to train other my whole data again and also I wish the model output 4 classes. Any advice ?

Thanks so much !

Additional context

github-actions[bot] commented 3 years ago

πŸ‘‹ Hello @Stephenfang51, 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 screenshots and minimum viable code to reproduce your issue, otherwise we can not help you.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset images, training logs, screenshots, and a public link to online W&B logging if available.

For business inquiries or professional support requests please visit https://www.ultralytics.com or email Glenn Jocher at glenn.jocher@ultralytics.com.

Requirements

Python 3.8 or later with all requirements.txt dependencies installed, including torch>=1.7. To install run:

$ pip install -r requirements.txt

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

CI CPU testing

If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training (train.py), testing (test.py), inference (detect.py) and export (export.py) on MacOS, Windows, and Ubuntu every 24 hours and on every commit.

glenn-jocher commented 3 years ago

@Stephenfang51 just update your dataset as you see fit and retrain on it.

github-actions[bot] commented 3 years ago

πŸ‘‹ Hello, this issue has been automatically marked as stale because it has not had recent activity. Please note it will be closed if no further activity occurs.

Access additional YOLOv5 πŸš€ resources:

Access additional Ultralytics ⚑ resources:

Feel free to inform us of any other issues you discover or feature requests that come to mind in the future. Pull Requests (PRs) are also always welcomed!

Thank you for your contributions to YOLOv5 πŸš€ and Vision AI ⭐!

kelectro commented 2 years ago

I am not sure what you mean @glenn-jocher. Just update the specific class and retrain using the whole dataset?

glenn-jocher commented 2 years ago

@kelectro what's your question exactly?

kelectro commented 2 years ago

I have a trained model in 4 classes and works fine in 3/4. I would like to know if its possible to tune only one specific class instead of retraining the model on the whole dataset.

glenn-jocher commented 2 years ago

@kelectro πŸ‘‹ Hello! Thanks for asking about improving YOLOv5 πŸš€ training results. If you have a poorly performing class the easiest method to improve it is to collect more data for it.

[Most of the time good results can be obtained with no changes to the models or training settings, provided your dataset is sufficiently large and well labelled. If at first you don't get good results, there are steps you might be able to take to improve, but we always recommend users first train with all default settings before considering any changes. This helps establish a performance baseline and spot areas for improvement.

If you have questions about your training results we recommend you provide the maximum amount of information possible if you expect a helpful response, including results plots (train losses, val losses, P, R, mAP), PR curve, confusion matrix, training mosaics, test results and dataset statistics images such as labels.png. All of these are located in your project/name directory, typically yolov5/runs/train/exp.

We've put together a full guide for users looking to get the best results on their YOLOv5 trainings below.

Dataset

COCO Analysis

Model Selection

Larger models like YOLOv5x and YOLOv5x6 will produce better results in nearly all cases, but have more parameters, require more CUDA memory to train, and are slower to run. For mobile deployments we recommend YOLOv5s/m, for cloud deployments we recommend YOLOv5l/x. See our README table for a full comparison of all models.

YOLOv5 Models

Training Settings

Before modifying anything, first train with default settings to establish a performance baseline. A full list of train.py settings can be found in the train.py argparser.

Further Reading

If you'd like to know more a good place to start is Karpathy's 'Recipe for Training Neural Networks', which has great ideas for training that apply broadly across all ML domains: http://karpathy.github.io/2019/04/25/recipe/](https://github.com/ultralytics/yolov5/issues/2844#issuecomment-851338384)

kelectro commented 2 years ago

Thank you for the very usefull guide!

TonyTran86 commented 2 years ago

I have a trained model in 4 classes and works fine in 3/4. I would like to know if its possible to tune only one specific class instead of retraining the model on the whole dataset.

As I understand in case the other classes not labeled when they existed in the image of dataset then the result will read as "negative cases".

visionKinger commented 1 year ago

❔Question

Thanks for your excellent work in advanced ! what if I want to finetune only one class of my own dataset? if I have[0,1,2,3] classes in my dataset, I want to add more data for "0" class, and do not want to train other my whole data again and also I wish the model output 4 classes. Any advice ?

Thanks so much !

Additional context

In my opinion, you can freeze the layers but the classification layer. In the classification layers, you should use Tensor.data.requiresgrad=False, in case not to learn other classes. And after calculating the gradient, you should clear the grad

glenn-jocher commented 1 year ago

@visionKinger hi there,

To fine-tune only one class of your own dataset without retraining the entire model, you can follow these steps:

  1. Freeze the layers of the pre-trained model except for the classification layer for the desired class.

  2. Set the requires_grad property of the parameters in the frozen layers to False. This ensures that the gradients are not computed for those layers during the backward pass, preventing them from being updated during training.

  3. During the forward pass, calculate the gradient only for the classification layer of the desired class. You can set requires_grad to True for the classification layer of the desired class, allowing it to be updated during training.

  4. After calculating the gradient, clear the gradients for the frozen layers. This prevents them from being accumulated and interfering with the optimization process.

By following these steps, you can focus on fine-tuning only the desired class without retraining the entire model, and the model will continue to output predictions for all four classes.

I hope this advice helps! Let me know if you have any further questions.

Best regards,

ggloss commented 8 months ago

@visionKinger hi there,

To fine-tune only one class of your own dataset without retraining the entire model, you can follow these steps:

  1. Freeze the layers of the pre-trained model except for the classification layer for the desired class.
  2. Set the requires_grad property of the parameters in the frozen layers to False. This ensures that the gradients are not computed for those layers during the backward pass, preventing them from being updated during training.
  3. During the forward pass, calculate the gradient only for the classification layer of the desired class. You can set requires_grad to True for the classification layer of the desired class, allowing it to be updated during training.
  4. After calculating the gradient, clear the gradients for the frozen layers. This prevents them from being accumulated and interfering with the optimization process.

By following these steps, you can focus on fine-tuning only the desired class without retraining the entire model, and the model will continue to output predictions for all four classes.

I hope this advice helps! Let me know if you have any further questions.

Best regards,

Hi @glenn-jocher, could you please recommend a guide with code to follow these steps? I've trained a YOLO model with the train.py for 10 classes and I just want to fine-tune the model for 2 classes on 10 of these classes .

glenn-jocher commented 8 months ago

Hi @ggloss,

Fine-tuning specific classes in YOLOv5 is not a standard feature, and the architecture does not support freezing individual classification layers for each class as it uses a single output layer for all classes. However, you can approach this by training on a dataset that includes only the new images for the class you wish to improve, while keeping the other classes in the dataset to prevent catastrophic forgetting.

Here's a general approach:

  1. Prepare a new dataset where the class you want to fine-tune is well-represented, and include a smaller number of examples from the other classes.
  2. Load your pre-trained weights with the --weights flag.
  3. Train the model on the new dataset using the train.py script. The model will update based on the new data, which should improve performance on the class of interest while maintaining knowledge of the other classes.

Remember to monitor the performance on a validation set that represents all classes to ensure that the model does not forget the other classes.

For specific code guidance, please refer to the Ultralytics documentation and examples, as providing code is beyond the scope of this platform.

ggloss commented 8 months ago

@glenn-jocher many thanks for your advice! I'll try to reproduce the presented approach.

glenn-jocher commented 8 months ago

You're welcome, @ggloss! I'm glad to hear you found the advice helpful. If you encounter any issues or have further questions as you proceed, feel free to reach out. Best of luck with your fine-tuning efforts! Happy training! πŸš€πŸ˜Š