{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "YOLOv8 Tutorial",
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "t6MPjfT5NrKQ"
      },
      "source": [
        "<div align=\"center\">\n",
        "\n",
        "  <a href=\"https://ultralytics.com/yolov8\" target=\"_blank\">\n",
        "    <img width=\"1024\", src=\"https://raw.githubusercontent.com/ultralytics/assets/main/yolov8/banner-yolov8.png\"></a>\n",
        "\n",
        "  [中文](https://docs.ultralytics.com/zh/) | [한국어](https://docs.ultralytics.com/ko/) | [日本語](https://docs.ultralytics.com/ja/) | [Русский](https://docs.ultralytics.com/ru/) | [Deutsch](https://docs.ultralytics.com/de/) | [Français](https://docs.ultralytics.com/fr/) | [Español](https://docs.ultralytics.com/es/) | [Português](https://docs.ultralytics.com/pt/) | [हिन्दी](https://docs.ultralytics.com/hi/) | [العربية](https://docs.ultralytics.com/ar/)\n",
        "\n",
        "  <a href=\"https://console.paperspace.com/github/ultralytics/ultralytics\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"/></a>\n",
        "  <a href=\"https://colab.research.google.com/github/ultralytics/ultralytics/blob/main/examples/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n",
        "  <a href=\"https://www.kaggle.com/ultralytics/yolov8\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n",
        "\n",
        "Welcome to the Ultralytics YOLOv8 🚀 notebook! <a href=\"https://github.com/ultralytics/ultralytics\">YOLOv8</a> is the latest version of the YOLO (You Only Look Once) AI models developed by <a href=\"https://ultralytics.com\">Ultralytics</a>. This notebook serves as the starting point for exploring the various resources available to help you get started with YOLOv8 and understand its features and capabilities.\n",
        "\n",
        "YOLOv8 models are fast, accurate, and easy to use, making them ideal for various object detection and image segmentation tasks. They can be trained on large datasets and run on diverse hardware platforms, from CPUs to GPUs.\n",
        "\n",
        "We hope that the resources in this notebook will help you get the most out of YOLOv8. Please browse the YOLOv8 <a href=\"https://docs.ultralytics.com/\">Docs</a> for details, raise an issue on <a href=\"https://github.com/ultralytics/ultralytics\">GitHub</a> for support, and join our <a href=\"https://ultralytics.com/discord\">Discord</a> community for questions and discussions!\n",
        "\n",
        "</div>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7mGmQbAO5pQb"
      },
      "source": [
        "# Setup\n",
        "\n",
        "Pip install `ultralytics` and [dependencies](https://github.com/ultralytics/ultralytics/blob/main/requirements.txt) and check software and hardware."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "wbvMlHd_QwMG",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "27ca383c-0a97-4679-f1c5-ba843f033de7"
      },
      "source": [
        "%pip install ultralytics\n",
        "import ultralytics\n",
        "ultralytics.checks()"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "Ultralytics YOLOv8.0.145 🚀 Python-3.10.6 torch-2.0.1+cu118 CUDA:0 (Tesla T4, 15102MiB)\n",
            "Setup complete ✅ (2 CPUs, 12.7 GB RAM, 24.2/78.2 GB disk)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4JnkELT0cIJg"
      },
      "source": [
        "# 1. Predict\n",
        "\n",
        "YOLOv8 may be used directly in the Command Line Interface (CLI) with a `yolo` command for a variety of tasks and modes and accepts additional arguments, i.e. `imgsz=640`. See a full list of available `yolo` [arguments](https://docs.ultralytics.com/usage/cfg/) and other details in the [YOLOv8 Predict Docs](https://docs.ultralytics.com/modes/train/).\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "zR9ZbuQCH7FX",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "64489d1f-e71a-44b5-92f6-2088781ca096"
      },
      "source": [
        "# Run inference on an image with YOLOv8n\n",
        "!yolo predict model=yolov8n.pt source='https://ultralytics.com/images/zidane.jpg'"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Downloading https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n.pt to 'yolov8n.pt'...\n",
            "100% 6.23M/6.23M [00:00<00:00, 77.2MB/s]\n",
            "Ultralytics YOLOv8.0.145 🚀 Python-3.10.6 torch-2.0.1+cu118 CUDA:0 (Tesla T4, 15102MiB)\n",
            "YOLOv8n summary (fused): 168 layers, 3151904 parameters, 0 gradients\n",
            "\n",
            "Downloading https://ultralytics.com/images/zidane.jpg to 'zidane.jpg'...\n",
            "100% 165k/165k [00:00<00:00, 7.46MB/s]\n",
            "image 1/1 /content/zidane.jpg: 384x640 2 persons, 1 tie, 365.8ms\n",
            "Speed: 13.7ms preprocess, 365.8ms inference, 431.7ms postprocess per image at shape (1, 3, 384, 640)\n",
            "Results saved to \u001b[1mruns/detect/predict\u001b[0m\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hkAzDWJ7cWTr"
      },
      "source": [
        "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n",
        "<img align=\"left\" src=\"https://user-images.githubusercontent.com/26833433/212889447-69e5bdf1-5800-4e29-835e-2ed2336dede2.jpg\" width=\"600\">"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0eq1SMWl6Sfn"
      },
      "source": [
        "# 2. Val\n",
        "Validate a model's accuracy on the [COCO](https://docs.ultralytics.com/datasets/detect/coco/) dataset's `val` or `test` splits. The latest YOLOv8 [models](https://github.com/ultralytics/ultralytics#models) are downloaded automatically the first time they are used. See [YOLOv8 Val Docs](https://docs.ultralytics.com/modes/val/) for more information."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "WQPtK1QYVaD_"
      },
      "source": [
        "# Download COCO val\n",
        "import torch\n",
        "torch.hub.download_url_to_file('https://ultralytics.com/assets/coco2017val.zip', 'tmp.zip')  # download (780M - 5000 images)\n",
        "!unzip -q tmp.zip -d datasets && rm tmp.zip  # unzip"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "X58w8JLpMnjH",
        "outputId": "e3aacd98-ceca-49b7-e112-a0c25979ad6c",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "# Validate YOLOv8n on COCO8 val\n",
        "!yolo val model=yolov8n.pt data=coco8.yaml"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Ultralytics YOLOv8.0.145 🚀 Python-3.10.6 torch-2.0.1+cu118 CUDA:0 (Tesla T4, 15102MiB)\n",
            "YOLOv8n summary (fused): 168 layers, 3151904 parameters, 0 gradients\n",
            "\n",
            "Dataset 'coco8.yaml' images not found ⚠️, missing path '/content/datasets/coco8/images/val'\n",
            "Downloading https://ultralytics.com/assets/coco8.zip to '/content/datasets/coco8.zip'...\n",
            "100% 433k/433k [00:00<00:00, 12.4MB/s]\n",
            "Unzipping /content/datasets/coco8.zip to /content/datasets...\n",
            "Dataset download success ✅ (0.7s), saved to \u001b[1m/content/datasets\u001b[0m\n",
            "\n",
            "Downloading https://ultralytics.com/assets/Arial.ttf to '/root/.config/Ultralytics/Arial.ttf'...\n",
            "100% 755k/755k [00:00<00:00, 17.5MB/s]\n",
            "\u001b[34m\u001b[1mval: \u001b[0mScanning /content/datasets/coco8/labels/val... 4 images, 0 backgrounds, 0 corrupt: 100% 4/4 [00:00<00:00, 276.04it/s]\n",
            "\u001b[34m\u001b[1mval: \u001b[0mNew cache created: /content/datasets/coco8/labels/val.cache\n",
            "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100% 1/1 [00:03<00:00,  3.84s/it]\n",
            "                   all          4         17      0.621      0.833      0.888       0.63\n",
            "                person          4         10      0.721        0.5      0.519      0.269\n",
            "                   dog          4          1       0.37          1      0.995      0.597\n",
            "                 horse          4          2      0.751          1      0.995      0.631\n",
            "              elephant          4          2      0.505        0.5      0.828      0.394\n",
            "              umbrella          4          1      0.564          1      0.995      0.995\n",
            "          potted plant          4          1      0.814          1      0.995      0.895\n",
            "Speed: 0.3ms preprocess, 78.7ms inference, 0.0ms loss, 65.4ms postprocess per image\n",
            "Results saved to \u001b[1mruns/detect/val\u001b[0m\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZY2VXXXu74w5"
      },
      "source": [
        "# 3. Train\n",
        "\n",
        "<p align=\"\"><a href=\"https://bit.ly/ultralytics_hub\"><img width=\"1000\" src=\"https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png\"/></a></p>\n",
        "\n",
        "Train YOLOv8 on [Detect](https://docs.ultralytics.com/tasks/detect/), [Segment](https://docs.ultralytics.com/tasks/segment/), [Classify](https://docs.ultralytics.com/tasks/classify/) and [Pose](https://docs.ultralytics.com/tasks/pose/) datasets. See [YOLOv8 Train Docs](https://docs.ultralytics.com/modes/train/) for more information."
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Select YOLOv8 🚀 logger {run: 'auto'}\n",
        "logger = 'Comet' #@param ['Comet', 'TensorBoard']\n",
        "\n",
        "if logger == 'Comet':\n",
        "  %pip install -q comet_ml\n",
        "  import comet_ml; comet_ml.init()\n",
        "elif logger == 'TensorBoard':\n",
        "  %load_ext tensorboard\n",
        "  %tensorboard --logdir ."
      ],
      "metadata": {
        "id": "ktegpM42AooT"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "1NcFxRcFdJ_O",
        "outputId": "b750f2fe-c4d9-4764-b8d5-ed7bd920697b",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "source": [
        "# Train YOLOv8n on COCO8 for 3 epochs\n",
        "!yolo train model=yolov8n.pt data=coco8.yaml epochs=3 imgsz=640"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Ultralytics YOLOv8.0.145 🚀 Python-3.10.6 torch-2.0.1+cu118 CUDA:0 (Tesla T4, 15102MiB)\n",
            "\u001b[34m\u001b[1mengine/trainer: \u001b[0mtask=detect, mode=train, model=yolov8n.pt, data=coco8.yaml, epochs=3, patience=50, batch=16, imgsz=640, save=True, save_period=-1, cache=False, device=None, workers=8, project=None, name=None, exist_ok=False, pretrained=True, optimizer=auto, verbose=True, seed=0, deterministic=True, single_cls=False, rect=False, cos_lr=False, close_mosaic=10, resume=False, amp=True, fraction=1.0, profile=False, overlap_mask=True, mask_ratio=4, dropout=0.0, val=True, split=val, save_json=False, save_hybrid=False, conf=None, iou=0.7, max_det=300, half=False, dnn=False, plots=True, source=None, show=False, save_txt=False, save_conf=False, save_crop=False, show_labels=True, show_conf=True, vid_stride=1, line_width=None, visualize=False, augment=False, agnostic_nms=False, classes=None, retina_masks=False, boxes=True, format=torchscript, keras=False, optimize=False, int8=False, dynamic=False, simplify=False, opset=None, workspace=4, nms=False, lr0=0.01, lrf=0.01, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=7.5, cls=0.5, dfl=1.5, pose=12.0, kobj=1.0, label_smoothing=0.0, nbs=64, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, mosaic=1.0, mixup=0.0, copy_paste=0.0, cfg=None, tracker=botsort.yaml, save_dir=runs/detect/train\n",
            "\n",
            "                   from  n    params  module                                       arguments                     \n",
            "  0                  -1  1       464  ultralytics.nn.modules.conv.Conv             [3, 16, 3, 2]                 \n",
            "  1                  -1  1      4672  ultralytics.nn.modules.conv.Conv             [16, 32, 3, 2]                \n",
            "  2                  -1  1      7360  ultralytics.nn.modules.block.C2f             [32, 32, 1, True]             \n",
            "  3                  -1  1     18560  ultralytics.nn.modules.conv.Conv             [32, 64, 3, 2]                \n",
            "  4                  -1  2     49664  ultralytics.nn.modules.block.C2f             [64, 64, 2, True]             \n",
            "  5                  -1  1     73984  ultralytics.nn.modules.conv.Conv             [64, 128, 3, 2]               \n",
            "  6                  -1  2    197632  ultralytics.nn.modules.block.C2f             [128, 128, 2, True]           \n",
            "  7                  -1  1    295424  ultralytics.nn.modules.conv.Conv             [128, 256, 3, 2]              \n",
            "  8                  -1  1    460288  ultralytics.nn.modules.block.C2f             [256, 256, 1, True]           \n",
            "  9                  -1  1    164608  ultralytics.nn.modules.block.SPPF            [256, 256, 5]                 \n",
            " 10                  -1  1         0  torch.nn.modules.upsampling.Upsample         [None, 2, 'nearest']          \n",
            " 11             [-1, 6]  1         0  ultralytics.nn.modules.conv.Concat           [1]                           \n",
            " 12                  -1  1    148224  ultralytics.nn.modules.block.C2f             [384, 128, 1]                 \n",
            " 13                  -1  1         0  torch.nn.modules.upsampling.Upsample         [None, 2, 'nearest']          \n",
            " 14             [-1, 4]  1         0  ultralytics.nn.modules.conv.Concat           [1]                           \n",
            " 15                  -1  1     37248  ultralytics.nn.modules.block.C2f             [192, 64, 1]                  \n",
            " 16                  -1  1     36992  ultralytics.nn.modules.conv.Conv             [64, 64, 3, 2]                \n",
            " 17            [-1, 12]  1         0  ultralytics.nn.modules.conv.Concat           [1]                           \n",
            " 18                  -1  1    123648  ultralytics.nn.modules.block.C2f             [192, 128, 1]                 \n",
            " 19                  -1  1    147712  ultralytics.nn.modules.conv.Conv             [128, 128, 3, 2]              \n",
            " 20             [-1, 9]  1         0  ultralytics.nn.modules.conv.Concat           [1]                           \n",
            " 21                  -1  1    493056  ultralytics.nn.modules.block.C2f             [384, 256, 1]                 \n",
            " 22        [15, 18, 21]  1    897664  ultralytics.nn.modules.head.Detect           [80, [64, 128, 256]]          \n",
            "Model summary: 225 layers, 3157200 parameters, 3157184 gradients\n",
            "\n",
            "Transferred 355/355 items from pretrained weights\n",
            "\u001b[34m\u001b[1mTensorBoard: \u001b[0mStart with 'tensorboard --logdir runs/detect/train', view at http://localhost:6006/\n",
            "\u001b[34m\u001b[1mAMP: \u001b[0mrunning Automatic Mixed Precision (AMP) checks with YOLOv8n...\n",
            "\u001b[34m\u001b[1mAMP: \u001b[0mchecks passed ✅\n",
            "\u001b[34m\u001b[1mtrain: \u001b[0mScanning /content/datasets/coco8/labels/train... 4 images, 0 backgrounds, 0 corrupt: 100% 4/4 [00:00<00:00, 860.11it/s]\n",
            "\u001b[34m\u001b[1mtrain: \u001b[0mNew cache created: /content/datasets/coco8/labels/train.cache\n",
            "\u001b[34m\u001b[1malbumentations: \u001b[0mBlur(p=0.01, blur_limit=(3, 7)), MedianBlur(p=0.01, blur_limit=(3, 7)), ToGray(p=0.01), CLAHE(p=0.01, clip_limit=(1, 4.0), tile_grid_size=(8, 8))\n",
            "\u001b[34m\u001b[1mval: \u001b[0mScanning /content/datasets/coco8/labels/val.cache... 4 images, 0 backgrounds, 0 corrupt: 100% 4/4 [00:00<?, ?it/s]\n",
            "Plotting labels to runs/detect/train/labels.jpg... \n",
            "\u001b[34m\u001b[1moptimizer:\u001b[0m AdamW(lr=0.000119, momentum=0.9) with parameter groups 57 weight(decay=0.0), 64 weight(decay=0.0005), 63 bias(decay=0.0)\n",
            "Image sizes 640 train, 640 val\n",
            "Using 2 dataloader workers\n",
            "Logging results to \u001b[1mruns/detect/train\u001b[0m\n",
            "Starting training for 3 epochs...\n",
            "\n",
            "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
            "        1/3     0.761G     0.9273      3.155      1.291         32        640: 100% 1/1 [00:01<00:00,  1.23s/it]\n",
            "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100% 1/1 [00:00<00:00,  2.21it/s]\n",
            "                   all          4         17      0.613      0.899      0.888      0.621\n",
            "\n",
            "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
            "        2/3      0.78G      1.161      3.126      1.517         33        640: 100% 1/1 [00:00<00:00,  9.06it/s]\n",
            "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100% 1/1 [00:00<00:00,  7.18it/s]\n",
            "                   all          4         17      0.601      0.896      0.888      0.613\n",
            "\n",
            "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
            "        3/3     0.757G     0.9264      2.508      1.254         17        640: 100% 1/1 [00:00<00:00,  7.32it/s]\n",
            "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100% 1/1 [00:00<00:00,  5.26it/s]\n",
            "                   all          4         17      0.598      0.892      0.886      0.613\n",
            "\n",
            "3 epochs completed in 0.003 hours.\n",
            "Optimizer stripped from runs/detect/train/weights/last.pt, 6.5MB\n",
            "Optimizer stripped from runs/detect/train/weights/best.pt, 6.5MB\n",
            "\n",
            "Validating runs/detect/train/weights/best.pt...\n",
            "Ultralytics YOLOv8.0.145 🚀 Python-3.10.6 torch-2.0.1+cu118 CUDA:0 (Tesla T4, 15102MiB)\n",
            "Model summary (fused): 168 layers, 3151904 parameters, 0 gradients\n",
            "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100% 1/1 [00:00<00:00, 16.58it/s]\n",
            "                   all          4         17      0.613      0.898      0.888      0.621\n",
            "                person          4         10      0.661        0.5       0.52      0.285\n",
            "                   dog          4          1      0.337          1      0.995      0.597\n",
            "                 horse          4          2      0.723          1      0.995      0.631\n",
            "              elephant          4          2      0.629      0.886      0.828      0.319\n",
            "              umbrella          4          1       0.55          1      0.995      0.995\n",
            "          potted plant          4          1      0.776          1      0.995      0.895\n",
            "Speed: 0.2ms preprocess, 4.6ms inference, 0.0ms loss, 1.1ms postprocess per image\n",
            "Results saved to \u001b[1mruns/detect/train\u001b[0m\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 4. Export\n",
        "\n",
        "Export a YOLOv8 model to any supported format below with the `format` argument, i.e. `format=onnx`. See [YOLOv8 Export Docs](https://docs.ultralytics.com/modes/export/) for more information.\n",
        "\n",
        "- 💡 ProTip: Export to [ONNX](https://onnx.ai/) or [OpenVINO](https://docs.openvino.ai/latest/index.html) for up to 3x CPU speedup.  \n",
        "- 💡 ProTip: Export to [TensorRT](https://developer.nvidia.com/tensorrt) for up to 5x GPU speedup.\n",
        "\n",
        "\n",
        "| Format                                                             | `format` Argument | Model                     | Metadata | Arguments                                           |\n",
        "|--------------------------------------------------------------------|-------------------|---------------------------|----------|-----------------------------------------------------|\n",
        "| [PyTorch](https://pytorch.org/)                                    | -                 | `yolov8n.pt`              | ✅        | -                                                   |\n",
        "| [TorchScript](https://pytorch.org/docs/stable/jit.html)            | `torchscript`     | `yolov8n.torchscript`     | ✅        | `imgsz`, `optimize`                                 |\n",
        "| [ONNX](https://onnx.ai/)                                           | `onnx`            | `yolov8n.onnx`            | ✅        | `imgsz`, `half`, `dynamic`, `simplify`, `opset`     |\n",
        "| [OpenVINO](https://docs.openvino.ai/latest/index.html)             | `openvino`        | `yolov8n_openvino_model/` | ✅        | `imgsz`, `half`, `int8`                             |\n",
        "| [TensorRT](https://developer.nvidia.com/tensorrt)                  | `engine`          | `yolov8n.engine`          | ✅        | `imgsz`, `half`, `dynamic`, `simplify`, `workspace` |\n",
        "| [CoreML](https://github.com/apple/coremltools)                     | `coreml`          | `yolov8n.mlpackage`       | ✅        | `imgsz`, `half`, `int8`, `nms`                      |\n",
        "| [TF SavedModel](https://www.tensorflow.org/guide/saved_model)      | `saved_model`     | `yolov8n_saved_model/`    | ✅        | `imgsz`, `keras`, `int8`                            |\n",
        "| [TF GraphDef](https://www.tensorflow.org/api_docs/python/tf/Graph) | `pb`              | `yolov8n.pb`              | ❌        | `imgsz`                                             |\n",
        "| [TF Lite](https://www.tensorflow.org/lite)                         | `tflite`          | `yolov8n.tflite`          | ✅        | `imgsz`, `half`, `int8`                             |\n",
        "| [TF Edge TPU](https://coral.ai/docs/edgetpu/models-intro/)         | `edgetpu`         | `yolov8n_edgetpu.tflite`  | ✅        | `imgsz`                                             |\n",
        "| [TF.js](https://www.tensorflow.org/js)                             | `tfjs`            | `yolov8n_web_model/`      | ✅        | `imgsz`                                             |\n",
        "| [PaddlePaddle](https://github.com/PaddlePaddle)                    | `paddle`          | `yolov8n_paddle_model/`   | ✅        | `imgsz`                                             |\n",
        "| [ncnn](https://github.com/Tencent/ncnn)                            | `ncnn`            | `yolov8n_ncnn_model/`     | ✅        | `imgsz`, `half`                                     |\n"
      ],
      "metadata": {
        "id": "nPZZeNrLCQG6"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!yolo export model=yolov8n.pt format=torchscript"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "CYIjW4igCjqD",
        "outputId": "2b65e381-717b-4a6f-d6f5-5254c867f3a4"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Ultralytics YOLOv8.0.145 🚀 Python-3.10.6 torch-2.0.1+cu118 CPU (Intel Xeon 2.30GHz)\n",
            "YOLOv8n summary (fused): 168 layers, 3151904 parameters, 0 gradients\n",
            "\n",
            "\u001b[34m\u001b[1mPyTorch:\u001b[0m starting from 'yolov8n.pt' with input shape (1, 3, 640, 640) BCHW and output shape(s) (1, 84, 8400) (6.2 MB)\n",
            "\n",
            "\u001b[34m\u001b[1mTorchScript:\u001b[0m starting export with torch 2.0.1+cu118...\n",
            "\u001b[34m\u001b[1mTorchScript:\u001b[0m export success ✅ 2.8s, saved as 'yolov8n.torchscript' (12.4 MB)\n",
            "\n",
            "Export complete (4.6s)\n",
            "Results saved to \u001b[1m/content\u001b[0m\n",
            "Predict:         yolo predict task=detect model=yolov8n.torchscript imgsz=640 \n",
            "Validate:        yolo val task=detect model=yolov8n.torchscript imgsz=640 data=None \n",
            "Visualize:       https://netron.app\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 5. Python Usage\n",
        "\n",
        "YOLOv8 was reimagined using Python-first principles for the most seamless Python YOLO experience yet. YOLOv8 models can be loaded from a trained checkpoint or created from scratch. Then methods are used to train, val, predict, and export the model. See detailed Python usage examples in the [YOLOv8 Python Docs](https://docs.ultralytics.com/usage/python/)."
      ],
      "metadata": {
        "id": "kUMOQ0OeDBJG"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from ultralytics import YOLO\n",
        "\n",
        "# Load a model\n",
        "model = YOLO('yolov8n.yaml')  # build a new model from scratch\n",
        "model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n",
        "\n",
        "# Use the model\n",
        "results = model.train(data='coco128.yaml', epochs=3)  # train the model\n",
        "results = model.val()  # evaluate model performance on the validation set\n",
        "results = model('https://ultralytics.com/images/bus.jpg')  # predict on an image\n",
        "results = model.export(format='onnx')  # export the model to ONNX format"
      ],
      "metadata": {
        "id": "bpF9-vS_DAaf"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 6. Tasks\n",
        "\n",
        "YOLOv8 can train, val, predict and export models for the most common tasks in vision AI: [Detect](https://docs.ultralytics.com/tasks/detect/), [Segment](https://docs.ultralytics.com/tasks/segment/), [Classify](https://docs.ultralytics.com/tasks/classify/) and [Pose](https://docs.ultralytics.com/tasks/pose/). See [YOLOv8 Tasks Docs](https://docs.ultralytics.com/tasks/) for more information.\n",
        "\n",
        "<br><img width=\"1024\" src=\"https://raw.githubusercontent.com/ultralytics/assets/main/im/banner-tasks.png\">\n"
      ],
      "metadata": {
        "id": "Phm9ccmOKye5"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 1. Detection\n",
        "\n",
        "YOLOv8 _detection_ models have no suffix and are the default YOLOv8 models, i.e. `yolov8n.pt` and are pretrained on COCO. See [Detection Docs](https://docs.ultralytics.com/tasks/detect/) for full details.\n"
      ],
      "metadata": {
        "id": "yq26lwpYK1lq"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Load YOLOv8n, train it on COCO128 for 3 epochs and predict an image with it\n",
        "from ultralytics import YOLO\n",
        "\n",
        "model = YOLO('yolov8n.pt')  # load a pretrained YOLOv8n detection model\n",
        "model.train(data='coco128.yaml', epochs=3)  # train the model\n",
        "model('https://ultralytics.com/images/bus.jpg')  # predict on an image"
      ],
      "metadata": {
        "id": "8Go5qqS9LbC5"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 2. Segmentation\n",
        "\n",
        "YOLOv8 _segmentation_ models use the `-seg` suffix, i.e. `yolov8n-seg.pt` and are pretrained on COCO. See [Segmentation Docs](https://docs.ultralytics.com/tasks/segment/) for full details.\n"
      ],
      "metadata": {
        "id": "7ZW58jUzK66B"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Load YOLOv8n-seg, train it on COCO128-seg for 3 epochs and predict an image with it\n",
        "from ultralytics import YOLO\n",
        "\n",
        "model = YOLO('yolov8n-seg.pt')  # load a pretrained YOLOv8n segmentation model\n",
        "model.train(data='coco128-seg.yaml', epochs=3)  # train the model\n",
        "model('https://ultralytics.com/images/bus.jpg')  # predict on an image"
      ],
      "metadata": {
        "id": "WFPJIQl_L5HT"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 3. Classification\n",
        "\n",
        "YOLOv8 _classification_ models use the `-cls` suffix, i.e. `yolov8n-cls.pt` and are pretrained on ImageNet. See [Classification Docs](https://docs.ultralytics.com/tasks/classify/) for full details.\n"
      ],
      "metadata": {
        "id": "ax3p94VNK9zR"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Load YOLOv8n-cls, train it on mnist160 for 3 epochs and predict an image with it\n",
        "from ultralytics import YOLO\n",
        "\n",
        "model = YOLO('yolov8n-cls.pt')  # load a pretrained YOLOv8n classification model\n",
        "model.train(data='mnist160', epochs=3)  # train the model\n",
        "model('https://ultralytics.com/images/bus.jpg')  # predict on an image"
      ],
      "metadata": {
        "id": "5q9Zu6zlL5rS"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 4. Pose\n",
        "\n",
        "YOLOv8 _pose_ models use the `-pose` suffix, i.e. `yolov8n-pose.pt` and are pretrained on COCO Keypoints. See [Pose Docs](https://docs.ultralytics.com/tasks/pose/) for full details."
      ],
      "metadata": {
        "id": "SpIaFLiO11TG"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Load YOLOv8n-pose, train it on COCO8-pose for 3 epochs and predict an image with it\n",
        "from ultralytics import YOLO\n",
        "\n",
        "model = YOLO('yolov8n-pose.pt')  # load a pretrained YOLOv8n classification model\n",
        "model.train(data='coco8-pose.yaml', epochs=3)  # train the model\n",
        "model('https://ultralytics.com/images/bus.jpg')  # predict on an image"
      ],
      "metadata": {
        "id": "si4aKFNg19vX"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "IEijrePND_2I"
      },
      "source": [
        "# Appendix\n",
        "\n",
        "Additional content below."
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Pip install from source\n",
        "!pip install git+https://github.com/ultralytics/ultralytics@main"
      ],
      "metadata": {
        "id": "pIdE6i8C3LYp"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Git clone and run tests on updates branch\n",
        "!git clone https://github.com/ultralytics/ultralytics -b main\n",
        "%pip install -qe ultralytics"
      ],
      "metadata": {
        "id": "uRKlwxSJdhd1"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Run tests (Git clone only)\n",
        "!pytest ultralytics/tests"
      ],
      "metadata": {
        "id": "GtPlh7mcCGZX"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Validate multiple models\n",
        "for x in 'nsmlx':\n",
        "  !yolo val model=yolov8{x}.pt data=coco.yaml"
      ],
      "metadata": {
        "id": "Wdc6t_bfzDDk"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}
