Python 사용법

이 가이드에서는 Python 프로젝트에 Ultralytics YOLO를 통합하여 객체 감지, 인스턴스 분할, 시맨틱 분할, 깊이 추정, 분류, 포즈 추정 및 방향성 바운딩 박스 감지를 수행하는 방법을 알아봅니다. 사전 학습된 모델을 불러와 사용하는 방법, 새 모델을 학습하는 방법, 이미지에서 예측을 실행하는 방법을 배울 수 있습니다. Python 인터페이스를 사용하면 몇 줄의 코드만으로 프로젝트에 YOLO를 추가할 수 있습니다.



시청: Ultralytics YOLO 마스터하기: Python

예를 들어 몇 줄의 코드만으로 모델을 불러오고 학습한 뒤 검증 세트에서 성능을 평가하고, ONNX 형식으로 내보낼 수도 있습니다.

Python
from ultralytics import YOLO

# 처음부터 새 YOLO 모델 만들기
model = YOLO("yolo26n.yaml")

# 사전 학습된 YOLO 모델 불러오기(학습에 권장)
model = YOLO("yolo26n.pt")

# 'coco8.yaml' 데이터셋을 사용하여 모델을 3 epoch 동안 학습하기
results = model.train(data="coco8.yaml", epochs=3)

# 검증 세트에서 모델 성능 평가하기
results = model.val()

# 모델을 사용하여 이미지에서 객체 감지 수행하기
results = model("https://ultralytics.com/images/bus.jpg")

# 모델을 ONNX 형식으로 내보내기
success = model.export(format="onnx")

학습#

Train 모드는 커스텀 데이터셋으로 YOLO 모델을 학습하는 데 사용됩니다. 이 모드에서는 지정된 데이터셋과 하이퍼파라미터를 사용해 모델을 학습합니다. 학습 과정에서는 이미지에 있는 객체의 클래스와 위치를 정확하게 예측할 수 있도록 모델 파라미터를 최적화합니다.

학습
from ultralytics import YOLO

model = YOLO("yolo26n.pt")  # 모든 모델 유형 전달
results = model.train(epochs=5)

학습 예제

검증#

Val 모드는 YOLO 모델 학습 후 검증하는 데 사용됩니다. 이 모드에서는 검증 세트로 모델을 평가하여 정확도와 일반화 성능을 측정합니다. 이 모드를 사용해 모델의 하이퍼파라미터를 조정하고 성능을 개선할 수 있습니다.

검증
from ultralytics import YOLO

# YOLO 모델 로드
model = YOLO("yolo26n.yaml")

# 모델 학습
model.train(data="coco8.yaml", epochs=5)

# 학습 데이터 세트의 검증 분할로 검증
model.val()

Val 예제

예측#

Predict 모드는 학습된 YOLO 모델을 사용하여 새 이미지나 동영상에서 예측을 수행하는 데 사용됩니다. 이 모드에서는 체크포인트 파일에서 모델을 로드한 다음, 사용자가 추론을 수행할 이미지나 동영상을 제공할 수 있습니다. 모델은 입력 이미지나 동영상에서 객체의 클래스와 위치를 예측합니다.

예측
import cv2
from PIL import Image

from ultralytics import YOLO

model = YOLO("model.pt")
# 모든 형식 지원 - 이미지/디렉터리/Path/URL/동영상/PIL/ndarray. 웹캠은 0
results = model.predict(source="folder", show=True)  # 예측 결과 표시. 모든 YOLO predict 인수 지원

# PIL에서
im1 = Image.open("bus.jpg")
results = model.predict(source=im1, save=True)  # 플롯한 이미지 저장

# ndarray에서
im2 = cv2.imread("bus.jpg")
results = model.predict(source=im2, save=True, save_txt=True)  # 예측 결과를 레이블로 저장

# PIL/ndarray 목록에서
results = model.predict(source=[im1, im2])

Predict 예제

내보내기#

Export 모드는 배포에 사용할 수 있는 형식으로 YOLO 모델을 내보내는 데 사용됩니다. 이 모드에서는 다른 소프트웨어 애플리케이션이나 하드웨어 장치에서 사용할 수 있는 형식으로 모델을 변환합니다. 이 모드는 프로덕션 환경에 모델을 배포할 때 유용합니다.

내보내기

공식 YOLO 모델을 동적 배치 크기 및 이미지 크기를 지원하는 ONNX 형식으로 내보냅니다.

from ultralytics import YOLO

model = YOLO("yolo26n.pt")
model.export(format="onnx", dynamic=True)

Export 예제

추적#

Track 모드는 YOLO 모델을 사용해 객체를 실시간으로 추적합니다. 이 모드에서는 체크포인트 파일에서 모델을 불러오고, 사용자가 실시간 객체 추적을 위해 라이브 비디오 스트림을 제공할 수 있습니다. 이 모드는 감시 시스템이나 자율주행차와 같은 애플리케이션에 유용합니다.

추적
from ultralytics import YOLO

# 모델 로드
model = YOLO("yolo26n.pt")  # 공식 탐지 모델 로드
model = YOLO("yolo26n-seg.pt")  # 공식 세그멘테이션 모델 로드
model = YOLO("path/to/best.pt")  # 사용자 지정 모델 로드

# 모델로 추적
results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True)
results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True, tracker="bytetrack.yaml")

Track 예제

벤치마크#

벤치마크 모드는 YOLO의 다양한 내보내기 형식에 대한 속도와 정확도를 측정하는 데 사용됩니다. 벤치마크는 내보낸 형식의 크기, 작업 지표(객체 탐지, 세그멘테이션, 포즈 및 OBB의 경우 mAP50-95, 시맨틱 세그멘테이션의 경우 mIoU, 깊이 추정의 경우 δ1, 분류의 경우 accuracy_top1)와 ONNX, OpenVINO, TensorRT 등 다양한 내보내기 형식에서 이미지당 밀리초 단위로 측정한 추론 시간을 보여줍니다. 이 정보를 활용하면 사용자는 속도와 정확도 요구 사항에 따라 특정 사용 사례에 가장 적합한 내보내기 형식을 선택할 수 있습니다.

벤치마크

공식 YOLO 모델을 모든 내보내기 형식에서 벤치마킹합니다.

from ultralytics.utils.benchmarks import benchmark

# Benchmark
benchmark(model="yolo26n.pt", data="coco8.yaml", imgsz=640, device=0)

벤치마크 예제

Trainer 사용#

YOLO 모델 클래스는 Trainer 클래스의 상위 수준 래퍼 역할을 합니다. 각 YOLO 작업에는 고유한 Trainer가 있으며, Trainer는 BaseTrainer을 상속합니다. 이러한 아키텍처를 통해 머신러닝 워크플로를 더욱 유연하게 구성하고 사용자 지정할 수 있습니다.

탐지 Trainer 예제
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  # 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")

# 마지막 체크포인트에서 중단된 학습 실행 재개
trainer = DetectionTrainer(overrides={"resume": "path/to/last.pt"})
trainer.train()

커스텀 작업을 지원하도록 Trainer를 맞춤 설정하거나 연구개발 아이디어를 탐색할 수 있습니다. Ultralytics YOLO의 모듈식 설계를 통해 새로운 컴퓨터 비전 작업을 수행하거나 기존 모델을 파인튜닝해 성능을 개선하는 등 구체적인 요구 사항에 맞게 프레임워크를 조정할 수 있습니다.

사용자 지정 튜토리얼

자주 묻는 질문#

  • Ultralytics YOLO를 Python 프로젝트에 간단하게 통합할 수 있습니다. 사전 학습된 모델을 로드하거나 새 모델을 처음부터 학습할 수 있습니다. 시작하는 방법은 다음과 같습니다.

    from ultralytics import YOLO
    
    # 사전 학습된 YOLO 모델 로드
    model = YOLO("yolo26n.pt")
    
    # 이미지에서 객체 탐지 수행
    results = model("https://ultralytics.com/images/bus.jpg")
    
    # 결과 시각화
    for result in results:
        result.show()

    자세한 예제는 Predict 모드 섹션을 참조하세요.

  • Ultralytics YOLO는 다양한 머신러닝 워크플로를 위해 6가지 모드를 제공합니다:

    • Train: 사용자 지정 데이터 세트를 사용하여 모델을 학습합니다.
    • Val: 검증 세트에서 모델 성능을 검증합니다.
    • Predict: 새 이미지나 동영상 스트림에서 예측을 수행합니다.
    • Export: ONNX 및 TensorRT와 같은 다양한 형식으로 모델을 내보냅니다.
    • Track: 동영상 스트림에서 객체를 실시간으로 추적합니다.
    • Benchmark: 다양한 구성에서 모델 성능을 벤치마킹합니다.

    각 모드는 모델 개발 및 배포의 서로 다른 단계를 담당합니다.

  • 커스텀 YOLO 모델을 학습하려면 데이터셋과 기타 하이퍼파라미터를 지정합니다. 간단한 예시는 다음과 같습니다:

    from ultralytics import YOLO
    
    # YOLO 모델 로드
    model = YOLO("yolo26n.yaml")
    
    # 사용자 지정 데이터 세트로 모델 학습
    model.train(data="path/to/your/dataset.yaml", epochs=10)
  • export 함수를 사용하면 배포에 적합한 형식으로 YOLO 모델을 간단하게 내보낼 수 있습니다. 예를 들어 모델을 ONNX 형식으로 내보낼 수 있습니다.

    from ultralytics import YOLO
    
    # YOLO 모델 로드
    model = YOLO("yolo26n.pt")
    
    # 모델을 ONNX 형식으로 내보내기
    model.export(format="onnx")

    다양한 내보내기 옵션은 Export 모드 문서를 참조하세요.

  • 네. 학습 후 다른 데이터셋 YAML을 val()에 전달하면 해당 데이터셋에서 모델을 평가할 수 있습니다:

    from ultralytics import YOLO
    
    # YOLO 모델 로드
    model = YOLO("yolo26n.yaml")
    
    # 모델 학습
    model.train(data="coco8.yaml", epochs=5)
    
    # 다른 데이터 세트에서 모델 검증
    model.val(data="path/to/separate/data.yaml")

    자세한 예제와 사용법은 Val 모드 페이지를 참조하세요.

댓글31

질문을 하거나 결과를 공유하거나 다른 사람을 도와주세요.

  1. kindaichinisanGitHub

    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?

    1. 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.

  2. UltralyticsAssistantGitHubUltralytics

    👋 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 ultralytics package with all its requirements. Upgrade in a Python>=3.8 environment with PyTorch>=1.8 by running:

    pip install -U ultralytics

    Environments

    YOLO works seamlessly in any of the following verified environments (preloaded with dependencies like CUDA, Python, and PyTorch):

    Status

    Ultralytics CI

    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 😊

    1. dnnxlGitHub

      @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?

    2. Glenn JocherUltralytics

      Yes, 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!

  3. Rain020GitHub

    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.

    1. 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 use del to 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.

    2. Rain020GitHub

      Thank you for your response. I need to conduct some experiments to verify whether our solution is effective.

  4. Sheepy1977GitHub

    There are some translation-mistakes in Chinese "Train" should be "训练",not “火车” "Val" should be "校验",not "瓦尔" "Track“ should be "跟踪“,not "轨道"

    1. 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.

  5. yirenyixinGitHub

    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

    1. Glenn JocherUltralytics

      Hello! It seems like the class names are defaulting to class_X because 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:
        - person

      Notice the change from name: to names: 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! 😊

  6. flyingship19820207GitHub

    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')

    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'

    1. Paula DerrengerUltralytics

      It seems like you're encountering an issue related to the LZMA compression library, specifically with the _lzma.LZMADecompressor object. 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.yaml dataset 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.yaml file and print its contents, which can help identify if there are any issues with the file itself.

    2. flyingship19820207GitHub

      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'}

    3. Paula DerrengerUltralytics(수정됨)

      @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 ultralytics

      After 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!

    4. flyingship19820207GitHub

      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.

    5. Paula DerrengerUltralytics

      Hey 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/activate

      And 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! 🚀

  7. flyingship19820207GitHub

    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.

    1. Paula DerrengerUltralytics

      Hey there! 👋 It seems like you're encountering an issue related to the _lzma module 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 pyenv to 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 --version

      After 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! 😊

    2. flyingship19820207GitHub

      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.

    3. Paula DerrengerUltralytics(수정됨)

      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 _lzma module 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 the lzma module 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 ultralytics

      Hope this helps, and happy coding! 😊