Closed p9anand closed 3 years ago
Hello @p9anand, 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.
Python 3.8 or later with all requirements.txt dependencies installed, including torch>=1.7
. To install run:
$ pip install -r requirements.txt
YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):
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.
I think that
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', classes=6)
model.load_state_dict(torch.load('...')['model'].state_dict())
model = model.fuse().autoshape()
would be a method?
I tried that but getting following error:
custom weights are loaded successfully and Autoshape was also loaded successfully.
It seems that this line
didn't work as expected, could you please upload your model so that I could debug this problem (sorry I didn't train any custom model)
Hi @p9anand
I did a quick fixes as below:
import torch
from PIL import Image
def copy_attr(a, b, include=(), exclude=()):
# Copy attributes from b to a, options to only include [...] and to exclude [...]
for k, v in b.__dict__.items():
if (len(include) and k not in include) or k.startswith('_') or k in exclude:
continue
else:
setattr(a, k, v)
# my network so slow that I can't download your model above successfully :(
# so I just use ultralytics's pretrained model here
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=False, classes=80)
checkpoint_ = torch.load('../yolov5-ultralytics/weights/yolov5s.pt')['model']
model.load_state_dict(checkpoint_.state_dict())
copy_attr(model, checkpoint_, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=())
model = model.fuse().autoshape()
img = Image.open('./notebooks/assets/zidane.jpg')
output = model(img)
print(f'prediction: {output.pred}')
Hope it can help you
It worked. Thanks for the help!!
@zhiqwang would you be able to submit a PR with your updates to copy_attr()? Thanks!!
Hi @glenn-jocher It's my pleasure to contribute this awesome repo.
The copy_attr()
function is actually copied from
This issue only occur when somebody are loading the trained model with torch.hub
and setting pretrained
to be False
. It's normal using
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True, classes=80)
And there is a tutorial of the usage with torch.hub
in #36, and you comment that
Load a State Dict
To load a custom state dict, first load a PyTorch Hub model of the same kind with the same number of classes:
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', classes=10) model.load_state_dict(torch.load('yolov5s_10cls.pt')['model'].state_dict())
So maybe it would be better to put this directions of the usage of copy_attr()
there?
@zhiqwang ah yes, I understand. We probably want to make changes in two places:
@p9anand @zhiqwang I've updated the PyTorch Hub tutorial as follows and implemented a default class names list in PR #1608.
@p9anand can you confirm that the new tutorial directions work for you? They are here. I think names is the only attribute that was missing before.
To load a custom state dict, first load a PyTorch Hub model of the same kind with the same number of classes:
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', classes=10) # create model
ckpt = torch.load('yolov5s_10cls.pt')['model'] # load checkpoint
model.load_state_dict(ckpt.state_dict())
model.names = ckpt.names # transfer class names (recommended)
@zhiqwang ah also, the .autoshape() method contains a .fuse() call inside it, so you can simply do model.autoshape().
Hi @glenn-jocher , Got it, it's more clean now.
@glenn-jocher : It worked. Thanks for the help!!
It didnt work in my case here is the code I am using for custom model
@Sagor-Saha see pytorch hub tutorial for correct loading of custom models.
I am trying to integrate the custom trained model into a django project. The command for custom model in [https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading] does not work when I run the model from django. But it definitely works without django. .
@Sagor-Saha those error messages are simply due to your environment not meeting the requirements in requirements.txt.
It appears you may have environment problems. Please ensure you meet all dependency requirements if you are attempting to run YOLOv5 locally. If in doubt, create a new virtual Python 3.8 environment, clone the latest repo (code changes daily), and pip install -r requirements.txt
again. We also highly recommend using one of our verified environments below.
Python 3.8 or later with all requirements.txt dependencies installed, including torch>=1.7
. To install run:
$ pip install -r requirements.txt
YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):
If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are passing. These tests evaluate proper operation of basic YOLOv5 functionality, including training (train.py), testing (test.py), inference (detect.py) and export (export.py) on MacOS, Windows, and Ubuntu.
i Run that same program i face this error
AttributeError: 'AutoShape' object has no attribute 'fuse'
@DineshKumar9412 π hi, thanks for letting us know about this problem with YOLOv5 π. We've created a few short guidelines below to help users provide what we need in order to get started investigating a possible problem.
When asking a question, people will be better able to provide help if you provide code that they can easily understand and use to reproduce the problem. This is referred to by community members as creating a minimum reproducible example. Your code that reproduces the problem should be:
In addition to the above requirements, for Ultralytics to provide assistance your code should be:
git pull
or git clone
a new copy to ensure your problem has not already been resolved by previous commits.If you believe your problem meets all of the above criteria, please close this issue and raise a new one using the π Bug Report template and providing a minimum reproducible example to help us better understand and diagnose your problem.
Thank you! π
model = torch.hub.load('ultralytics/yolov5', 'custom', path='path/to/best.pt') # default model = torch.hub.load('path/to/yolov5', 'custom', path='path/to/best.pt', source='local') # local repo
@zhiqwang @glenn-jocher thanks for the detailed explanation but wanted to know that model = torch.hub.load('ultralytics/yolov5', 'custom', path='path/to/best.pt') # default yolov5 architecture trained on COCO data and model = torch.hub.load('path/to/yolov5', 'custom', path='path/to/best.pt', source='local') # local repo with architecture changes ie adding mulittaksking / removed few layers / instead gave path to yolov5m , does still torch.hub will be alble to load the custom model.???
Thank you so much
On Tue, Aug 10, 2021, 11:02 PM abhigoku10 @.***> wrote:
@zhiqwang https://github.com/zhiqwang @glenn-jocher https://github.com/glenn-jocher thanks for the detailed explanation but wanted to know that model = torch.hub.load('ultralytics/yolov5', 'custom', path='path/to/ best.pt') # default yolov5 architecture trained on COCO data and model = torch.hub.load('path/to/yolov5', 'custom', path='path/to/best.pt', source='local') # local repo with architecture changes ie adding mulittaksking / removed few layers / instead gave path to yolov5m , does still torch.hub will be alble to load the custom model.???
β You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/ultralytics/yolov5/issues/1605#issuecomment-896178580, or unsubscribe https://github.com/notifications/unsubscribe-auth/ATZ55VEW2BYGM7MF7PHKH23T4FPDZANCNFSM4UOKYJLA . Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&utm_campaign=notification-email .
Do we need to redefine the number of classes when we load a custom weight by pytorch ? Because my new weights have only 1 class
@littlerain2310 no
Thanks @glenn-jocher. One more question:
@littlerain2310 π hi, thanks for letting us know about this problem with YOLOv5 π. We've created a few short guidelines below to help users provide what we need in order to get started investigating a possible problem.
When asking a question, people will be better able to provide help if you provide code that they can easily understand and use to reproduce the problem. This is referred to by community members as creating a minimum reproducible example. Your code that reproduces the problem should be:
In addition to the above requirements, for Ultralytics to provide assistance your code should be:
git pull
or git clone
a new copy to ensure your problem has not already been resolved by previous commits.If you believe your problem meets all of the above criteria, please close this issue and raise a new one using the π Bug Report template and providing a minimum reproducible example to help us better understand and diagnose your problem.
Thank you! π
@glenn-jocher thanks for your reply!
For my custom model, after a lot of trial and error i tried this way and it worked!
model = torch.hub.load( "ultralytics/yolov5", "custom", path = './tests/last.pt', force_reload=True, autoshape=True ) # force_reload = recache latest code
@HasibGit yes
# Model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # or yolov5m, ... yolov5x6 etc. official models
model = torch.hub.load('ultralytics/yolov5', 'custom', path='path/to/best.pt') # custom model
can some one help me ?
@Barry04 your pytorch is likely out of date. See https://pytorch.org/get-started/locally/
Hii, I have been struggling a lot to load a custom model as here - https://github.com/ultralytics/yolov5/releases/download/v6.0/yolov5m_Objects365.pt to my main.py file using torch.hub.load but its been failing for the last two days now. I have tried multiple ways, but I cant seem to get it working. Could someone please help me with it?
@gd1925 π Hello! Thanks for asking about handling inference results. YOLOv5 π PyTorch Hub models allow for simple model loading and inference in a pure python environment without using detect.py
.
This example loads a pretrained YOLOv5s model from PyTorch Hub as model
and passes an image for inference. 'yolov5s'
is the YOLOv5 'small' model. For details on all available models please see the README. Custom models can also be loaded, including custom trained PyTorch models and their exported variants, i.e. ONNX, TensorRT, TensorFlow, OpenVINO YOLOv5 models.
import torch
# Model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # yolov5n - yolov5x6 official model
# 'custom', 'path/to/best.pt') # custom model
# Images
im = 'https://ultralytics.com/images/zidane.jpg' # or file, Path, URL, PIL, OpenCV, numpy, list
# Inference
results = model(im)
# Results
results.print() # or .show(), .save(), .crop(), .pandas(), etc.
results.xyxy[0] # im predictions (tensor)
results.pandas().xyxy[0] # im predictions (pandas)
# xmin ymin xmax ymax confidence class name
# 0 749.50 43.50 1148.0 704.5 0.874023 0 person
# 2 114.75 195.75 1095.0 708.0 0.624512 0 person
# 3 986.00 304.00 1028.0 420.0 0.286865 27 tie
results.pandas().xyxy[0].value_counts('name') # class counts (pandas)
# person 2
# tie 1
See YOLOv5 PyTorch Hub Tutorial for details.
Good luck π and let us know if you have any other questions!
Hi @glenn-jocher, Thank you so much for your reply and the explanation. Its working on my side now!!
Hi @glenn-jocher, my question is in reference to the integrating the above yolov5 with CVAT toolkit. I have added the following lines of code to my main.py but I am not sure if it is correct. Could you please take a look and let me know if its the correct way to load the model?
I am not getting any error, but on running deploy_gpu.sh, it stops at building image ...
Could you please help me? Thank you in advance..
YOLOv5 PyTorch Hub models automatically load on GPU if available, so your logic is redundant.
Also I think you might need cuda:0
rather than cuda
if you're going to manually attempt device logic.
Hi @glenn-jocher, Thank you so much for your reply. I will try it out.
@gd1925 you're welcome! π Don't hesitate to reach out if you have any more questions or run into any issues. Good luck with your implementation!
βQuestion
Loading model custom trained weights using Pytorch hub
Additional context
Hi,
I'm trying to load my custom model weights using torch hub. As you can see in the image. In one case It was able to load it and second case it failed.
But in the other case i got following error.
Lets say, if i choose first method to load the custom weights. how can i make inference directly of a PIL image. Because when i was trying to do that i got following error.