Datasets and labelling
UAT 306 Artificial Intelligence for UAS
Lesson
By the end of this module you will be able to
- Write labelling guidelines that make different annotators agree
- Measure annotator agreement with Cohen's kappa and box IoU
- Split a dataset by flight while keeping class proportions similar
- Check the dataset before training for leakage and wrong labels
- Turn IMU and telemetry logs into windows and physics-based features for a model
Why this matters
A model learns only what the data and labels support, and random splits of images from similar flights tend to give over-optimistic scores. This module takes up two questions: how trustworthy are the labels, and how to split by flight while keeping class proportions similar.
Labelling guidelines
If two annotators label the same image differently, the model learns that confusion too. Good guidelines define each class with images of what does and does not belong, the smallest object to label, how to draw boxes (tight to the object, with or without shadow), and what to do when unsure.
Example 1 How well do two annotators agree?
Two annotators classify 100 image patches as crack, none or stain, and draw boxes for the same three cracks (simulated data). Cohen’s kappa (Cohen, 1960) removes the agreement expected by chance.
a = ["crack"] * 40 + ["none"] * 50 + ["stain"] * 10
b = ["crack"] * 34 + ["none"] * 6 + ["none"] * 44 + ["crack"] * 4 + ["stain"] * 2 + ["stain"] * 8 + ["none"] * 2
n = len(a)
labels = sorted(set(a) | set(b))
po = sum(x == y for x, y in zip(a, b)) / n
pe = sum((a.count(c) / n) * (b.count(c) / n) for c in labels)
print(f"observed agreement {po:.2f}, chance agreement {pe:.2f}, kappa {(po - pe) / (1 - pe):.2f}")
def iou(p, q): # box (x1, y1, x2, y2) in pixels
ix = max(0, min(p[2], q[2]) - max(p[0], q[0]))
iy = max(0, min(p[3], q[3]) - max(p[1], q[1]))
inter = ix * iy
union = (p[2] - p[0]) * (p[3] - p[1]) + (q[2] - q[0]) * (q[3] - q[1]) - inter
return inter / union
pairs = [((100, 100, 200, 160), (104, 98, 206, 158)), ((50, 50, 90, 80), (60, 55, 110, 85)),
((300, 200, 340, 260), (330, 240, 380, 300))]
for k, (p, q) in enumerate(pairs, 1):
print(f"box {k}: IoU between annotators {iou(p, q):.2f}")
observed agreement 0.86, chance agreement 0.42, kappa 0.76
box 1: IoU between annotators 0.85
box 2: IoU between annotators 0.38
box 3: IoU between annotators 0.04
Agreement of 86% looks high, but after removing chance agreement, kappa is about 0.76 (kappa of 1 means agreement on every image, and 0 means agreement no better than chance). Boxes 2 and 3 have low IoU, meaning the annotators understood the extent of the crack differently. Revise the guidelines on drawing boxes before labelling the rest.
Splitting by flight while keeping class proportions
Images from the same flight are very similar and must stay in the same split as a whole (a group split). But splitting by flight alone can give some splits unusually few or many cracks. scikit-learn provides StratifiedGroupKFold, which keeps both groups and class proportions; this example writes a simple version of the idea to show the mechanism.
Example 2 Splitting 12 flights into train, validation and test
Each flight has a different number of images and proportion of images with cracks (simulated data). Sort the flights by crack rate, then deal them into splits with the repeating pattern train, train, validation, train, train, test.
flights = {"F01": (118, 0.138), "F02": (135, 0.245), "F03": (137, 0.160), "F04": (66, 0.107),
"F05": (110, 0.060), "F06": (124, 0.220), "F07": (77, 0.228), "F08": (103, 0.130),
"F09": (131, 0.201), "F10": (94, 0.246), "F11": (134, 0.243), "F12": (89, 0.234)} # images, crack rate
pattern = ["train", "train", "val", "train", "train", "test"]
split = {"train": [], "val": [], "test": []}
for i, f in enumerate(sorted(flights, key=lambda k: flights[k][1])):
split[pattern[i % len(pattern)]].append(f)
total = sum(n for n, _ in flights.values())
for name, fs in split.items():
imgs = sum(flights[f][0] for f in fs)
cracks = sum(flights[f][0] * flights[f][1] for f in fs)
print(f"{name:<5} flights {', '.join(fs):<32} images {imgs:>4} ({imgs / total:.0%}), crack rate {cracks / imgs:.3f}")
assert not (set(split["train"]) & set(split["test"]))
train flights F05, F04, F01, F03, F06, F07, F11, F02 images 901 (68%), crack rate 0.180
val flights F08, F12 images 192 (15%), crack rate 0.178
test flights F09, F10 images 225 (17%), crack rate 0.220
Train and validation have very similar crack rates, test is slightly higher, and no flight is in both train and test. With few flights, the split is coarse, so neither image shares nor class rates hit their targets exactly. In practice, collect data from many flights and sites, and record in the dataset documentation how the split was made.
Checking the dataset before training
The minimum checklist is: duplicate or near-duplicate images across splits, boxes outside the image or with zero size, images without labels that should have them, class proportions in each split, and image usage rights.
Sensor and telemetry data
Images are not the only data a drone produces. The flight controller logs the inertial measurement unit (IMU: accelerometers and gyroscopes) hundreds of times per second, together with telemetry such as battery voltage and current, motor outputs, GNSS position and its accuracy. These are time series: values ordered in time, where a single sample means little and the pattern over a stretch of time carries the information. The usual recipe for machine learning on time series has three steps:
- Windowing: cut the signal into windows of fixed length (for example 1 second), each window becoming one example with one label.
- Feature extraction: summarise each window with a few numbers chosen from physics, such as the standard deviation (overall vibration level), the energy in a frequency band from the Fourier transform, or the mean current.
- Model and evaluation: train a classifier or regression model on the features, splitting by flight exactly as for images, because neighbouring and overlapping windows from one flight are almost identical.
ArduPilot’s documentation on measuring vibration uses the same idea: its VIBE log message records the standard deviation of the accelerometer output, and levels below 30 m/s/s are normally acceptable while levels above 60 m/s/s nearly always cause problems with position or altitude hold. PX4’s guidance on vibration lists unbalanced propellers among the first causes to check.
Example 3 Detecting a chipped propeller from IMU vibration
One-second windows of vertical acceleration at 400 samples per second, from hovers with sound propellers and with a chipped propeller spinning at 95 revolutions per second (simulated data, assumed values). A chipped blade shakes the frame once per revolution. We compare two features: the overall standard deviation, and the share of vibration energy within 5 Hz of the rotor frequency.
import numpy as np
rng = np.random.default_rng(4)
FS = 400 # accelerometer samples per second (assumed)
t = np.arange(FS) / FS # one 1-second window
ROTOR_HZ = 95 # propeller rotation rate in hover (assumed)
def window(damaged):
a = rng.normal(0, 6, FS) # normal vibration, m/s^2
if damaged: # once-per-revolution shake from a chipped propeller
a += rng.uniform(35, 50) * np.sin(2 * np.pi * ROTOR_HZ * t + rng.uniform(0, 2 * np.pi))
return a
def features(a):
power = np.abs(np.fft.rfft(a - a.mean())) ** 2
freq = np.fft.rfftfreq(len(a), 1 / FS)
band = np.abs(freq - ROTOR_HZ) <= 5 # energy near the rotor frequency
return a.std(), power[band].sum() / power.sum()
for name, dmg in (("normal", False), ("chipped prop", True)):
std, share = features(window(dmg))
print(f"{name:<12} one window: std {std:5.1f} m/s^2, energy share near {ROTOR_HZ} Hz {share:.2f}")
normal = np.array([features(window(False)) for _ in range(50)])
damaged = np.array([features(window(True)) for _ in range(50)])
for label, col, limit in (("std > 30 m/s^2", 0, 30.0), ("rotor-band share > 0.5", 1, 0.5)):
print(f"rule {label:<22}: flags normal {(normal[:, col] > limit).sum():>2}/50, "
f"chipped prop {(damaged[:, col] > limit).sum():>2}/50")
normal one window: std 6.1 m/s^2, energy share near 95 Hz 0.04
chipped prop one window: std 35.9 m/s^2, energy share near 95 Hz 0.97
rule std > 30 m/s^2 : flags normal 0/50, chipped prop 25/50
rule rotor-band share > 0.5: flags normal 0/50, chipped prop 50/50
The overall vibration level catches only half of the damaged windows, because a moderate imbalance can stay under the 30 m/s/s guideline while still being abnormal. The energy share at the rotor frequency separates the two groups completely, because it measures the physical signature of the fault rather than the total shaking. This is the main lesson of sensor data: good features come from understanding the physics, and the model that uses them can be as simple as a threshold. In real logs, windows from one flight must stay in one split, and the rotor frequency changes with throttle, so the band must follow the motor speed recorded in the log.
Module lab
Lab: a trustworthy dataset
- Write one page of labelling guidelines for cracks, with images of what does and does not count
- Have two classmates label the same 50 images in CVAT, and compute kappa and IoU with Example 1
- Revise the guidelines where they disagree, relabel and measure again
- Split the dataset by flight with Example 2 or
StratifiedGroupKFoldand report class proportions - Check the dataset against the minimum checklist and write the dataset documentation
- Optional extension outside class: export the IMU (or VIBE) messages from one of your own flight logs, cut them into 1-second windows and compute both features of Example 3
Common mistakes
Watch out
- Labelling without guidelines and hoping the model will sort it out
- Reporting raw agreement without removing chance
- Splitting randomly by image when images from the same flight are similar
- Splitting by flight without checking class proportions
- Not recording image usage rights
- Splitting sensor windows randomly, so overlapping windows from one flight end up in both train and test
Summary
- Clear labelling guidelines make labels consistent, and label consistency caps model accuracy
- Cohen’s kappa removes chance agreement; IoU measures box agreement
- Split by flight or site and keep class proportions similar in every split
- Check the dataset before every training run and record it in the dataset documentation
- IMU and telemetry are time series: cut them into windows, extract features from physics, and split by flight
Check your understanding
- With = 0.9 and = 0.5, what is kappa?
- What is the IoU of boxes (0,0,10,10) and (5,0,15,10)?
- Why might 90% agreement still not be good enough?
- Why split by flight?
- Why is the energy near the rotor frequency a better feature than overall vibration for finding a chipped propeller?
Answers
- An overlap of 50 over a union of 150, so
- If one class is very common, high agreement can arise by chance; look at kappa
- Images from the same flight are very similar; if they end up in both train and test, scores look better than they are
- It measures the once-per-revolution signature of the fault itself, so it separates damaged from sound propellers even when the total vibration is still below the guideline
Key formulas
| Cohen's kappa | |
| IoU of two boxes |
Key references
- Cohen, J. (1960). A coefficient of agreement for nominal scales. Educational and Psychological Measurement, 20(1), 37–46. link
- scikit-learn developers. Cross-validation: Evaluating estimator performance (scikit-learn 1.9). link
- Géron, A. (2022). Hands-on machine learning with Scikit-Learn, Keras, and TensorFlow (3rd ed.). O'Reilly.
- ArduPilot Dev Team. Measuring vibration. ArduPilot Copter documentation. link
- PX4 Autopilot. Vibration isolation. PX4 user guide (main). link
Further reading
Study the assigned knowledge units in advance, review media and take the module quiz
Preparing and splitting datasets
Checking datasets before AI training
CVAT Community
In class / field
Lecture, case discussion and in-class problem solving
Learning evidence: Quiz results and submitted exercises