Bắt đầu

Cài đặt Ultralytics

Cài đặt package ultralytics bằng pip, conda hoặc Docker, hay cài từ mã nguồn, sau đó chạy dự đoán đầu tiên với model YOLO26 pretrained. Mỗi phương thức đều cài đặt tất cả dependency bắt buộc được liệt kê trong pyproject.toml.

Cài đặt

Cài đặt hoặc cập nhật package ultralytics trong môi trường Python>=3.8 với PyTorch>=1.8:

pip install -U ultralytics

Để cài đặt phiên bản phát triển mới nhất, hãy cài trực tiếp từ repository GitHub của Ultralytics:

pip install git+https://github.com/ultralytics/ultralytics.git@main
Mẹo

Các yêu cầu của PyTorch thay đổi tùy theo hệ điều hành và phiên bản CUDA. Để sử dụng một bản dựng cụ thể, hãy cài đặt PyTorch trước theo hướng dẫn cài đặt PyTorch, sau đó cài đặt ultralytics. Đối với GPU AMD trên Linux, hãy cài đặt bản dựng PyTorch dùng ROCm như mô tả trong hướng dẫn tích hợp AMD.

Sử dụng Ultralytics với CLI#

Chạy dự đoán đầu tiên từ terminal bằng lệnh yolo:

yolo predict model=yolo26n.pt

Các trọng số yolo26n.pt đã huấn luyện trước sẽ tự động được tải xuống, model chạy trên hai ảnh mẫu đi kèm và lệnh hiển thị vị trí lưu kết quả đã chú thích, là runs/detect/predict trong lần chạy đầu tiên. Trỏ source đến ảnh, video, thư mục, URL hoặc luồng của bạn, hoặc đến webcam bằng source=0:

yolo predict model=yolo26n.pt source=0 show=True

predict là mode, tức thao tác cần thực hiện với model: train, val, predict, export, track hoặc benchmark. Task (detect, segment, semantic, depth, classify, pose hoặc obb) được đọc từ tệp model, vì vậy cú pháp yolo TASK MODE ARGS thường chỉ cần mode cùng các cặp arg=value, chẳng hạn như imgsz=640. Xem Hướng dẫn CLI để biết tất cả mode và trang Cấu hình để xem mọi tham số.

Sử dụng Ultralytics với Python#

Thực hiện cùng dự đoán đó trong Python:

from ultralytics import YOLO

model = YOLO("yolo26n.pt")  # tải model detection YOLO26n đã huấn luyện trước
results = model("https://ultralytics.com/images/bus.jpg", save=True)  # dự đoán và lưu ảnh đã chú thích

results là danh sách các đối tượng Results, mỗi đối tượng ứng với một ảnh và chứa bbox, mask, keypoint hoặc xác suất lớp tùy theo task. Hướng dẫn Python trình bày cách huấn luyện, đánh giá, export và tracking bằng cùng lớp YOLO.



Xem: Hướng dẫn bắt đầu nhanh Ultralytics YOLO

Cài đặt Ultralytics#

Các cài đặt được lưu lâu dài, chẳng hạn như thư mục dataset, trọng số và runs, API key của Nền tảng Ultralytics và các tùy chọn bật/tắt trình ghi nhật ký thử nghiệm, nằm trong tệp JSON được quản lý bằng yolo settings. Xem trang Cài đặt để xem, thay đổi hoặc đặt lại các cài đặt này.

Tiếp theo là gì#

Khám phá các mode mà YOLO hỗ trợ, các tác vụ model có thể thực hiện và kích thước model YOLO26, sau đó huấn luyện trên dữ liệu của riêng bạn sau khi định dạng dữ liệu theo hướng dẫn về dataset.

Để tìm hiểu trước về những gì sắp ra mắt, hãy khám phá YOLO27 (Sắp ra mắt). Các model của YOLO27 hiện chưa có sẵn; những ví dụ trên sử dụng dòng YOLO26 đã phát hành.

Câu hỏi thường gặp#

  • Cài đặt Ultralytics bằng pip như sau:

    pip install -U ultralytics

    Lệnh này cài đặt bản phát hành ổn định mới nhất của package ultralytics từ PyPI. Để cài đặt phiên bản phát triển trực tiếp từ GitHub:

    pip install git+https://github.com/ultralytics/ultralytics.git

    Đảm bảo công cụ dòng lệnh Git đã được cài đặt trên hệ thống.

  • Có, hãy tạo môi trường conda cùng Python và Ultralytics YOLO trong một lệnh, sau đó kích hoạt môi trường đó:

    conda create --name ultralytics-env -c conda-forge python=3.11 ultralytics torchvision -y
    conda activate ultralytics-env

    Conda là một lựa chọn thay thế pip, giúp giải quyết các phiên bản tương thích cho toàn bộ package cùng lúc. Với môi trường CUDA, hãy thêm metapackage pytorch-gpu vào cùng lệnh để conda chọn bản PyTorch hỗ trợ CUDA:

    conda create --name ultralytics-env -c conda-forge python=3.11 ultralytics torchvision pytorch-gpu -y
    conda activate ultralytics-env

    Để biết thêm hướng dẫn, hãy xem hướng dẫn bắt đầu nhanh với Conda.

  • Docker cung cấp môi trường cô lập, nhất quán cho Ultralytics YOLO, nhờ đó cùng một cấu hình có thể chạy trên nhiều hệ thống mà không gặp vấn đề do cài đặt cục bộ. Có thể tìm các Docker image chính thức trên Docker Hub, với các biến thể dành cho GPU, CPU, ARM64, NVIDIA Jetson và Conda. Để tải về và chạy image mới nhất:

    # Pull the latest ultralytics image from Docker Hub
    sudo docker pull ultralytics/ultralytics:latest
    
    # Run the ultralytics image in a container with GPU support
    sudo docker run -it --ipc=host --device nvidia.com/gpu=all ultralytics/ultralytics:latest

    Trên Linux, yêu cầu thiết bị CDI cần Docker >= 28.2.0 và NVIDIA Container Toolkit >= 1.18. Để xem hướng dẫn Docker chi tiết, hãy tham khảo hướng dẫn bắt đầu nhanh với Docker.

  • Clone repository Ultralytics và thiết lập môi trường phát triển bằng cách:

    # Clone the ultralytics repository
    git clone https://github.com/ultralytics/ultralytics
    
    # Navigate to the cloned directory
    cd ultralytics
    
    # Install the package in editable mode for development
    pip install -e .

    Cách này cho phép bạn đóng góp cho dự án hoặc thử nghiệm với mã nguồn mới nhất. Để biết cách fork và ghim một nhánh tùy chỉnh, hãy xem Cài đặt cho phát triển.

  • CLI Ultralytics YOLO chạy mọi tác vụ và mode từ terminal bằng các lệnh một dòng, nhờ đó bạn có thể huấn luyện, xác thực, dự đoán và export mà không cần viết mã Python. Cú pháp cơ bản là:

    yolo TASK MODE ARGS

    Ví dụ, để huấn luyện một model detection:

    yolo train data=coco8.yaml model=yolo26n.pt epochs=10

    Tìm hiểu thêm các lệnh và ví dụ sử dụng trong Hướng dẫn CLI đầy đủ.

Bình luận57

Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.

  1. DebawyGitHub

    Can you add this commands to relevant files

    import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"

    to work around this error

    OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized. OMP: Hint This means that multiple copies of the OpenMP runtime have been linked into the program. That is dangerous, since it can degrade performance or cause incorrect results. The best thing to do is to ensure that only a single OpenMP runtime is linked into the process, e.g. by avoiding static linking of the OpenMP runtime in any library. As an unsafe, unsupported, undocumented workaround you can set the environment variable KMP_DUPLICATE_LIB_OK=TRUE to allow the program to continue to execute, but that may cause crashes or silently produce incorrect results. For more information, please see http://www.intel.com/software/products/support/.

    To Reproduce

    1
    1. Glenn JocherUltralytics

      Thanks for pointing that out! While setting the KMP_DUPLICATE_LIB_OK environment variable can indeed provide a workaround for the multiple copies of the OpenMP runtime error, it's generally recommended to address the root cause by ensuring only a single OpenMP runtime is linked, as indicated by the error message itself. 🛠️

      Injecting this workaround directly into the Ultralytics files might inadvertently mask underlying issues for some users. For those facing this specific error and understanding the associated risks, applying the workaround in their environment or at the beginning of their scripts before importing any other libraries can offer a temporary solution:

      import os
      os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"

      Before applying this workaround, I'd suggest investigating the installation and dependencies of the libraries involved to identify possible conflicts with the OpenMP runtime. Feel free to reach out if you run into any hurdles while exploring these avenues. Happy coding! 🚀

      1
  2. D3RK0GitHub

    Problem

    I am getting the following message:

    View Ultralytics Settings with 'yolo settings' or at '/home/s3115879/.config/Ultralytics/settings.json'
    Update Settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'. For help see https://docs.ultralytics.com/quickstart/#ultralytics-settings.```
    
    I am using a script to train four models, one which is the YOLOv8 model. However, when I train one of the other models, I am getting this message as part of training screen output.
    I am surmising that it is leaking from the Ultralytics package import at the beginning of my script.
    
    # Question
    How can I solve this?
    
    Many thanks!
    1. Glenn JocherUltralytics

      @D3RK0 the message you are seeing is expected and indicates that Ultralytics has initialized its settings file. It is triggered when the ultralytics package is imported. To suppress this output, you can redirect or filter the logs in your script. For more details on managing settings, refer to the Ultralytics Settings Guide. Let me know if you need further clarification.

  3. serna01GitHub

    I have my setting file: ¨ { "settings_version": "0.0.6", "datasets_dir": "/mnt/aiongpfs/users/aserna/2022-utils-main", "weights_dir": "weights", "runs_dir": "runs", "uuid": "d35778183b9f05d1160fdafdfe94267790d645e372ef7fefb95e8edcd6205215", "sync": true, "api_key": "", "openai_api_key": "", "clearml": true, "comet": true, "dvc": true, "hub": true, "mlflow": true, "neptune": true, "raytune": true, "tensorboard": true, "wandb": false, "vscode_msg": true } " and when i run my code " from ultralytics import YOLO

    Initialize model and specify the checkpoint

    #model = YOLO('yolo11n.pt') # Use a pretrained YOLO model model = YOLO('yolov8s.pt') #model = YOLO('runs/detect/train19/weights/best.pt') # Use a pretrained YOLOv8 model

    Train the model with custom dataset

    model.train( data='stream1.yaml', # Path to YAML config epochs=25, # Number of epochs imgsz=640, # Image size batch=16, # Batch size device=0, # GPU device ID fraction=0.5, workers=1

    )

    metrics = model.val(data='stream1.yaml', imgsz=640) print(metrics)" i get the following error "FileNotFoundError: Dataset 'stream1.yaml' images not found ⚠️, missing path '/mnt/aiongpfs/users/aserna/2022-utils-main/stream-1/datasets/stream-1/images/val' Note dataset download directory is '/mnt/aiongpfs/users/aserna/2022-utils-main/stream-1/datasets'. You can update this in '/home/users/aserna/.config/Ultralytics/settings.json' " , with my stream1.yaml "path: stream-1/ # Path to your data folder train: images/train # Folder with training images val: images/val # Folder with validation images test: images/test nc: 11 names: # Class names and indexes 0: proba_2 1: cheops 2: debris 3: double_star 4: earth_observation_sat_1 5: lisa_pathfinder 6: proba_3_csc 7: proba_3_ocs 8: smart_1 9: soho 10: xmm_newton " so i go back and check the settings.json and somehow its adding information ( i dont know how) to the filepath "{ "settings_version": "0.0.6", "datasets_dir": "/mnt/aiongpfs/users/aserna/2022-utils-main/stream-1/datasets", "weights_dir": "weights", "runs_dir": "runs", "uuid": "d35778183b9f05d1160fdafdfe94267790d645e372ef7fefb95e8edcd6205215", "sync": true, "api_key": "", "openai_api_key": "", "clearml": true, "comet": true, "dvc": true, "hub": true, "mlflow": true, "neptune": true, "raytune": true, "tensorboard": true, "wandb": false, "vscode_msg": true }", its only happening with Yolo11, when I tried the same code with yolov8s it seems to be working work

    1. Glenn JocherUltralytics

      @serna01 it seems like the issue is related to the dataset path in your stream1.yaml file. Please ensure the paths specified in your YAML file match the actual directory structure on your system. If the problem persists with YOLO11, consider verifying the settings in your settings.json to ensure they align with your dataset's location.

    2. serna01GitHub

      yes, that was exactly my point, how could it be that the directory for one model is ok, but for v11 i get the error of filepath? Right now i am running the training with v8., but for some reason, when i just change the model name, it says that there ir an error reading the json file so it creates a new one, and that is why the new one has an incorrect file directory

    3. Glenn JocherUltralytics

      It seems like the issue may be related to the dataset directory paths specified in your stream1.yaml file. Ensure that the paths are correctly set relative to the datasets_dir in your settings.json. If the problem persists, try specifying the full path in your YAML file to see if that resolves the issue with YOLO11.

  4. dnnxlGitHub

    Hi! How can I plot some samples of the dataset with the bounding box for object detection before training with ultralytics? With the goal to check qualitatively the dataset is okay

    1. Glenn JocherUltralytics

      @dnnxl to visualize dataset samples with bounding boxes before training, you can use the ultralytics package to load your dataset and plot the images with annotations. This helps ensure your dataset is correctly labeled. For more detailed guidance, please refer to the Ultralytics documentation.

  5. siviktGitHub

    Hey, here are some issues while using ultralytics~=8.2.0

    I change settings, though it does not affect training process: runs are still go into "runs" under current directory, not under '/yolo_training/my_runs'

    working_dir = Path('/yolo_training')
    ultralytics.settings.update({
        'runs_dir': str(working_dir/'my_runs'),
        'weights_dir': str(working_dir/'my_weights'),
        'datasets_dir': str(working_dir/'my_datasets')
    })

    I am trying to train Yolov10 as following

    model = YOLO(model='yolov10l.pt', task='detect')
    train_results = model.train(
        data=str(dataset_cfg_path),
        val=True,
        epochs=1,
        batch=16,
        cache=False,
        workers=32, 
        patience=3,
        verbose=True,
        device='0'
    )

    and here is another issue: model.train() downloads 'yolov8n.pt'. Why it is so, if the model is defined as YOLO(model='yolov10l.pt', task='detect')?

    1. Glenn JocherUltralytics

      @sivikt it seems like the settings update isn't being applied correctly. Ensure the settings are updated before any model operations. Regarding the model download issue, please verify the model path and ensure 'yolov10l.pt' is accessible. If the problem persists, try reinstalling the package to ensure all components are up to date.

      1
  6. omrirGitHub

    I tried the basic install using 'pip install ultralytics' on computer with only CPU. I run the test CLI --> yolo detect predict model=yolov8n.pt source='https://ultralytics.com/images/bus.jpg' Got strange result. A lot of bounding boxes uncorrected on the upper part of the image: I cannot paste an image here, so here this is the textual result: Found https://ultralytics.com/images/bus.jpg locally at bus.jpg image 1/1 C:\Users\Omri-Einat\Desktop\pythonProject\bus.jpg: 640x480 13 persons, 65 bicycles, 14 cars, 4 motorcycles, 4 buss, 1 train, 1 truck, 2 boats, 1 traffic light, 25 fire hydrants, 4 stop signs, 43 parking meters, 7 benchs, 3 cats, 1 horse, 1 elephant, 6 giraffes, 15 backpacks, 8 umbrellas, 53 handbags, 1 tie, 1 frisbee, 3 skiss, 2 baseball bats, 7 baseball gloves, 1 tennis racket, 1 hot dog, 1 pizza, 1 laptop, 1 remote, 4 cell phones, 1 microwave, 4 ov ens, 1 sink, 1328.2ms Speed: 0.0ms preprocess, 1328.2ms inference, 31.3ms postprocess per image at shape (1, 3, 640, 480)

    Any idea?

    Thanks!

    1. Paula DerrengerUltralytics

      @omrir thank you for reporting this issue. It seems like the model is producing an unusually high number of detections. This could be due to a bug or an issue with the specific model version. Please ensure you are using the latest version of the ultralytics package by running pip install -U ultralytics. If the problem persists, try using a different pre-trained model or adjusting the confidence threshold with the conf argument to filter out low-confidence detections. If the issue continues, please provide more details so we can investigate further.

    2. omrirGitHub

      I performed what you suggested. Also tried different model and higher confidence. Still the same result:

      Successfully installed ultralytics-8.2.71

      [notice] A new release of pip is available: 23.2.1 -> 24.2 [notice] To update, run: python.exe -m pip install --upgrade pip PS C:\Users\Desktop\pythonProject> yolo detect predict model=yolov8s.pt source='https://ultralytics.com/images/bus.jpg' Ultralytics YOLOv8.2.71 🚀 Python-3.10.7 torch-2.4.0+cpu CPU (Intel Core(TM) i5-3570 3.40GHz) YOLOv8s summary (fused): 168 layers, 11,156,544 parameters, 0 gradients, 28.6 GFLOPs

      Found https://ultralytics.com/images/bus.jpg locally at bus.jpg image 1/1 C:\Users\Desktop\pythonProject\bus.jpg: 640x480 15 persons, 35 bicycles, 1 car, 7 motorcycles, 9 boats, 4 traffic lights, 29 fire hydrants, 2 stop signs, 18 parking meters, 3 benchs, 1 cow, 19 backpacks, 38 hand bags, 9 frisbees, 8 skiss, 2 baseball bats, 4 baseball gloves, 3 tennis rackets, 6 forks, 1 knife, 3 spoons, 1 hot dog, 1 dining table, 75 cell phones, 1 oven, 1 clock, 2 hair driers, 2 toothbrushs, 1328.1ms Speed: 0.0ms preprocess, 1328.1ms inference, 31.2ms postprocess per image at shape (1, 3, 640, 480) Results saved to runs\detect\predict8 💡 Learn more at https://docs.ultralytics.com/modes/predict PS C:\Users\Desktop\pythonProject> yolo detect predict model=yolov8m.pt conf=0.7 source='https://ultralytics.com/images/bus.jpg' Ultralytics YOLOv8.2.71 🚀 Python-3.10.7 torch-2.4.0+cpu CPU (Intel Core(TM) i5-3570 3.40GHz) YOLOv8m summary (fused): 218 layers, 25,886,080 parameters, 0 gradients, 78.9 GFLOPs

      Found https://ultralytics.com/images/bus.jpg locally at bus.jpg image 1/1 C:\Users\Desktop\pythonProject\bus.jpg: 640x480 9 persons, 2 bicycles, 30 cars, 20 airplanes, 13 buss, 2 boats, 7 fire hydrants, 2 parking meters, 2 benchs, 1 dog, 1 horse, 4 sheeps, 1 backpack, 57 umbrellas, 7 handbags, 1 tie, 21 frisbees, 1 skis, 1 snowboard, 2 sports balls, 4 kites, 46 baseball bats, 1 skateboard, 3 surfboards, 3 tennis rackets, 12 bottles, 2 cups, 12 forks, 4 knifes, 19 spoons, 1 banana, 2 pizzas, 3 dining tables, 1 re mote, 2 vases, 1 toothbrush, 2906.4ms Speed: 15.6ms preprocess, 2906.4ms inference, 0.0ms postprocess per image at shape (1, 3, 640, 480) Results saved to runs\detect\predict9 💡 Learn more at https://docs.ultralytics.com/modes/predict

    3. Paula DerrengerUltralytics

      Thank you for the detailed feedback. The issue with all bounding boxes having a probability of 1 and the excessive number of detections suggests a potential bug. Please ensure you are using the latest version of the ultralytics package. If the issue persists, try running the model on a different image or dataset to see if the problem is consistent. If it is, please open an issue on our GitHub repository with details about your environment and the steps to reproduce the issue. This will help us investigate and resolve the problem more effectively.

  7. Miseson2024GitHub

    Thank you for this great application! It has been amazing detecting objects with high occlusion successfully although I am a real Python beginner.

    I successfully trained a model myself using Spyder in Anaconda navigator after setting everything myself. I also successfully predicted objects in my own dataset until my Anaconda navigator stopped working when I tried to install an application at certain point. So, now I have uninstalled everything and reinstalled Python this time without Anaconda: Python and Spyder connected with kernels. Before, I did not like that I could not use pip due to Anaconda. I installed Ultralytics and PyTorch following the instruction. However, the prediction is completely wrong although the console does not show any error message. I have no clue what I should troubleshoot. What do you think is wrong?

    1. Paula DerrengerUltralytics

      @Miseson2024 thank you for your kind words! It sounds like you've done a great job setting up and using Ultralytics YOLO so far. Given that your predictions are now incorrect after reinstalling Python and Spyder, I recommend checking a few things:

      1. Ensure you have the latest versions of Ultralytics and PyTorch installed. You can update them using pip install -U ultralytics torch.
      2. Verify that your model and dataset paths are correctly specified and accessible.
      3. Check if your model weights were correctly saved and loaded. Sometimes, re-training the model can help if the weights are corrupted.

      If the issue persists, please try running your script outside of Spyder to see if the problem is specific to the IDE. For more detailed troubleshooting, refer to our Quickstart Guide.

      1
  8. jonaChong70GitHub

    Please be specific on the conflict errors. It will be helpful to post the errors. On Thursday 11 July 2024 at 05:42:24 pm GMT+8, Adeel Akram @.***> wrote:

    Hi all,

    Does anybody tried building a conda envirionment? I tried it by first installing latest PyTorch (CPU) for conda and then by installing Ultralytics for conda. I got a lot of conflict errors. However, installing ultralytics from PyPI inside conda environemnt works fine. I think there should be recommended versions for both PyTorch and Ultralytics.

    — Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you were mentioned.Message ID: @.***>

    1. Paula DerrengerUltralytics(đã chỉnh sửa)

      @jonaChong70 hi Adeel,

      Thank you for reaching out! 😊

      To address your issue with building a conda environment, it would be very helpful if you could provide specific conflict error messages you encountered. This will allow us to better understand and troubleshoot the problem.

      In the meantime, here are some steps you can follow to ensure a smooth installation:

      1. Install all packages together: When working in a CUDA environment, it's best practice to install ultralytics, torchvision and pytorch-gpu from conda-forge in a single command (PyTorch no longer publishes to the pytorch channel). This helps the conda package manager resolve any conflicts. For example:

        conda create --name ultralytics-env -c conda-forge python=3.11 ultralytics torchvision pytorch-gpu -y
      2. Verify package versions: Ensure you are using the latest versions of all packages. Sometimes, conflicts arise from outdated dependencies.

      3. Reproducible example: If the issue persists, please provide a minimum reproducible example. This will help us diagnose the problem more effectively. You can find guidance on creating a reproducible example here.

      If you prefer using pip within a conda environment and it works fine for you, that's also a valid approach. However, the conda installation should ideally work without issues, and we're here to help resolve any conflicts you encounter.

      Feel free to share the error logs, and we'll assist you further!

  9. a-akramGitHub(đã chỉnh sửa)

    Hi all,

    Has anybody tried building a conda environment? I tried it by installing the latest PyTorch (CPU) for conda and then by installing Ultralytics for conda. I got a lot of conflict errors. However, installing ultralytics from PyPI inside the conda environment works fine. I think there should be recommended versions for both PyTorch and Ultralytics.

    1. Paula DerrengerUltralytics(đã chỉnh sửa)

      @a-akram hi there,

      Thank you for reaching out! It sounds like you're encountering dependency conflicts when trying to set up a conda environment for Ultralytics. This can sometimes happen due to the complex nature of package dependencies.

      To help resolve this, I recommend installing all necessary packages in a single command to allow conda to manage dependencies more effectively. Here's a command that should help:

      conda create --name ultralytics-env -c conda-forge python=3.11 ultralytics torchvision pytorch-gpu -y

      This command creates a new environment and installs ultralytics, torchvision and a CUDA-enabled PyTorch (pytorch-gpu) from conda-forge together, which can help avoid conflicts. For CPU only, drop pytorch-gpu. PyTorch no longer publishes new releases to the pytorch conda channel.

      If you continue to experience issues, please ensure you are using the latest versions of all packages. You can check for updates and install the latest versions using:

      conda update --all

      Activate the new environment with conda activate ultralytics-env.

      For more detailed guidance, you can refer to our Quickstart Guide.

      If you have any further questions or need additional assistance, feel free to ask. Happy coding! 😊