Self-Driving Cars
Topic 24 · Part 6: Modern perception (advanced) · ⏱ about 4 h

Real Datasets, Transfer Learning and mAP

Move from the simulator to real roads: the public driving datasets (KITTI, BDD100K, nuScenes, Waymo), measuring a detector properly with average precision and COCO mAP, and why starting from a pretrained network beats training from scratch. Fine-tune a pretrained YOLO on your recordings, then on KITTI.

Softmaxima Simulator StudioWrite your car in Python, with as many files and trained networks as it needs, and watch it drive. In your browser, nothing to install.Open
Show:
In this topic
Beginner

In plain words

A simulator makes perfect labels for free; real roads do not. Researchers compare methods on a few famous real datasets, with one agreed score. And instead of training from nothing, they start from a network that has already seen millions of photos, which is like hiring an experienced driver instead of teaching someone who has never seen a road.

By the end of this topic you will be able to name the main driving datasets, score a detector the way research papers do, and fine-tune a pretrained detector.

Start with: the demo Try it: the precision–recall curve of your detector.

Beginner

Why real data changes everything

Everything so far was trained on our simulator, where labels are free and perfect. Real roads are messier: thousands of kinds of car, glare, dirt on the lens, people half hidden behind each other, labels drawn by hand and sometimes wrong. Every published result in self-driving perception is measured on a handful of public datasets, so a researcher or engineer must know them:

DatasetWhat it hasGood for
KITTI (2012)about 15,000 labelled frames from Karlsruhe, Germany: camera, stereo, lidar, GPSthe classic benchmark for 2D/3D detection, stereo and depth; small enough to train on in Colab
BDD100K (2018–20)100,000 videos from US cities, day and night, all weathers; boxes, lanes, drivable area, segmentationcamera-only perception with real variety
nuScenes (2019)1,000 scenes from Boston and Singapore: 6 cameras, lidar, 5 radars, full 3D labels and mapsmulti-camera, lidar, fusion and prediction
Waymo Open (2019–)thousands of scenes with high-quality lidar and cameras, and a huge motion-prediction set3D detection and motion prediction at scale

All of them are free for research and learning, after a registration. Their licences usually forbid commercial use: check before you build a product on one.

Beginner

Measuring a detector properly: average precision

In Part 2 we reported precision and recall at one confidence threshold. But the threshold is a choice, so research papers report a number that covers every threshold:

  1. Sort all detections from the whole test set by confidence, highest first.
  2. Walk down the list. Each detection is a hit if it overlaps an unmatched true object of the same class by at least the IoU threshold; otherwise it is a false alarm. After each one, write down precision and recall so far: this traces the precision–recall curve.
  3. Average precision (AP) is the area under that curve (COCO samples it at 101 recall levels, after making precision never increase).

mAP is the mean of AP over classes. [email protected] counts a box as right if IoU ≥ 0.5; COCO mAP (written [email protected]:0.95) averages over IoU thresholds from 0.50 to 0.95, so it also rewards boxes that fit tightly. When papers say "mAP" without saying which, it is usually the COCO one.

Try it

Try it: the precision–recall curve of your detector

The example detector from Part 2 runs on 80 frames it has never seen, keeping every box above 5% confidence. Then slide the IoU threshold: at 0.5 the car AP is decent, at 0.75 it collapses. Our grid detector finds the cars but its boxes are loose. That is exactly what COCO mAP was designed to expose.

Interactive: this part runs in your browser.

Beginner

Going deeper

The sections marked Intermediate · Maths, Code or Advanced go deeper: the equations, the code and the finer details. They are worth it when you are ready, but you can follow the whole idea without them. To hide them, press those buttons next to Show at the top of the page; the Beginner explanations and Try it demos stay.

Code

Code: average precision, step by step

This runs in your browser, on a tiny hand-made test set, so you can check every number by hand.

Python · NumPy
import numpy as np

def iou(a, b):
    ix = max(0, min(a[2], b[2]) - max(a[0], b[0]))
    iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
    inter = ix * iy
    return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)

def average_precision(dets, truths, iou_thr=0.5):
    """dets: [(image, score, box)], truths: [(image, box)], one class. COCO-style AP (101 recall points)."""
    dets = sorted(dets, key=lambda d: -d[1])                  # most confident first
    used, tp, fp, curve = set(), 0, 0, []
    for img, score, box in dets:
        cands = [(iou(box, t[1]), k) for k, t in enumerate(truths) if t[0] == img and k not in used]
        best = max(cands, default=(0, None))
        if best[0] >= iou_thr:
            used.add(best[1])
            tp += 1
        else:
            fp += 1
        curve.append((tp / len(truths), tp / (tp + fp)))       # (recall, precision) after this detection
    recall, precision = np.array(curve).T
    precision = np.maximum.accumulate(precision[::-1])[::-1]   # make precision non-increasing
    levels = np.linspace(0, 1, 101)
    idx = np.searchsorted(recall, levels, side="left")         # first point that reaches each recall level
    return np.mean([precision[i] if i < len(precision) else 0.0 for i in idx])

# A tiny test set: 3 images with 4 cars, and a detector's 6 guesses with their confidence.
truths = [(0, [10, 10, 50, 40]), (0, [60, 12, 90, 40]), (1, [20, 20, 70, 60]), (2, [5, 5, 30, 30])]
dets = [(0, 0.95, [12, 11, 52, 41]),   # a good box
        (1, 0.90, [22, 18, 68, 62]),   # a good box
        (0, 0.80, [70, 20, 110, 50]),  # misplaced: overlaps the 2nd car only a little
        (2, 0.60, [6, 4, 31, 29]),     # a good box
        (1, 0.40, [100, 100, 120, 120]),  # nothing there
        (0, 0.30, [61, 13, 91, 42])]   # finds the 2nd car, but with low confidence

for thr in (0.5, 0.75, 0.9):
    print(f"AP at IoU {thr}: {average_precision(dets, truths, thr):.3f}")
coco = np.mean([average_precision(dets, truths, t) for t in np.arange(0.5, 0.96, 0.05)])
print(f"COCO AP (IoU 0.50 to 0.95): {coco:.3f}")
Open in playground ↗
Beginner

Transfer learning: do not start from zero

Our networks in Part 2 started from random weights. In practice almost nobody does that. Networks pretrained on large photo datasets (ImageNet, COCO) have already learned edges, textures, wheels and people. Fine-tuning one on your data, with a small learning rate, needs far less data and time, and usually ends far better, especially for the rare classes. This is transfer learning.

The detectors used most in practice are the YOLO family (from Ultralytics and others), DETR-style transformers (RT-DETR, D-FINE) and, in large companies, their own designs. Libraries such as Ultralytics, MMDetection and Hugging Face make fine-tuning one a few lines of code. Your job as an engineer is then mostly the data and the evaluation, not the network.

Code

Code: your recordings in the YOLO format

Record two or more datasets at 240 × 120 in Recording a labelled dataset. This turns them into the format most detection libraries read.

Python (Colab)
# In Google Colab. Upload two or more recordings from the course (the last one is kept for validation).
# This writes them in the YOLO format that most detection libraries use: one image file and one text file per image.
from google.colab import files
import os
import numpy as np
from PIL import Image

names = list(files.upload())
assert len(names) >= 2, "Upload at least two recordings: the last one is kept for validation."
CLASSES = ["car", "pedestrian", "traffic light"]

def write(split, recording, start):
    d = np.load(recording)
    os.makedirs(f"sim/images/{split}", exist_ok=True)
    os.makedirs(f"sim/labels/{split}", exist_ok=True)
    H, W = d["images"].shape[1:3]
    for f, img in enumerate(d["images"]):
        name = f"{start + f:06d}"
        Image.fromarray(img).save(f"sim/images/{split}/{name}.png")
        with open(f"sim/labels/{split}/{name}.txt", "w") as fh:
            for _, cls, x1, y1, x2, y2, _ in d["boxes"][d["boxes"][:, 0] == f]:
                if y2 - y1 < 4:
                    continue                          # too small to learn from
                # YOLO format: class, then the box centre and size as fractions of the image
                fh.write(f"{cls} {(x1 + x2) / 2 / W:.6f} {(y1 + y2) / 2 / H:.6f} {(x2 - x1) / W:.6f} {(y2 - y1) / H:.6f}\n")
    return start + len(d["images"])

n = 0
for r in names[:-1]:
    n = write("train", r, n)
write("val", names[-1], n)
with open("sim.yaml", "w") as fh:
    fh.write(f"path: {os.path.abspath('sim')}\ntrain: images/train\nval: images/val\nnames: {dict(enumerate(CLASSES))}\n")
print(open("sim.yaml").read())
print(len(os.listdir("sim/images/train")), "training images,", len(os.listdir("sim/images/val")), "validation images")
This code needs Google Colab (it uploads the dataset file you recorded), which cannot run inside a web page. To run it, press Copy, then paste it into a new notebook in Google Colab ↗ (free; Runtime → Change runtime type → GPU for deep learning).
Code

Code: from scratch against pretrained

The same small YOLO, trained twice on the same data. Compare the COCO mAP of the two, and especially the pedestrian AP: the class with the fewest examples gains most from pretraining.

Python (Colab)
# Train the same small YOLO twice on your simulator data: once from random weights, once starting from weights
# pretrained on COCO (a large photo dataset). Same data, same number of epochs. Runtime: GPU (Runtime > Change runtime type).
!pip install -q ultralytics
from ultralytics import YOLO

results = {}
for name, start in [("from scratch", "yolo11n.yaml"),          # the architecture only: random weights
                    ("pretrained", "yolo11n.pt")]:            # weights learned on COCO's 118,000 photos
    model = YOLO(start)
    model.train(data="sim.yaml", epochs=30, imgsz=256, batch=64, project="runs", name=name.replace(" ", "_"), verbose=False)
    m = model.val(data="sim.yaml", imgsz=256)
    results[name] = m
    print(f"{name}: [email protected] = {m.box.map50:.3f}, COCO [email protected]:0.95 = {m.box.map:.3f}")
    for i, c in enumerate(["car", "pedestrian", "traffic light"]):
        print(f"   {c:>13}: [email protected]:0.95 = {m.box.maps[i]:.3f}")
This code needs Ultralytics, which cannot run inside a web page. To run it, press Copy, then paste it into a new notebook in Google Colab ↗ (free; Runtime → Change runtime type → GPU for deep learning).
Code

Code: fine-tune on KITTI, real roads

Now real photos. KITTI needs a free registration. The images are 1242 × 375, so this uses a 640-pixel input; 20 epochs take roughly an hour on a free Colab GPU.

Python (Colab)
# Fine-tune the pretrained YOLO on KITTI, real photos from a car driving around Karlsruhe, Germany.
# 1. Register (free) at https://www.cvlibs.net/datasets/kitti/eval_object.php?obj_benchmark=2d and download
#    "left color images of object data set" (12 GB) and "training labels of object data set" (5 MB).
# 2. Upload both zip files to your Google Drive, in a folder called kitti. Then run this cell.
#    KITTI's licence (CC BY-NC-SA 3.0) allows non-commercial use such as learning.
from google.colab import drive
import os
import random
import zipfile
from PIL import Image

drive.mount("/content/drive")
for z in ["data_object_image_2.zip", "data_object_label_2.zip"]:
    zipfile.ZipFile(f"/content/drive/MyDrive/kitti/{z}").extractall("kitti_raw")

KEEP = {"Car": 0, "Van": 0, "Pedestrian": 1, "Person_sitting": 1, "Cyclist": 2}   # three classes; trucks, trams and "DontCare" are left out
ids = sorted(f[:-4] for f in os.listdir("kitti_raw/training/label_2"))
random.seed(0)
random.shuffle(ids)
for split, part in [("val", ids[:1000]), ("train", ids[1000:])]:
    os.makedirs(f"kitti/images/{split}", exist_ok=True)
    os.makedirs(f"kitti/labels/{split}", exist_ok=True)
    for i in part:
        src = f"kitti_raw/training/image_2/{i}.png"
        W, H = Image.open(src).size
        os.symlink(os.path.abspath(src), f"kitti/images/{split}/{i}.png")
        with open(f"kitti/labels/{split}/{i}.txt", "w") as out:
            for line in open(f"kitti_raw/training/label_2/{i}.txt"):
                p = line.split()                     # type, truncated, occluded, alpha, x1, y1, x2, y2, 3D size, 3D position, rotation
                if p[0] in KEEP:
                    x1, y1, x2, y2 = map(float, p[4:8])
                    out.write(f"{KEEP[p[0]]} {(x1 + x2) / 2 / W:.6f} {(y1 + y2) / 2 / H:.6f} {(x2 - x1) / W:.6f} {(y2 - y1) / H:.6f}\n")
with open("kitti.yaml", "w") as fh:
    fh.write(f"path: {os.path.abspath('kitti')}\ntrain: images/train\nval: images/val\nnames: {{0: car, 1: pedestrian, 2: cyclist}}\n")

!pip install -q ultralytics
from ultralytics import YOLO
model = YOLO("yolo11n.pt")
model.train(data="kitti.yaml", epochs=20, imgsz=640, batch=32, project="runs", name="kitti")
m = model.val(data="kitti.yaml")
print(f"KITTI validation: [email protected] = {m.box.map50:.3f}, [email protected]:0.95 = {m.box.map:.3f}")
for i, c in enumerate(["car", "pedestrian", "cyclist"]):
    print(f"   {c:>10}: [email protected]:0.95 = {m.box.maps[i]:.3f}")
model.predict("kitti/images/val", max_det=50, save=True, project="runs", name="kitti_predictions")   # pictures with boxes drawn
model.export(format="onnx")                  # a portable file for C++, mobile and embedded inference engines
This code needs Google Colab (it uploads the dataset file you recorded), which cannot run inside a web page. To run it, press Copy, then paste it into a new notebook in Google Colab ↗ (free; Runtime → Change runtime type → GPU for deep learning).

Things to try: train on day images and test on night ones (KITTI has none, BDD100K has many), or train on your simulator data and test on KITTI. The drop you see is the domain gap, measured.

Check yourself

Quiz

1. What does COCO mAP ([email protected]:0.95) reward that [email protected] does not?

2. Why is average precision better than precision at one threshold?

3. Why does a pretrained network usually beat one trained from scratch on a small dataset?

4. Which dataset would you choose to study fusing six cameras with lidar?

Go deeper

📚 Further reading

Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.

Ready