Python-Verwendung
Diese Anleitung zeigt dir, wie du Ultralytics YOLO in deine Python-Projekte für Objekterkennung, Instanzsegmentierung, semantische Segmentierung, Tiefenschätzung, Klassifizierung, Pose-Schätzung und Erkennung mit gedrehten Begrenzungsrahmen integrierst. Du lernst, wie du vortrainierte Modelle lädst und verwendest, neue Modelle trainierst und Vorhersagen für Bilder erstellst. Mit der Python-Schnittstelle kannst du YOLO mit nur wenigen Codezeilen in ein Projekt einbinden.
Ansehen: Ultralytics YOLO meistern: Python
Nutzer können beispielsweise ein Modell laden, es trainieren, seine Leistung auf einem Validierungsdatensatz bewerten und es mit nur wenigen Codezeilen sogar in das ONNX-Format exportieren.
from ultralytics import YOLO
# Erstelle ein neues YOLO-Modell von Grund auf
model = YOLO("yolo26n.yaml")
# Lade ein vortrainiertes YOLO-Modell (für das Training empfohlen)
model = YOLO("yolo26n.pt")
# Trainiere das Modell 3 Epochen lang mit dem Datensatz 'coco8.yaml'
results = model.train(data="coco8.yaml", epochs=3)
# Werte die Leistung des Modells auf dem Validierungsdatensatz aus
results = model.val()
# Führe mit dem Modell eine Objekterkennung auf einem Bild aus
results = model("https://ultralytics.com/images/bus.jpg")
# Exportiere das Modell in das ONNX-Format
success = model.export(format="onnx")Trainieren#
Der Trainingsmodus dient dazu, ein YOLO-Modell mit einem benutzerdefinierten Datensatz zu trainieren. Dabei wird das Modell anhand des angegebenen Datensatzes und der Hyperparameter trainiert. Beim Training werden die Modellparameter so optimiert, dass das Modell Klassen und Positionen von Objekten in einem Bild präzise vorhersagen kann.
from ultralytics import YOLO
model = YOLO("yolo26n.pt") # Beliebigen Modelltyp übergeben
results = model.train(epochs=5)Validieren#
Der Validierungsmodus dient zur Validierung eines trainierten YOLO-Modells. Dabei wird das Modell mit einem Validierungsdatensatz ausgewertet, um seine Genauigkeit und Generalisierungsleistung zu messen. Mit diesem Modus lassen sich die Hyperparameter des Modells anpassen, um seine Leistung zu verbessern.
from ultralytics import YOLO
# Ein YOLO-Modell laden
model = YOLO("yolo26n.yaml")
# Das Modell trainieren
model.train(data="coco8.yaml", epochs=5)
# Validierung anhand der Validierungsaufteilung des Trainingsdatensatzes
model.val()Vorhersagen#
Der Predict-Modus dient dazu, mit einem trainierten YOLO-Modell Vorhersagen für neue Bilder oder Videos zu erstellen. In diesem Modus wird das Modell aus einer Checkpoint-Datei geladen. Anschließend kann der Nutzer Bilder oder Videos zur Inferenz bereitstellen. Das Modell sagt die Klassen und Positionen der Objekte in den Eingabebildern oder -videos voraus.
import cv2
from PIL import Image
from ultralytics import YOLO
model = YOLO("model.pt")
# akzeptiert alle Formate – Bild/Verzeichnis/Path/URL/Video/PIL/ndarray. 0 für Webcam
results = model.predict(source="folder", show=True) # Vorhersagen anzeigen. Akzeptiert alle YOLO-Predict-Argumente
# from PIL
im1 = Image.open("bus.jpg")
results = model.predict(source=im1, save=True) # Visualisierte Bilder speichern
# aus ndarray
im2 = cv2.imread("bus.jpg")
results = model.predict(source=im2, save=True, save_txt=True) # Vorhersagen als Labels speichern
# aus einer Liste von PIL/ndarray
results = model.predict(source=[im1, im2])Exportieren#
Der Export-Modus dient dazu, ein YOLO-Modell in ein Format zu exportieren, das für die Bereitstellung verwendet werden kann. In diesem Modus wird das Modell in ein Format konvertiert, das von anderen Softwareanwendungen oder Hardwaregeräten verwendet werden kann. Dieser Modus ist nützlich, wenn das Modell in Produktionsumgebungen bereitgestellt wird.
Exportiere ein offizielles YOLO-Modell mit dynamischer Batch- und Bildgröße nach ONNX.
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
model.export(format="onnx", dynamic=True)Verfolgen#
Der Tracking-Modus dient dazu, Objekte mithilfe eines YOLO-Modells in Echtzeit zu verfolgen. In diesem Modus wird das Modell aus einer Checkpoint-Datei geladen und du kannst einen Live-Videostream bereitstellen, um Objekte in Echtzeit zu verfolgen. Dieser Modus eignet sich für Anwendungen wie Überwachungssysteme oder selbstfahrende Autos.
from ultralytics import YOLO
# Ein Modell laden
model = YOLO("yolo26n.pt") # Ein offizielles Erkennungsmodell laden
model = YOLO("yolo26n-seg.pt") # Ein offizielles Segmentierungsmodell laden
model = YOLO("path/to/best.pt") # Ein benutzerdefiniertes Modell laden
# Mit dem Modell verfolgen
results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True)
results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True, tracker="bytetrack.yaml")Benchmark#
Der Benchmarkmodus wird verwendet, um Geschwindigkeit und Genauigkeit verschiedener Exportformate für YOLO zu messen. Die Benchmarks liefern Informationen zur Größe des exportierten Formats, zur Aufgabenmetrik (mAP50-95 für Erkennung, Segmentierung, Pose und OBB, mIoU für semantische Segmentierung, δ1 für Tiefenschätzung oder accuracy_top1 für Klassifizierung) sowie zur Inferenzzeit in Millisekunden pro Bild bei verschiedenen Exportformaten wie ONNX, OpenVINO, TensorRT und anderen. Anhand dieser Informationen können Nutzer das optimale Exportformat für ihren jeweiligen Anwendungsfall und ihre Anforderungen an Geschwindigkeit und Genauigkeit auswählen.
Ein offizielles YOLO-Modell mit allen Exportformaten benchmarken.
from ultralytics.utils.benchmarks import benchmark
# Benchmark
benchmark(model="yolo26n.pt", data="coco8.yaml", imgsz=640, device=0)Trainer verwenden#
Die Modellklasse YOLO dient als übergeordnete Schnittstelle für Trainer-Klassen. Für jede YOLO-Aufgabe gibt es einen eigenen Trainer, der von BaseTrainer abgeleitet ist. Diese Architektur bietet mehr Flexibilität und Anpassungsmöglichkeiten für deine Workflows im maschinellen Lernen.
from ultralytics.models.yolo.detect import DetectionPredictor, DetectionTrainer, DetectionValidator
overrides = {"model": "yolo26n.pt", "data": "coco8.yaml", "epochs": 3}
# Trainer
trainer = DetectionTrainer(overrides=overrides)
trainer.train()
trained_model = trainer.best # Pfad zu best.pt
# Validator
validator = DetectionValidator(args={"data": "coco8.yaml"})
validator(model=trained_model)
# Predictor
predictor = DetectionPredictor(overrides={"model": trained_model})
predictor(source="https://ultralytics.com/images/bus.jpg")
# Einen unterbrochenen Trainingslauf am letzten Checkpoint fortsetzen
trainer = DetectionTrainer(overrides={"resume": "path/to/last.pt"})
trainer.train()Du kannst Trainer anpassen, damit sie benutzerdefinierte Aufgaben unterstützen oder Forschungs- und Entwicklungsideen umsetzen. Dank des modularen Designs von Ultralytics YOLO kannst du das Framework an deine speziellen Anforderungen anpassen – ganz gleich, ob du an einer neuen Aufgabe im Bereich Computer Vision arbeitest oder vorhandene Modelle per Fine-Tuning optimierst.
Häufig gestellte Fragen#
Ultralytics YOLO lässt sich ganz einfach in deine Python-Projekte integrieren. Du kannst ein vortrainiertes Modell laden oder ein neues Modell von Grund auf trainieren. So legst du los:
from ultralytics import YOLO # Ein vortrainiertes YOLO-Modell laden model = YOLO("yolo26n.pt") # Objekterkennung in einem Bild durchführen results = model("https://ultralytics.com/images/bus.jpg") # Die Ergebnisse visualisieren for result in results: result.show()Weitere ausführliche Beispiele findest du im Abschnitt Predict-Modus.
Ultralytics YOLO bietet sechs Modi für verschiedene Machine-Learning-Workflows:
- Trainieren: Ein Modell mit benutzerdefinierten Datensätzen trainieren.
- Validieren: Die Modellleistung anhand eines Validierungssatzes überprüfen.
- Vorhersagen: Vorhersagen für neue Bilder oder Videostreams erstellen.
- Exportieren: Modelle in verschiedene Formate wie ONNX und TensorRT exportieren.
- Verfolgen: Objekte in Videostreams in Echtzeit verfolgen.
- Benchmark: Die Modellleistung mit verschiedenen Konfigurationen benchmarken.
Jeder Modus deckt eine andere Phase der Modellentwicklung und -bereitstellung ab.
Um ein benutzerdefiniertes YOLO-Modell zu trainieren, gib deinen Datensatz und alle weiteren Hyperparameter an. Hier ein kurzes Beispiel:
from ultralytics import YOLO # Das YOLO-Modell laden model = YOLO("yolo26n.yaml") # Das Modell mit einem benutzerdefinierten Datensatz trainieren model.train(data="path/to/your/dataset.yaml", epochs=10)Mit der Funktion
exportlassen sich YOLO-Modelle ganz einfach in ein für die Bereitstellung geeignetes Format exportieren. Du kannst ein Modell zum Beispiel ins ONNX-Format exportieren:from ultralytics import YOLO # Das YOLO-Modell laden model = YOLO("yolo26n.pt") # Exportiere das Modell in das ONNX-Format model.export(format="onnx")Weitere Exportoptionen findest du in der Dokumentation zum Export-Modus.
Ja. Übergib nach dem Training eine andere Datensatz-YAML-Datei an
val(), um das Modell damit auszuwerten:from ultralytics import YOLO # Ein YOLO-Modell laden model = YOLO("yolo26n.yaml") # Das Modell trainieren model.train(data="coco8.yaml", epochs=5) # Das Modell anhand eines anderen Datensatzes validieren model.val(data="path/to/separate/data.yaml")Auf der Seite zum Val-Modus findest du ausführliche Beispiele und Anwendungshinweise.
Kommentare31
Stell eine Frage, teile deine Ergebnisse oder hilf jemand anderem.
KD-Chy
i think this is the better idea
seesmof
Believe in the Lord Jesus Christ.
kindaichinisan
How do I detect object using onnx model exported from pt model (yolo v9). Any sample code? Is it required to do pre-processing and post-processing?
Glenn JocherUltralytics@kindaichinisan you can use ONNX models directly with Ultralytics for inference - no manual pre/post-processing needed:
from ultralytics import YOLO # Load the ONNX model model = YOLO("your_model.onnx") # Run inference results = model("image.jpg")The Ultralytics framework handles all pre-processing and post-processing automatically when using ONNX models, just like with PT models.
UltralyticsAssistantUltralytics
👋 Hello, thank you for your interest in Ultralytics 🚀! We recommend checking out the Docs for new users, particularly the Python Usage guide you’ve linked, which contains detailed instructions on integrating YOLO for object detection, segmentation, and classification.
If this is a 🐛 Bug Report, please provide a minimum reproducible example so we can assist you better.
For custom training or ❓ questions, please include as much detail as possible, such as your Python script, dataset examples, training logs, or errors, and ensure you’re following our Tips for Best Training Results.
Looking to connect with the Ultralytics community? Join us:
- For real-time chat, visit Discord 🎧
- For focused discussions, try Discourse
- For general discussions and tips, explore our Subreddit
Upgrade
Ensure you’re running the latest version of the
ultralyticspackage with all its requirements. Upgrade in a Python>=3.8 environment with PyTorch>=1.8 by running:pip install -U ultralyticsEnvironments
YOLO works seamlessly in any of the following verified environments (preloaded with dependencies like CUDA, Python, and PyTorch):
- Notebooks with free GPU:
- Google Cloud Deep Learning VM: See GCP Quickstart Guide
- Amazon Deep Learning AMI: See AWS Quickstart Guide
- Docker Image: See Docker Quickstart Guide
Status
If the badge above is green, our Ultralytics CI tests are passing. These tests are run daily and verify correct operation of all YOLO Modes and Tasks across macOS, Windows, and Ubuntu.
This is an automated response to assist you quickly. An Ultralytics engineer will review your question and provide additional support shortly 😊
dnnxl
Hi Augmentations is available for YOLOv11?
Glenn JocherUltralytics(bearbeitet)@dnnxl yes, YOLO11 supports augmentations during training. They are controlled by training arguments such as
hsv_h,fliplr,scale,mosaicandmixup, not by the dataset YAML file. See Augmentation Settings and the Train Mode documentation. Let us know if you have further questions!1dnnxl
@dnnxl yes, YOLO11 supports augmentations during training, which are defined in the dataset configuration YAML file. You can customize augmentations such as flipping, scaling, and cropping to enhance model performance. For more details, refer to the Train Mode documentation. Let us know if you have further questions!
Thanks for your answer, it works for object detection purposes right?
Glenn JocherUltralyticsYes, augmentations in YOLO11 are fully supported for object detection tasks and can be applied during training to improve model generalization. Let us know if you need guidance on configuring them!
Rain020
Operating system: Win11, Ultralyicts: 8.3.27, YOLO11. I have developed a desktop application for PC-side processing. I need to release related GPU memory resources after closing the page or completing tasks. However, I haven’t found an effective way to release the memory to prevent GPU memory leaks. Looking forward to your response.
Glenn JocherUltralytics@Rain020 to release GPU memory after completing tasks with YOLO11, you can try using PyTorch's
torch.cuda.empty_cache()function to clear unused cached memory. Additionally, ensure that all model and variable references are deleted and usedelto remove them before calling the cache clearing function. If issues persist, consider checking for any persistent references that might still occupy memory. For more details, refer to the PyTorch documentation.Rain020
Thank you for your response. I need to conduct some experiments to verify whether our solution is effective.
QSHCUPID
results = model("https://ultralytics.com/images/bus.jpg")
QSHCUPID
results = model("https://ultralytics.com/images/bus.jpg")
QSHCUPID
123
Sheepy1977
There are some translation-mistakes in Chinese "Train" should be "训练",not “火车” "Val" should be "校验",not "瓦尔" "Track“ should be "跟踪“,not "轨道"
Paula DerrengerUltralytics@Sheepy1977 thank you for pointing out the translation errors. We appreciate your attention to detail. We will update the translations as follows:
- "Train" will be corrected to "训练"
- "Val" will be corrected to "校验"
- "Track" will be corrected to "跟踪"
Your feedback helps us improve the documentation for all users. If you notice any other issues, please let us know.
yirenyixin
Hello, when I was training with the dataset, I found that all the label names I gave were changed to class_X after training. The following is the configuration of my ymal file: path: E:\BaiduNetdiskDownload\Citypersons train: images/train val: images/train nc: 1 name: 0: person
After training, use the model to recognize others. The label information displays class_0
Glenn JocherUltralyticsHello! It seems like the class names are defaulting to
class_Xbecause the model might not be recognizing the class names specified in your YAML file. This can sometimes happen if there's an issue with the formatting of the YAML file or how the classes are being read during training.To ensure your class names are recognized correctly, please make sure your YAML file is formatted correctly. Here's a corrected version of your YAML configuration:
path: E:\BaiduNetdiskDownload\Citypersons train: images/train val: images/train nc: 1 names: - personNotice the change from
name:tonames:and ensuring that the class names are listed with a dash-. This should help the model recognize and use the correct class names during training and inference.If the issue persists after this adjustment, please double-check the path and file names for typos and ensure that the dataset is being loaded correctly during training. If you need further assistance, feel free to ask! 😊
flyingship19820207
The code is simple, for it is the same with your sample:
from ultralytics import YOLO
Create a new YOLO model from scratch
model = YOLO('yolov8n.yaml')
Load a pretrained YOLO model (recommended for training)
model = YOLO('yolov8n.pt')
Train the model using the 'coco128.yaml' dataset for 3 epochs
results = model.train(data='coco128.yaml', epochs=3)
Evaluate the model's performance on the validation set
results = model.val()
Perform object detection on an image using the model
results = model('https://ultralytics.com/images/bus.jpg')
Export the model to ONNX format
success = model.export(format='onnx')
Below is the error details: Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/ultralytics/engine/trainer.py", line 133, in init self.data = check_det_dataset(self.args.data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/ultralytics/data/utils.py", line 271, in check_det_dataset if zipfile.is_zipfile(file) or is_tarfile(file): ^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/tarfile.py", line 2791, in is_tarfile t = open(name) ^^^^^^^^^^ File "/usr/local/lib/python3.11/tarfile.py", line 1804, in open return func(name, "r", fileobj, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/tarfile.py", line 1933, in xzopen t = cls.taropen(name, mode, fileobj, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/tarfile.py", line 1854, in taropen return cls(name, mode, fileobj, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/tarfile.py", line 1714, in init self.firstmember = self.next() ^^^^^^^^^^^ File "/usr/local/lib/python3.11/tarfile.py", line 2631, in next raise e File "/usr/local/lib/python3.11/tarfile.py", line 2604, in next tarinfo = self.tarinfo.fromtarfile(self) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/tarfile.py", line 1292, in fromtarfile buf = tarfile.fileobj.read(BLOCKSIZE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/lzma.py", line 207, in read return self._buffer.read(size) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/_compression.py", line 68, in readinto data = self.read(len(byte_view)) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/_compression.py", line 96, in read if self._decompressor.needs_input: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: '_lzma.LZMADecompressor' object has no attribute 'needs_input'
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File "/root/chenyong/1_yolo/1_test/yolo_test.py", line 10, in results = model.train(data='coco128.yaml', epochs=3) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/ultralytics/engine/model.py", line 635, in train self.trainer = (trainer or self._smart_load("trainer"))(overrides=args, _callbacks=self.callbacks) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/ultralytics/engine/trainer.py", line 137, in init raise RuntimeError(emojis(f"Dataset '{clean_url(self.args.data)}' error ❌ {e}")) from e RuntimeError: Dataset 'coco128.yaml' error ❌ '_lzma.LZMADecompressor' object has no attribute 'needs_input'
Paula DerrengerUltralyticsIt seems like you're encountering an issue related to the LZMA compression library, specifically with the
_lzma.LZMADecompressorobject. This could be due to a variety of reasons, including compatibility issues with the Python version you're using or the specific dataset file format.As a first step, I recommend ensuring that your Python environment is up-to-date and that you're using a compatible version of the Ultralytics YOLO package. Additionally, verifying the integrity and format of the
coco128.yamldataset file might help, as the error suggests there could be an issue with reading the dataset file.If you're still facing this issue after checking these points, could you please provide more details about your environment, such as the Python and Ultralytics YOLO versions? This information will help us better understand the problem and assist you more effectively. 🛠️
In the meantime, here's a quick check you can perform to ensure your dataset file is accessible and correctly formatted:
import yaml # Attempt to load the YAML file to check its integrity with open('coco128.yaml', 'r') as file: dataset = yaml.safe_load(file) print(dataset)This code snippet will try to load your
coco128.yamlfile and print its contents, which can help identify if there are any issues with the file itself.flyingship19820207
Thanks for your reply. I copy coco128.yaml from /usr/local/lib/python3.11/site-packages/ultralytics/cfg/datasets/coco128.yaml to current work dir.And run the code you provided: import yaml
Attempt to load the YAML file to check its integrity
with open('coco128.yaml', 'r') as file: dataset = yaml.safe_load(file) print(dataset) The result is as below: {'path': '../datasets/coco128', 'train': 'images/train2017', 'val': 'images/train2017', 'test': None, 'names': {0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus', 6: 'train', 7: 'truck', 8: 'boat', 9: 'traffic light', 10: 'fire hydrant', 11: 'stop sign', 12: 'parking meter', 13: 'bench', 14: 'bird', 15: 'cat', 16: 'dog', 17: 'horse', 18: 'sheep', 19: 'cow', 20: 'elephant', 21: 'bear', 22: 'zebra', 23: 'giraffe', 24: 'backpack', 25: 'umbrella', 26: 'handbag', 27: 'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis', 31: 'snowboard', 32: 'sports ball', 33: 'kite', 34: 'baseball bat', 35: 'baseball glove', 36: 'skateboard', 37: 'surfboard', 38: 'tennis racket', 39: 'bottle', 40: 'wine glass', 41: 'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl', 46: 'banana', 47: 'apple', 48: 'sandwich', 49: 'orange', 50: 'broccoli', 51: 'carrot', 52: 'hot dog', 53: 'pizza', 54: 'donut', 55: 'cake', 56: 'chair', 57: 'couch', 58: 'potted plant', 59: 'bed', 60: 'dining table', 61: 'toilet', 62: 'tv', 63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard', 67: 'cell phone', 68: 'microwave', 69: 'oven', 70: 'toaster', 71: 'sink', 72: 'refrigerator', 73: 'book', 74: 'clock', 75: 'vase', 76: 'scissors', 77: 'teddy bear', 78: 'hair drier', 79: 'toothbrush'}, 'download': 'https://ultralytics.com/assets/coco128.zip'}
flyingship19820207
python version is Python 3.11.7 (main, Jan 15 2024, 10:22:22) [GCC 11.4.0] on linux YOLO version is 8.1.24
Paula DerrengerUltralytics(bearbeitet)@flyingship19820207 hey there! Thanks for reaching out with your environment details. It looks like you're using Python 3.11.7 and YOLOv8 version 8.1.24, which should be compatible.
Given the error you encountered, it seems like there might be an issue with the LZMA library in Python 3.11.7 or how the dataset is being processed. As a quick workaround, you might want to try running your code in a virtual environment with an earlier version of Python (e.g., Python 3.8 or 3.9) to see if the issue persists. This can help isolate whether it's a Python version-specific issue.
Here's a quick guide on setting up a virtual environment:
# Create a virtual environment with Python 3.8 (needs to be installed already) python3.8 -m venv yolov8-env # Activate the virtual environment source yolov8-env/bin/activate # Install Ultralytics YOLO pip install ultralyticsAfter setting up and activating your virtual environment, try running your YOLOv8 code again. If the problem is resolved, it might be worth reporting this as a compatibility issue with Python 3.11.7 on the Ultralytics GitHub page for further investigation. 🕵️♂️
Let me know how it goes!
flyingship19820207
Thanks for your advice, I will try using python3.9 today.
flyingship19820207
I have tried python3.10 which system-provided by ubuntu 22.4,it works well.It seems the error is caused by many python version in one system.
Paula DerrengerUltralyticsHey there! 🎉 It's great to hear that switching to Python 3.10 resolved the issue for you. It seems like the problem was indeed related to having multiple Python versions in your system. This can sometimes lead to conflicts, especially with dependencies and libraries that are sensitive to the Python version.
For future reference, it's always a good idea to use virtual environments for each project. This way, you can manage dependencies more effectively and avoid version conflicts. Here's a quick way to set up a virtual environment for your projects:
python3 -m venv myenv source myenv/bin/activateAnd then, you can install the specific packages you need within this isolated environment.
If you have any more questions or run into further issues, feel free to reach out. Happy coding with YOLOv8! 🚀
flyingship19820207
there is an error while trying to train yolo8 :RuntimeError: Dataset 'coco8.yaml' error ❌ '_lzma.LZMADecompressor' object has no attribute 'needs_input'.I use python3.11 and the system is ubuntu.How to fix it.
Paula DerrengerUltralyticsHey there! 👋 It seems like you're encountering an issue related to the
_lzmamodule while training YOLOv8 with Python 3.11 on Ubuntu. This could be due to a compatibility issue with the LZMA library in Python 3.11.A quick workaround could be to try downgrading to Python 3.8 or 3.9, as these versions are known to work well with YOLOv8 and its dependencies. You can manage multiple Python versions using a tool like
pyenv.Here's how you can install and use
pyenvto switch to Python 3.8:# Install pyenv curl https://pyenv.run | bash # Add pyenv to path (you might want to add this to your .bashrc or .zshrc) export PATH="$HOME/.pyenv/bin:$PATH" eval "$(pyenv init --path)" eval "$(pyenv virtualenv-init -)" # Install Python 3.8 pyenv install 3.8.10 # Set the local (current directory) Python version to 3.8.10 pyenv local 3.8.10 # Verify the Python version python --versionAfter switching to Python 3.8, try running your training command again. If the issue persists or you have any more questions, feel free to reach out! 😊
flyingship19820207
I comment these code below: #if zipfile.is_zipfile(file) or is_tarfile(file):
new_dir = safe_download(file, dir=DATASETS_DIR, unzip=True, delete=False)
file = find_dataset_yaml(DATASETS_DIR / new_dir)
extract_dir, autodownload = file.parent, False
in file /usr/local/lib/python3.11/site-packages/ultralytics/data/utils.py,then run again, it seems works.
Paula DerrengerUltralytics(bearbeitet)Hey there! 👋 It looks like you've found a workaround by commenting out some code related to dataset extraction in
utils.py. While this might work temporarily, it's generally not recommended to modify library code directly, as it could lead to unexpected behavior or issues with future updates.The error you encountered seems related to the
_lzmamodule in Python 3.11. This could be a compatibility issue with the Python version and the LZMA library. A safer approach might be to ensure all your dependencies are correctly installed and compatible with Python 3.11. You could try reinstalling thelzmamodule or using a Python environment with a version known to work well with YOLOv8, such as Python 3.8 or 3.9.If you're set on using Python 3.11, you might also want to check if there's an open issue on the Ultralytics YOLOv8 GitHub repository regarding this, or consider opening a new issue to bring this to the developers' attention. They might offer a more permanent fix or advice on handling this compatibility issue.
In the meantime, if you need to keep working, using a virtual environment with a different Python version could be a quick fix:
# Create a virtual environment with Python 3.8 python3.8 -m venv yolov8-env # Activate the virtual environment source yolov8-env/bin/activate # Install YOLOv8 and other dependencies pip install ultralyticsHope this helps, and happy coding! 😊
