Sub topic 2
Defining Classes and a Label Taxonomy
This chapter assumes you can read basic Python, know what a JSON file is, and have a general idea of how supervised training works. You should also have read the previous chapter on task types, because the choice between detection, instance segmentation and panoptic segmentation affects how many classes you need and how precisely each one must be defined.
Why the taxonomy comes first
A class taxonomy is the list of categories annotators may assign, together with a written definition of each one and the relationships between them. You settle it before anyone draws a box. Changing it later is expensive, because every existing label may need to be re-examined.
A model learns whatever distinctions your labels contain. If two annotators disagree about whether a pickup truck is a "car" or a "truck", the model receives contradictory examples. It cannot resolve that disagreement for you. Most "the model is bad at X" problems in labelled datasets come from classes that were never defined sharply enough, not from the model architecture.
A good taxonomy has three parts:
- Class names: short, unique identifiers such as
carortraffic_sign. - Definitions: one or two sentences stating what is included and excluded.
- Structure: an optional parent grouping (for example
carandtruckboth undervehicle) and a stable numeric ID for each class.
Classes, attributes and hierarchy
Not every distinction should be a class. Many are better stored as an attribute: extra metadata attached to an annotation without changing its class.
| Distinction | Better as | Reason |
|---|---|---|
| car vs. truck | Class | The model should localise and name them differently |
| Occluded vs. fully visible | Attribute | Same object, different visibility |
| Traffic light colour (red, green) | Attribute, or fine class | Depends on whether the model must output the colour |
| Daytime vs. night | Image-level tag | Describes the scene, not an object |
| Brand of car | Usually neither | Rarely visible enough to label reliably |
A hierarchy lets you label at the finest level you can do reliably and report at a coarser level. Suppose you label sedan, suv and van. You can later merge them into car for a first model without relabelling anything. Going the other direction, splitting car into three types, means revisiting every box. When in doubt, label finer than you think you need, as long as annotators can tell the classes apart consistently.
What makes a class usable
Check each proposed class against these criteria before accepting it.
- Visually distinguishable. A human looking only at the image can tell it from its neighbours. Classes such as "person who is a student" fail this test.
- Mutually exclusive, or explicitly overlapping. For detection, one object normally gets one class. If an object can legitimately carry two labels, say so in the guideline.
- Large enough to see. If most instances are 5 pixels wide at your image resolution, annotators will guess. Set a minimum size below which objects are ignored or flagged.
- Frequent enough. A class with 20 examples will rarely train well. Either collect more data or merge it into a parent.
- Needed by the product. Every class costs annotation time and review time. Drop classes nobody will use.
Writing a class definition
A definition has to settle borderline cases in advance, so it must say more than the name does. A useful template has four fields:
- Includes: what counts, with the main variants.
- Excludes: what looks similar but belongs elsewhere, naming the other class.
- Minimum size or visibility: the threshold below which the object is not labelled.
- Example images: several typical cases and several hard ones.
For car, a weak definition is "a car". A usable one is: "Passenger car, taxi, SUV or van up to 3.5 tonnes, parked or moving. Excludes buses, lorries and motorbikes. Label only if at least 20 pixels tall." The second version lets two people reach the same decision about a delivery van without talking to each other.
Occlusion, truncation and ambiguous cases get their own chapter. At the taxonomy stage, you only need to ensure each class definition points to the shared rules.
Include an explicit "other" and "ignore" policy
Every real image contains objects that fit none of your classes. You need a policy for them, and there are three common ones.
- Leave unlabelled. Simple, but the model learns that such objects are background. If a
forkliftis unlabelled and later becomes a class, old images contain false negatives. - An
otherclass. Annotators box everything unclassifiable. This gives the model a place to put uncertain objects but can become a dumping ground, and its definition is inherently vague. - An ignore region. Annotators mark areas, such as a dense crowd or a blurry distant region, that the training loss should skip. COCO supports this with the
iscrowdflag. Many detectors can also be configured to skip such regions.
Choose one policy per project and write it down. Mixing policies across annotators is a common source of silent inconsistency.
IDs, names and the off-by-one trap
Models and file formats refer to classes by integer ID, not by name. Two conventions collide here:
- YOLO-style text labels use class indices starting at 0.
- COCO category IDs are arbitrary integers, and many datasets, including the example in this tutorial, start at 1. Some tools reserve 0 for background.
If you mix these, every prediction is shifted by one class, and car shows up as truck. The error does not crash anything, which is what makes it dangerous. Keep one master taxonomy file and generate every format-specific mapping from it, instead of typing IDs by hand in several places.
Treat IDs as permanent. Once a dataset version has been released, never reuse an ID for a different meaning. If you retire a class, leave its ID unused.
Encoding the taxonomy as data
Keep the taxonomy in a version-controlled file that both the annotation tool configuration and your training code read. The sketch below stores it as a Python dictionary, validates it, and generates COCO categories and a YOLO names list.
TAXONOMY = {
"version": "1.0.0",
"classes": [
{"id": 0, "name": "car", "parent": "vehicle",
"definition": "Passenger car, taxi, SUV or van up to 3.5 tonnes, parked or moving."},
{"id": 1, "name": "truck", "parent": "vehicle",
"definition": "Lorry or pickup over 3.5 tonnes, including trailers attached to it."},
{"id": 2, "name": "pedestrian", "parent": "person",
"definition": "A person on foot, including those pushing a pram or bicycle."},
],
}
def validate_taxonomy(taxonomy):
problems = []
classes = taxonomy["classes"]
ids = [c["id"] for c in classes]
names = [c["name"] for c in classes]
if len(set(ids)) != len(ids):
problems.append("duplicate class ids")
if len(set(names)) != len(names):
problems.append("duplicate class names")
if sorted(ids) != list(range(len(ids))):
problems.append("ids are not contiguous from 0")
for c in classes:
if len(c.get("definition", "").split()) < 5:
problems.append(f"class {c['name']!r} has no usable definition")
return problems
def to_coco_categories(taxonomy):
# COCO ids start at 1 here, so shift the 0-based ids by one.
return [
{"id": c["id"] + 1, "name": c["name"], "supercategory": c["parent"]}
for c in taxonomy["classes"]
]
def to_yolo_names(taxonomy):
return [c["name"] for c in sorted(taxonomy["classes"], key=lambda c: c["id"])]
print(validate_taxonomy(TAXONOMY))
print(to_coco_categories(TAXONOMY))
print(to_yolo_names(TAXONOMY))Running the script prints an empty list for the validation step, followed by the three COCO categories with IDs 1 to 3, and then ['car', 'truck', 'pedestrian']. Run the validator in your continuous integration or before every export, so a typo in the file is caught before any labels depend on it.
Merging and remapping classes
Taxonomies change. The usual safe operation is a merge, in which fine classes collapse into a coarser one. Do it through an explicit mapping applied to the exported labels, never by editing the raw annotations in place. Keep the original labels so the merge is reversible.
MERGE = {"van": "car", "suv": "car", "taxi": "car"}
KEEP = {"car", "truck", "pedestrian"}
def remap_labels(annotations, merge, keep):
remapped, dropped = [], set()
for ann in annotations:
name = merge.get(ann["label"], ann["label"])
if name in keep:
remapped.append({**ann, "label": name})
else:
dropped.add(ann["label"])
return remapped, dropped
annotations = [
{"label": "van", "bbox": [50, 40, 100, 50]},
{"label": "truck", "bbox": [200, 60, 180, 90]},
{"label": "scooter", "bbox": [10, 10, 30, 40]},
]
result, dropped = remap_labels(annotations, MERGE, KEEP)
print(result)
print(dropped)The van annotation becomes car, truck is unchanged, and scooter is reported in dropped instead of vanishing silently. Always inspect the dropped set. A non-empty set means either your mapping is incomplete or annotators used a label that is not in the taxonomy.
Common errors
- Overlapping classes with no tie-break rule.
busandtruckboth fit a minibus. Add a rule to the definitions naming the winner. - Classes defined by use, not appearance. "Emergency vehicle" depends on context. Define by visible features, such as a light bar and markings, or use an attribute.
- Too many classes at the start. Fifty classes with sparse examples lead to disagreement and weak training. Start with fewer and split later, using the hierarchy.
- Changing definitions mid-project without re-checking. Labels made under the old rule remain in the data. Record a taxonomy version and decide whether old images need review.
- Different ID schemes across tools. See the off-by-one trap above.
- Relying on names alone for the model's output. Evaluation should report per-class results, so you can see which definition is failing.
Versioning the taxonomy
Give the taxonomy a version number and store it with every exported dataset. A simple scheme works well: increment the patch number for wording clarifications, the minor number for added classes, and the major number for merges, splits or changed meanings. When the major number changes, plan a review of any affected labels. This record lets you explain later why two models trained on "the same data" behave differently.
Exercise
A team labels a street dataset with the classes car, van and suv. In review, two annotators disagree on about 30% of the vehicles that look like a small van or large SUV. The product only needs to know whether a vehicle is present. What should the team do to the taxonomy, and why do they not need to relabel the images?
Show answer
Merge the three classes into a single car class through an explicit mapping applied at export (for example {"van": "car", "suv": "car"}). The distinction is not visually reliable, and the product does not need it, so keeping it only adds noise. The original fine labels stay in the raw annotations, so the merge is reversible and no images need relabelling. The team should bump the taxonomy's major version and record the mapping.
Exercise
A converter writes YOLO label files using the COCO category IDs 1, 2 and 3 for car, truck and pedestrian. The training config lists the names as [car, truck, pedestrian]. What goes wrong, and how do you prevent it?
Show answer
YOLO expects 0-based indices, so ID 1 is read as truck, ID 2 as pedestrian, and ID 3 is out of range. Cars are mislabelled as trucks and pedestrians as the wrong class. Prevent it by generating every format's IDs from one master taxonomy file (COCO IDs as id + 1, YOLO as id), and by running a validation step that checks every label's class index is within the range of the names list.