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

Error loading self trained model #12916

Closed
1 task done
handalele opened this issue Apr 13, 2024 · 5 comments
Closed
1 task done

Error loading self trained model #12916

handalele opened this issue Apr 13, 2024 · 5 comments
Labels
question Further information is requested Stale

Comments

@handalele
Copy link

Search before asking

Question

I encountered an error while using my own trained model for real-time detection and rendering the detection results to the front-end
Here is my code and error message
model1 = YOLO('runs/train/exp4/weights/best.pt')

def process_frame(frame):
res = model1(frame) # predict on an image
res_plotted = res[0].plot()
return res_plotted

def gen(camera,fps=30):
delay = 1/fps
while True:
success, image = camera.read()
if not success:
break
ret, jpeg = cv2.imencode('.jpg', image)
frame = jpeg.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
time.sleep(delay)

def generate_frames(file):
cap = cv2.VideoCapture(file)

while True:
    ret, frame = cap.read()

    if not ret:
        break
    processed_frame = process_frame(frame)
    ret, buffer = cv2.imencode('.jpg', processed_frame)
    frame_data = buffer.tobytes()
    yield (b'--frame\r\n'
           b'Content-Type: image/jpeg\r\n\r\n' + frame_data + b'\r\n')

File "E:\Anaconda3\envs\flaskdemo\lib\site-packages\werkzeug\wsgi.py", line 289, in next
return self._next()
File "E:\Anaconda3\envs\flaskdemo\lib\site-packages\werkzeug\wrappers\response.py", line 32, in _iter_encoded
for item in iterable:
File "C:\Users\200391\Desktop\ProjectStudy\demouse\yolov.py", line 56, in generate_frames
processed_frame = process_frame(frame)
File "C:\Users\200391\Desktop\ProjectStudy\demouse\yolov.py", line 30, in process_frame
res = model1(frame) # predict on an image
File "E:\Anaconda3\envs\flaskdemo\lib\site-packages\ultralytics\engine\model.py", line 176, in call
return self.predict(source, stream, **kwargs)
File "E:\Anaconda3\envs\flaskdemo\lib\site-packages\ultralytics\engine\model.py", line 452, in predict
return self.predictor.predict_cli(source=source) if is_cli else self.predictor(source=source, stream=stream)
File "E:\Anaconda3\envs\flaskdemo\lib\site-packages\ultralytics\engine\predictor.py", line 168, in call
return list(self.stream_inference(source, model, *args, **kwargs)) # merge list of Result into one
File "E:\Anaconda3\envs\flaskdemo\lib\site-packages\torch\utils_contextlib.py", line 35, in generator_context
response = gen.send(None)
File "E:\Anaconda3\envs\flaskdemo\lib\site-packages\ultralytics\engine\predictor.py", line 268, in stream_inference
s[i] += self.write_results(i, Path(paths[i]), im, s)
File "E:\Anaconda3\envs\flaskdemo\lib\site-packages\ultralytics\engine\predictor.py", line 328, in write_results
string += result.verbose() + f"{result.speed['inference']:.1f}ms"
File "E:\Anaconda3\envs\flaskdemo\lib\site-packages\ultralytics\engine\results.py", line 328, in verbose
log_string += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, "
KeyError: 1275
demo

Additional

No response

@handalele handalele added the question Further information is requested label Apr 13, 2024
Copy link
Contributor

👋 Hello @handalele, 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

@glenn-jocher
Copy link
Member

Hey there! It seems like you're encountering a KeyError which typically indicates an issue with the class indices. From your error message, it seems like the model is attempting to access a class index (1275) that doesn't exist in the dataset's label set. This could happen if there's a mismatch between the classes your model was trained on and the classes defined in your code or inference setup.

To troubleshoot, I suggest:

  1. Double-check the number of classes your model was trained on and ensure it matches the configuration in your code where the model is loaded for inference.
  2. If you're utilizing a custom dataset, verify that the class labels align with your dataset's annotations.

This usually resolves the KeyError by ensuring consistency between your training and inference environments. If the issue persists, you might want to review your training setup and dataset. Let's keep improving together! 🚀

@handalele
Copy link
Author

I printed the type label and the detected type ID in the detection results, and found that the detection ID
if boxes:
print(self.names)
for c in boxes.cls.unique():
# 无
print(int(c))
n = (boxes.cls == c).sum() # detections per class
log_string += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, "
return log_string
This is the message from the console output, the detected class id is too large. Why does this problem not occur when I reason with pictures or videos
{0: 'people', 1: 'bio', 2: 'plastic'}
1515
KeyError: 1515

{0: 'people', 1: 'bio', 2: 'plastic'}
875
KeyError: 875

{0: 'people', 1: 'bio', 2: 'plastic'}
1115
KeyError: 1115

{0: 'people', 1: 'bio', 2: 'plastic'}
1115
KeyError: 1115

{0: 'people', 1: 'bio', 2: 'plastic'}
1435
KeyError: 1435

@glenn-jocher
Copy link
Member

Hey there! It looks like the class IDs detected during inference are way beyond the expected range based on your class names. This unusual behavior could be due to a mismatch in model weights used during inference or a misconfiguration in the model's definition. Here are a couple of things to check:

  • Ensure that the model loaded for inference is indeed the one trained on your dataset with the correct number of classes.
  • Confirm that there's no data corruption with the model weights file.

It's unusual for this issue to occur with images or videos but not elsewhere. This hints that the anomaly may lie in how the data is being processed or fed into the model during the instance where the error occurs. Double-check your data preprocessing steps to ensure consistency across different data types (images, videos, real-time feeds, etc.).

Let's aim for seamless model inference! 🌟

Copy link
Contributor

👋 Hello there! We wanted to give you a friendly reminder that this issue has not had any recent activity and may be closed soon, but don't worry - you can always reopen it if needed. If you still have any questions or concerns, please feel free to let us know how we can help.

For additional resources and information, please see the links below:

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 YOLO 🚀 and Vision AI ⭐

@github-actions github-actions bot added the Stale label May 15, 2024
@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale May 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested Stale
Projects
None yet
Development

No branches or pull requests

2 participants