Semantic segmentation: FCN, DeepLab and PSPNet
Label every pixel: fully convolutional networks and upsampling, DeepLab's atrous convolutions that see wide without shrinking, PSPNet's pooled context, ignored pixels, and why mean IoU beats pixel accuracy. DeepLabV3 runs in CodeSplash.
What runs in CodeSplash
- VIS010Fully Convolutional Network for semantic segmentation (FCN) Explained here
- VIS011DeepLab family Runs in CodeSplash (Experimental)
- VIS012Pyramid Scene Parsing Network (PSPNet) Explained here
- Semantic segmentation (DeepLabV3, 20 classes) Experimental
- Segmentation quality (IoU, Dice, segment F1) Experimental
You will be able to
- Explain how a fully convolutional network outputs a class per pixel
- Compute the span of a dilated kernel
- Describe what pyramid pooling adds to each pixel's features
- Score a segmentation with mean IoU and say why pixel accuracy misleads
A class for every pixel
ReadSemantic segmentationSemantic segmentationGiving every pixel a class (person, cat, sofa…) or background; objects of one class merge into one region. gives every pixel a class: road, car, person, sky. It doesn't separate instances: two touching cars are one "car" region. That makes it the right tool for areas (how much of the field is weeds?) and the wrong one for counts.
The output is an image-sized map of class scores. The difficulty is resolution: classification networks shrink the image to learn what is there, and segmentation needs to say exactly where.
FCN: convolutions all the way
ReadA fully convolutional networkFully convolutional network (FCN)A CNN with no dense layers, so it takes any image size and outputs a class score for every pixel after upsampling. replaces a classifier's dense layers with convolutions, so it accepts any image size and outputs a coarse grid of class scores. Upsampling (bilinear or a transposed convolutionTransposed convolutionAn upsampling layer that spreads each input value through a kernel; with stride not dividing kernel size, overlaps make checkerboards.) brings the grid back to full size, and skip connections add detail from earlier, finer layers.
Border pixels are often marked voidIgnore label (void pixels)Pixels marked as unknown, such as object borders, that are left out of both the loss and the score. and left out of the loss. In the program a coarse 2 × 2 score map is upsampled to 4 × 4 and refined; 1 pixel is ignored and the loss over the rest is 0.332.
DeepLab: see wide, stay sharp
ReadDeepLab keeps feature maps large by not downsampling, and widens the view with atrous convolutionAtrous (dilated) convolutionA convolution whose kernel taps are spread apart, so it sees a wider area with the same number of weights.: the kernel's taps are spread apart. A 3-tap kernel with dilation d spans 2d + 1 inputs with the same 3 weights.
In the program the kernel 1-2-1 slides over 9 values. Undilated it spans 3 inputs and gives 7 outputs; with dilation 2 it spans 5 and gives 5. Later versions run several dilation rates side by side (atrous spatial pyramid pooling) to catch objects of different sizes.
How far can it see?
PredictPredict first
A 3-tap kernel uses dilation 4. How many inputs does it span, end to end?
Reveal
9: 2 × 4 + 1. It still has only 3 weights and reads 3 of those 9 inputs; the gaps are why stacking the same rate repeatedly can leave a checkerboard of unseen pixels.
PSPNet: add the whole scene
ReadA pixel of water could be a lake or a swimming pool; the scene around it decides. Pyramid poolingPyramid poolingAveraging features over the whole image and over coarser grids, then upsampling and stacking them as extra context. averages the features over the whole image and over coarser grids, upsamples each back and stacks them beside every pixel's own features.
The program pools a 4 × 4 grid holding 0 to 15: the global average is 7.50, the four 2 × 2 bins average 2.50, 4.50, 10.5 and 12.5. Each pixel ends with 3 channels: itself, the scene and its quarter.
DeepLabV3 in CodeSplash
In the appSemantic segmentation runs a pretrained DeepLabV3 that knows 20 everyday classes plus background, and reports each class's share of the pixels:
3 classes found in 3 of 5 images; background covers 55.9% of an image on average.
- Images
- 5
- Classes found
- 3
- Regions
- 3
- Background
- 55.9%
Plots
View data
| Height (px) | Image | Class | Mask (COCO RLE) | Media id | Mean confidence | Width (px) | x0 | x1 | y0 | y1 |
|---|---|---|---|---|---|---|---|---|---|---|
| 160 | cat.png | cat | Q2o2Q200000O100O1O1O1O1N2O1M3N2YOg0H8N2K5LThg0IWXXO1O0000000000O]V1NbiN9I3N3L4M2L5L3XN]OnNg0o0AgNe0V1@`Ng0]1a1M2M4^NQMm0b3N3L3N3J7J;G2M3MSk4 | 0eaeb6793ad08de630a090bbf7b187aa30acbc292e63d298d3ff0338cec02a50 | 0.9664 | 240 | 0 | 209 | 0 | 160 |
| 160 | cup.png | diningtable | W1i3W100000O1O10000O1O100O100O1O100O1O100O100O1O1O1O1O100O1O100N200O100N200O1O100O1O1O1O100O1O100O1O1O1O100O10PRm0 | 0f2f46f52111cb7dc1a71df8df67fa7af376bf66c5304888c767b881a4c9c6a6 | 0.9413 | 240 | 0 | 240 | 0 | 160 |
| 192 | astronaut.png | person | iR14c0O\4T1H3L4B?I8I4K5O1N2M3O1N2M300N2O1N2O1M3O1N2N2O100N2O100O1O100O1O1O1O100N2O1N2O1N2O1N2N2N200N2O100O100O1QOQLLP41ULMk31ZLLf32^LLb32aLM_33bLL^33eLJ\35fLI[36hLGY39W100O1O1O100O1O100O1000000O100000000O100000000001O0000001O0000001O1hKO_21aM0^21`M1_2O_M5_2K_M7a2J]M8b2I[M:d2GZM:f2FZM;e2HVM<h2DWM>h2DUM>j2EPM`0n2DlL?S3EfL`0X3X1L1O2N1SOXM`Nh2^1[MaNf2\1\MdNd2Y1bMRNF;i2`1lMZNX2d1S1M4N2M3L4M4M3L3N3N3J5N2M5J3N2M]P: | f37291cf2c47100683468e90bd3810c1f03d64d8eb9c51f8972c9160a9de5d22 | 0.9392 | 192 | 5 | 138 | 7 | 192 |
| 150 | shapes.png | — | — | fb6409af86ab2ef69eff6ef058e1227929f5a75ad407435a729a370097b2578c | — | 200 | — | — | — | — |
| 48 | flat.png | — | — | 81d0ef9f87003b2a8f4726bd99d84744e070a37fc2ba0a63f1537fd951587a11 | — | 64 | — | — | — | — |
View data
| Class |
|---|
| cat |
| diningtable |
| person |
Assumptions
- 20 Pascal VOC classes — Pixels of anything outside the 20 classes become background or the nearest class.
- One class per pixel — Overlapping objects of the same class merge into one region; use instance segmentation to count objects.
- Labeled at the segmentation size — Classes are decided with the short side at 256 px and enlarged to each image by nearest neighbor.
- Photos like COCO's — The model learned from everyday photos; other kinds of images need a model trained on them.
Classes
| Class | Images | Mean share of pixels | Mean confidence |
|---|---|---|---|
| cat | 1 | 15.9% | 0.9664 |
| diningtable | 1 | 19.4% | 0.9413 |
| person | 1 | 8.8% | 0.9392 |
Classes per image
| Row | File | Regions | Classes | Background |
|---|---|---|---|---|
| 1 | cat.png | 1 | cat | 20.3% |
| 2 | cup.png | 1 | diningtable | 3.2% |
| 3 | astronaut.png | 1 | person | 55.9% |
| 4 | shapes.png | 0 | 100.0% | |
| 5 | flat.png | 0 | 100.0% |
- 1 rows have no path and are left out.
- 1 files could not be decoded and are left out.
The exact R script · R R version 4.5.1 (2025-06-13)
# Semantic segmentation (DeepLabV3, 20 classes)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method segment.semantic 1.0.0 · spec fd2703dc572f68f7
# Dataset: img3_photos (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
ARCH <- "deeplabv3_resnet50"
# %% Images listed in the path column
PATH <- "path"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img3_photos.parquet", col_select = PATH))
if (!nrow(df)) cs_error("CS_E_NO_ROWS")
warnings <- character(0)
# %% Media files (image column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
media <- cs_media_setup(jsonlite::fromJSON("{\"ids_column\":\"media_id\",\"kind\":\"image\",\"path_column\":\"path\",\"role\":\"image\",\"transform\":{\"filter\":\"triangle\",\"fit\":\"within\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[1333,1333]}}", simplifyVector = FALSE), "target/academy-parity/run-8142/segment.semantic/defaults_small/out-r", df,
"tests/parity/fixtures/img3_photos.parquet")
media_ids <- cs_media_ids(media, df)
text_ <- function(v) { v <- as.character(v); v[!is.na(v) & !nzchar(v)] <- NA_character_; v }
paths_ <- text_(df[[PATH]])
has_id <- which(!is.na(media_ids) & !is.na(paths_))
if (!length(has_id)) cs_error("CS_E_ALL_MISSING", column = PATH)
status_ <- cs_media_status(media, media_ids[has_id])
ok <- has_id[is.na(status_)]
n_no_path <- nrow(df) - length(has_id)
n_unreadable <- length(has_id) - length(ok)
if (!length(ok)) cs_error("CS_E_INVALID_VALUES", column = PATH, requirement = "an image file that can be decoded", count = length(has_id))
if (n_no_path) warnings <- c(warnings, sprintf("%d rows have no path and are left out.", n_no_path))
if (n_unreadable) warnings <- c(warnings, sprintf("%d files could not be decoded and are left out.", n_unreadable))
items <- lapply(ok, function(k) list(media_id = media_ids[k], file = basename(paths_[k]), row = k - 1L))
# One decoded image (3, h, w) on 0-1 and its size before decoding (orientation applied).
load_image <- function(mid) {
a <- cs_media_load(media, mid)
list(image = array(a, dim = dim(a)[-1]), size = cs_media_source_size(media, mid)[[1]])
}
# %% Pretrained model and compute profile
cs_deep_profile_configure(list(profile = "parity"))
cs_deep_torch()
model <- cs_vis_load(ARCH, dtype = cs_deep_profile_current()$dtype)
# %% Label every pixel (torchvision DeepLabV3 on the converted weights, 20 Pascal VOC classes)
SIZE <- 256
CLASSES <- unlist(c())
run <- cs_vis_segment_images(model, items, load_image, size = SIZE, classes = CLASSES, min_share = 0)
table <- run$table
s <- cs_vis_summarize(table, run$images, semantic = TRUE)
values <- c(list(n_rows = nrow(df), n_no_path = n_no_path, n_unreadable = n_unreadable), s$values,
list(model = cs_vis_model_info(ARCH)$label, size = SIZE))
# %% Artifacts: one row per image and class (mask as COCO RLE) and one row per image
out <- cs_ml_out_dir("target/academy-parity/run-8142/segment.semantic/defaults_small/out-r")
cs_boxes_write(table, file.path(out, "boxes.parquet"))
per <- data.frame(row = vapply(run$images, function(r) r$row + 1L, 0L),
media_id = vapply(run$images, function(r) r$media_id, ""),
file = vapply(run$images, function(r) r$file, ""),
width = vapply(run$images, function(r) r$width, 0L),
height = vapply(run$images, function(r) r$height, 0L),
regions = vapply(run$images, function(r) as.integer(r$objects), 0L),
background = vapply(run$images, function(r) r$background, 0), stringsAsFactors = FALSE)
nanoparquet::write_parquet(per, file.path(out, "images.parquet"))
# %% Result
ov <- cs_vis_overlay_columns(table, run$images)
charts <- list(cs_chart("overlay", "image-overlay", "Class masks", list(
image = cs_col("Image", ov$image, "categorical"),
media_id = cs_col("Media id", ov$media_id, "categorical"),
x0 = cs_col("x0", ov$x0, "numeric"), y0 = cs_col("y0", ov$y0, "numeric"),
x1 = cs_col("x1", ov$x1, "numeric"), y1 = cs_col("y1", ov$y1, "numeric"),
label = cs_col("Class", ov$label, "categorical"),
score = cs_col("Mean confidence", ov$score, "numeric"),
mask = cs_col("Mask (COCO RLE)", ov$mask, "categorical"),
width = cs_col("Width (px)", ov$width, "numeric"), height = cs_col("Height (px)", ov$height, "numeric")
), controls = list(boxes = FALSE)))
if (nrow(table)) {
charts[[length(charts) + 1L]] <- cs_chart("classes", "bar", "Images showing each class", list(
x = cs_col("Class", as.character(table$label), "categorical", s$order)))
}
assumptions <- c(list(
list(key = "voc_classes", label = "20 Pascal VOC classes", status = "info",
detail = "Pixels of anything outside the 20 classes become background or the nearest class."),
list(key = "one_label", label = "One class per pixel", status = "info",
detail = "Overlapping objects of the same class merge into one region; use instance segmentation to count objects."),
list(key = "resolution", label = "Labeled at the segmentation size", status = "info",
detail = sprintf("Classes are decided with the short side at %d px and enlarged to each image by nearest neighbor.", as.integer(SIZE))),
list(key = "domain", label = "Photos like COCO's", status = "info",
detail = "The model learned from everyday photos; other kinds of images need a model trained on them.")
), cs_deep_profile_warning_rows())
image_cols <- list(list(key = "row", label = "Row", type = "integer"), list(key = "file", label = "File"),
list(key = "objects", label = "Regions", type = "integer"), list(key = "classes", label = "Classes"),
list(key = "background", label = "Background", type = "percent"))
class_cols <- list(list(key = "class", label = "Class"), list(key = "images", label = "Images", type = "integer"),
list(key = "pixel_share", label = "Mean share of pixels", type = "percent"),
list(key = "mean_score", label = "Mean confidence", type = "number"))
cs_publish(list(
title = "Semantic segmentation (DeepLabV3, 20 classes)",
engine = cs_engine_info("torch", "torchvision", "safetensors", "nanoparquet", "codesplashr"),
n = values$n_images,
summary = sprintf("%d classes found in %d of %d images; background covers %.1f%% of an image on average.",
values$n_classes, values$n_images_with_objects, values$n_images, values$background_mean * 100),
statistics = list(
list(key = "n_images", label = "Images", value = values$n_images, format = "integer"),
list(key = "n_classes", label = "Classes found", value = values$n_classes, format = "integer"),
list(key = "n_objects", label = "Regions", value = values$n_objects, format = "integer"),
list(key = "background_mean", label = "Background", value = values$background_mean, format = "percent")
),
tables = list(
list(key = "classes", title = "Classes", columns = class_cols, rows = s$classes),
list(key = "images", title = "Classes per image", columns = image_cols, rows = s$images[seq_len(min(200L, length(s$images)))])
),
assumptions = assumptions,
charts = charts,
values = values,
warnings = as.list(warnings),
artifacts = list(list(key = "boxes", path = file.path(out, "boxes.parquet"), format = "parquet"),
list(key = "images", path = file.path(out, "images.parquet"), format = "parquet"))
))
3 classes found in 3 of 5 images; background covers 55.9% of an image on average.
- Images
- 5
- Classes found
- 3
- Regions
- 3
- Background
- 55.9%
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- 20 Pascal VOC classes — Pixels of anything outside the 20 classes become background or the nearest class.
- One class per pixel — Overlapping objects of the same class merge into one region; use instance segmentation to count objects.
- Labeled at the segmentation size — Classes are decided with the short side at 256 px and enlarged to each image by nearest neighbor.
- Photos like COCO's — The model learned from everyday photos; other kinds of images need a model trained on them.
Classes
| Class | Images | Mean share of pixels | Mean confidence |
|---|---|---|---|
| cat | 1 | 15.9% | 0.9664 |
| diningtable | 1 | 19.4% | 0.9413 |
| person | 1 | 8.8% | 0.9392 |
Classes per image
| Row | File | Regions | Classes | Background |
|---|---|---|---|---|
| 1 | cat.png | 1 | cat | 20.3% |
| 2 | cup.png | 1 | diningtable | 3.2% |
| 3 | astronaut.png | 1 | person | 55.9% |
| 4 | shapes.png | 0 | 100.0% | |
| 5 | flat.png | 0 | 100.0% |
- 1 rows have no path and are left out.
- 1 files could not be decoded and are left out.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Semantic segmentation (DeepLabV3, 20 classes)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method segment.semantic 1.0.0 · spec fd2703dc572f68f7
# Dataset: img3_photos (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import media as cs_media
from codesplash import ml as csml
from codesplash.deep import core as cs_core
from codesplash.deep import profile as cs_profile
from codesplash.vision import boxes as vbox
from codesplash.vision import detect as vdet
ARCH = "deeplabv3_resnet50"
# %% Images listed in the path column
PATH = "path"
df = pd.read_parquet("tests/parity/fixtures/img3_photos.parquet", columns=[PATH])
if not len(df):
cs.cs_error("CS_E_NO_ROWS")
warnings = []
# %% Media files (image column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
import json as _media_json
from codesplash import media as cs_media
media = cs_media.setup(_media_json.loads("{\"ids_column\":\"media_id\",\"kind\":\"image\",\"path_column\":\"path\",\"role\":\"image\",\"transform\":{\"filter\":\"triangle\",\"fit\":\"within\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[1333,1333]}}"), "target/academy-parity/run-8142/segment.semantic/defaults_small/out-python", df, "tests/parity/fixtures/img3_photos.parquet")
media_ids = cs_media.ids_of(media, df)
def _text(v):
return None if pd.isna(v) else str(v) # None, NaN, pd.NA
has_id = [k for k, m in enumerate(media_ids) if m is not None and _text(df[PATH].iloc[k]) not in (None, "")]
if not has_id:
cs.cs_error("CS_E_ALL_MISSING", column=PATH)
_status = cs_media.status(media, [media_ids[k] for k in has_id])
ok = [k for k, s in zip(has_id, _status) if s is None]
n_no_path = len(df) - len(has_id)
n_unreadable = len(has_id) - len(ok)
if not ok:
cs.cs_error("CS_E_INVALID_VALUES", column=PATH, requirement="an image file that can be decoded", count=len(has_id))
if n_no_path:
warnings.append(f"{n_no_path} rows have no path and are left out.")
if n_unreadable:
warnings.append(f"{n_unreadable} files could not be decoded and are left out.")
items = [{"media_id": media_ids[k], "file": os.path.basename(str(df[PATH].iloc[k])), "row": k} for k in ok]
def load_image(mid):
"""One decoded image (3, h, w) on 0–1 and its size before decoding (orientation applied)."""
return cs_media.load(media, [mid])[0], tuple(cs_media.source_size(media, [mid])[0])
# %% Pretrained model and compute profile
cs_profile.configure({"profile": "parity"})
cs_core.torch_init()
model = vdet.load(ARCH, dtype=cs_profile.current().dtype)
# %% Label every pixel (torchvision DeepLabV3 on the converted weights, 20 Pascal VOC classes)
SIZE = 256
CLASSES = [] or None
run = vdet.segment_images(model, items, load_image, size=SIZE, classes=CLASSES, min_share=0)
table = run["table"]
s = vdet.summarize(table, run["images"], semantic=True)
values = {"n_rows": len(df), "n_no_path": n_no_path, "n_unreadable": n_unreadable, **s["values"],
"model": vdet.MODELS[ARCH]["label"], "size": SIZE}
# %% Artifacts: one row per image and class (mask as COCO RLE) and one row per image
out = csml.out_dir("target/academy-parity/run-8142/segment.semantic/defaults_small/out-python")
vbox.write(table, os.path.join(out, "boxes.parquet"))
per = pd.DataFrame([{"row": r["row"] + 1, "media_id": r["media_id"], "file": r["file"], "width": r["width"],
"height": r["height"], "regions": r["objects"], "background": r["background"]} for r in run["images"]],
columns=["row", "media_id", "file", "width", "height", "regions", "background"])
per.to_parquet(os.path.join(out, "images.parquet"), index=False)
# %% Result
ov = vdet.overlay_columns(table, run["images"])
charts = [cs.chart("overlay", "image-overlay", "Class masks", {
"image": cs.col("Image", ov["image"], "categorical"),
"media_id": cs.col("Media id", ov["media_id"], "categorical"),
"x0": cs.col("x0", ov["x0"], "numeric"), "y0": cs.col("y0", ov["y0"], "numeric"),
"x1": cs.col("x1", ov["x1"], "numeric"), "y1": cs.col("y1", ov["y1"], "numeric"),
"label": cs.col("Class", ov["label"], "categorical"),
"score": cs.col("Mean confidence", ov["score"], "numeric"),
"mask": cs.col("Mask (COCO RLE)", ov["mask"], "categorical"),
"width": cs.col("Width (px)", ov["width"], "numeric"), "height": cs.col("Height (px)", ov["height"], "numeric"),
}, controls={"boxes": False})]
if len(table):
charts.append(cs.chart("classes", "bar", "Images showing each class", {
"x": cs.col("Class", [str(v) for v in table["label"].tolist()], "categorical", s["order"])}))
assumptions = [
{"key": "voc_classes", "label": "20 Pascal VOC classes", "status": "info",
"detail": "Pixels of anything outside the 20 classes become background or the nearest class."},
{"key": "one_label", "label": "One class per pixel", "status": "info",
"detail": "Overlapping objects of the same class merge into one region; use instance segmentation to count objects."},
{"key": "resolution", "label": "Labeled at the segmentation size", "status": "info",
"detail": f"Classes are decided with the short side at {SIZE} px and enlarged to each image by nearest neighbor."},
{"key": "domain", "label": "Photos like COCO's", "status": "info",
"detail": "The model learned from everyday photos; other kinds of images need a model trained on them."},
] + cs_profile.warning_rows()
image_cols = [{"key": "row", "label": "Row", "type": "integer"}, {"key": "file", "label": "File"},
{"key": "objects", "label": "Regions", "type": "integer"}, {"key": "classes", "label": "Classes"},
{"key": "background", "label": "Background", "type": "percent"}]
class_cols = [{"key": "class", "label": "Class"}, {"key": "images", "label": "Images", "type": "integer"},
{"key": "pixel_share", "label": "Mean share of pixels", "type": "percent"},
{"key": "mean_score", "label": "Mean confidence", "type": "number"}]
cs.publish({
"title": "Semantic segmentation (DeepLabV3, 20 classes)",
"engine": cs.engine_info("torch", "torchvision", "numpy", "pandas"),
"n": values["n_images"],
"summary": f"{values['n_classes']} classes found in {values['n_images_with_objects']} of {values['n_images']} images; "
f"background covers {values['background_mean'] * 100:.1f}% of an image on average.",
"statistics": [
{"key": "n_images", "label": "Images", "value": values["n_images"], "format": "integer"},
{"key": "n_classes", "label": "Classes found", "value": values["n_classes"], "format": "integer"},
{"key": "n_objects", "label": "Regions", "value": values["n_objects"], "format": "integer"},
{"key": "background_mean", "label": "Background", "value": values["background_mean"], "format": "percent"},
],
"tables": [
{"key": "classes", "title": "Classes", "columns": class_cols, "rows": s["classes"]},
{"key": "images", "title": "Classes per image", "columns": image_cols, "rows": s["images"][:200]},
],
"assumptions": assumptions,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "boxes", "path": os.path.join(out, "boxes.parquet"), "format": "parquet"},
{"key": "images", "path": os.path.join(out, "images.parquet"), "format": "parquet"}],
})
To score a segmentation against labeled masks, Segmentation quality compares them pixel by pixel:
Across 10 images and 5 classes, mean IoU = 0.495, mean Dice = 0.598 and pixel accuracy = 0.773.
- Mean IoU
- 0.4946
- Mean Dice
- 0.5977
- Pixel accuracy
- 0.7735
Plots
View data
| label | Measure | Overlap |
|---|---|---|
| bicycle | IoU | 0.4855 |
| bicycle | Dice | 0.6537 |
| car | IoU | 0.3877 |
| car | Dice | 0.5588 |
| dog | IoU | 0 |
| dog | Dice | 0 |
| person | IoU | 0.8472 |
| person | Dice | 0.9173 |
| (background) | IoU | 0.7525 |
| (background) | Dice | 0.8588 |
Assumptions
- The reference is complete — Regions or segments missing from the reference turn correct predictions into errors.
- Reference classes don't overlap — Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.
Per class (pixels summed over images)
| label | Reference pixels | Predicted pixels | Overlap (pixels) | IoU | Dice |
|---|---|---|---|---|---|
| bicycle | 9,844 | 14,196 | 7,857 | 0.4855 | 0.6537 |
| car | 59,682 | 26,067 | 23,959 | 0.3877 | 0.5588 |
| dog | 0 | 3,012 | 0 | 0 | 0 |
| person | 33,581 | 30,231 | 29,266 | 0.8472 | 0.9173 |
| (background) | 102,433 | 125,542 | 97,893 | 0.7525 | 0.8588 |
Mean IoU per image
| media_id | Mean IoU |
|---|---|
| img01 | 0.5896 |
| img02 | 0.6133 |
| img03 | 0.3908 |
| img04 | 0.3639 |
| img05 | 0.6776 |
| img06 | 0.6747 |
| img07 | 0.4281 |
| img08 | 0.8811 |
| img09 | 0.4880 |
| img10 | 0.1023 |
- Reference rows: source = annotation; predictions: source = prediction. Masks are compared on their run lengths (no pixels decoded); unlabeled pixels form a background class; crowd regions are left out of scoring.
The exact R script · R R version 4.5.1 (2025-06-13)
# Segmentation quality (IoU, Dice, segment F1)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.segments 1.1.0 · spec a232974b1dc8e926
# Dataset: img4_boxes (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_eval_seg_* (segmentation scores), cs_eval_det_runs, cs_eval_stacked, cs_rle_* (COCO RLE)
# %% Data
GROUP <- "media_id"
FRAME <- NULL
LABEL <- "label"
SOURCE <- "source"
MASK <- "mask_rle"
WIDTH <- "image_width"
HEIGHT <- "image_height"
CROWD <- "iscrowd"
START <- NULL
END <- NULL
SCORE <- NULL
KIND <- "masks" # masks | intervals
BACKGROUND <- TRUE
THRESHOLDS <- as.numeric(unlist(c(0.1, 0.25, 0.5)))
if (!length(THRESHOLDS)) THRESHOLDS <- 0.5
THRESHOLDS <- sort(unique(THRESHOLDS))
REF_LEVEL <- NULL
SOURCE_LEVELS <- c("annotation", "prediction") # stored order
# Reference rows from a second table (option reference_table): its own column for each role, or NULL.
REF_ROLES <- NULL
columns <- unique(c(GROUP, FRAME, LABEL, SOURCE, MASK, WIDTH, HEIGHT, CROWD, START, END, SCORE))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_boxes.parquet", col_select = columns))
if (KIND == "masks" && (is.null(MASK) || is.null(WIDTH) || is.null(HEIGHT))) {
cs_error("CS_E_INVALID_OPTION", option = "Segments are", allowed = "time intervals unless the mask, width and height columns are set", value = "masks")
}
if (KIND == "intervals" && (is.null(START) || is.null(END))) {
cs_error("CS_E_INVALID_OPTION", option = "Segments are", allowed = "masks unless the start and end columns are set", value = "time intervals")
}
pre_warnings <- list()
if (!is.null(REF_ROLES)) {
# The reference table's rows go above this table's rows under an added source column (twin: with_reference).
w <- cs_eval_with_reference(df, cs_graph_dataset_option("target/academy-parity/run-8142/evaluate.segments/masks-background-crowd/out-r", "reference_table"),
list(group = GROUP, frame = FRAME, label = LABEL, mask = MASK, width = WIDTH, height = HEIGHT, crowd = CROWD,
start = START, end = END, score = SCORE), REF_ROLES,
c(list(frame = "Frame"), if (KIND == "masks") list(mask = "Mask", width = "Image width", height = "Image height") else list(start = "Start", end = "End")),
SOURCE, REF_LEVEL, c("group", "label", if (KIND == "masks") c("mask", "width", "height") else c("start", "end")))
df <- w$df
pre_warnings <- w$warnings
wc <- w$columns
GROUP <- wc$group; FRAME <- wc$frame; LABEL <- wc$label; MASK <- wc$mask; WIDTH <- wc$width; HEIGHT <- wc$height
CROWD <- wc$crowd; START <- wc$start; END <- wc$end
SOURCE <- w$source; REF_LEVEL <- w$reference; SOURCE_LEVELS <- w$levels
} else if (is.null(SOURCE)) {
cs_error("CS_E_INVALID_OPTION", option = "Reference table", allowed = "a table of reference rows unless the Reference or prediction column is set", value = "none")
}
needed <- c(GROUP, LABEL, SOURCE, if (KIND == "masks") c(MASK, WIDTH, HEIGHT) else c(START, END))
numeric_cols <- if (KIND == "masks") c(WIDTH, HEIGHT) else c(START, END, SCORE)
st <- cs_eval_stacked(df, needed, numeric_cols, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
if (sum(is_ref) == 0L || sum(!is_ref) == 0L) cs_error("CS_E_GROUP_COUNT", column = SOURCE, expected = 2, k = 1)
labels_all <- as.character(df[[LABEL]])
crowd <- if (!is.null(CROWD) && KIND == "masks") cs_eval_flags(df[[CROWD]]) else logical(nrow(df))
crowd[!is_ref] <- FALSE
classes <- sort(unique(labels_all[!crowd]), method = "radix")
if (KIND == "masks") {
# %% Masks -> runs, per image
ik <- cs_eval_image_keys(df[[GROUP]], if (!is.null(FRAME)) df[[FRAME]] else NULL)
img_idx <- ik$index
ws <- as.numeric(df[[WIDTH]])
hs <- as.numeric(df[[HEIGHT]])
runs <- lapply(seq_len(nrow(df)), function(i) {
tryCatch(cs_eval_det_runs(cs_rle_string_to_counts(as.character(df[[MASK]][i])), as.integer(hs[i]), as.integer(ws[i])),
error = function(e) NULL)
})
n_bad <- sum(vapply(runs, is.null, logical(1)))
if (n_bad > 0) cs_error("CS_E_INVALID_VALUES", column = MASK, requirement = "a COCO RLE string that covers width × height pixels", count = n_bad)
ims <- lapply(seq_along(ik$media), function(i) list(n = NULL, size = NULL, ref = list(), pred = list(), void = list()))
for (i in seq_along(runs)) {
q <- img_idx[i] + 1L
r <- runs[[i]]
if (is.null(ims[[q]]$n)) {
ims[[q]]$n <- as.numeric(r$size[1]) * as.numeric(r$size[2])
ims[[q]]$size <- r$size
} else if (!identical(ims[[q]]$size, r$size)) {
cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", WIDTH, HEIGHT), requirement = "the same size for every mask of an image", count = 1)
}
rr <- list(s = r$s, e = r$e)
if (crowd[i]) {
ims[[q]]$void[[length(ims[[q]]$void) + 1L]] <- rr
} else if (is_ref[i]) {
lab <- labels_all[i]
ims[[q]]$ref[[lab]] <- c(if (is.null(ims[[q]]$ref[[lab]])) list() else ims[[q]]$ref[[lab]], list(rr))
} else {
lab <- labels_all[i]
ims[[q]]$pred[[lab]] <- c(if (is.null(ims[[q]]$pred[[lab]])) list() else ims[[q]]$pred[[lab]], list(rr))
}
}
res <- cs_eval_seg_masks(ims, classes, BACKGROUND)
names_ <- res$classes
n_ref <- sum(is_ref & !crowd)
n_pred <- sum(!is_ref)
unit <- "pixels"
group_rows <- lapply(seq_along(ik$media), function(i) list(group = ik$media[i], frame = if (is.infinite(ik$frame[i])) NA_real_ else ik$frame[i],
miou = if (is.null(res$per_image[[i]])) NA_real_ else res$per_image[[i]]))
n_groups <- length(ik$media)
has_score <- FALSE
} else {
# %% Intervals per recording
s_all <- as.numeric(df[[START]])
e_all <- as.numeric(df[[END]])
bad <- e_all < s_all
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = END, requirement = sprintf("at least %s", START), count = sum(bad))
sc_all <- if (!is.null(SCORE)) as.numeric(df[[SCORE]]) else rep(NA_real_, nrow(df))
has_score <- !is.null(SCORE)
if (has_score) {
miss <- !is_ref & is.na(sc_all)
if (any(miss)) {
warnings <- c(warnings, sprintf("%d predicted segments have no %s and were left out.", sum(miss), SCORE))
keep <- !miss
df <- df[keep, , drop = FALSE]; is_ref <- is_ref[keep]; labels_all <- labels_all[keep]
s_all <- s_all[keep]; e_all <- e_all[keep]; sc_all <- sc_all[keep]
classes <- sort(unique(labels_all), method = "radix")
}
}
grp <- as.character(df[[GROUP]])
groups <- sort(unique(grp), method = "radix")
recs <- lapply(groups, function(g) {
rows <- which(grp == g)
rr <- rows[is_ref[rows]]
pr <- rows[!is_ref[rows]]
list(ref = data.frame(start = s_all[rr], end = e_all[rr], label = labels_all[rr], stringsAsFactors = FALSE),
pred = data.frame(start = s_all[pr], end = e_all[pr], label = labels_all[pr], score = if (has_score) sc_all[pr] else rep(0, length(pr)),
row = pr - 1L, stringsAsFactors = FALSE))
})
res <- cs_eval_seg_intervals(recs, classes, THRESHOLDS, has_score)
names_ <- res$classes
n_ref <- res$n_ref
n_pred <- res$n_pred
unit <- "seconds"
n_groups <- length(groups)
}
# %% Assumptions
assumptions <- list(
list(key = "complete", label = "The reference is complete", status = "info",
detail = "Regions or segments missing from the reference turn correct predictions into errors."),
list(key = "overlap", label = "Reference classes don't overlap", status = "info",
detail = "Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.")
)
# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
tkey <- function(t) sprintf("%g", t)
values <- list(kind = KIND, n_groups = n_groups, n_classes = length(names_), n_reference = n_ref, n_predictions = n_pred,
accuracy = res$accuracy, miou = res$miou, mean_dice = res$mean_dice, fw_iou = res$fw_iou,
scored = if (!is.null(res$scored)) res$scored else sum(res$gsum), ignored = if (!is.null(res$ignored)) res$ignored else NA_real_,
map = NA_real_)
for (j in seq_along(names_)) {
values[[sprintf("iou[%s]", names_[j])]] <- res$iou[j]
values[[sprintf("dice[%s]", names_[j])]] <- res$dice[j]
}
cls_cols <- list(list(key = "class", label = LABEL, type = "string"), list(key = "ref", label = sprintf("Reference %s", unit), type = "number"),
list(key = "pred", label = sprintf("Predicted %s", unit), type = "number"), list(key = "inter", label = sprintf("Overlap (%s)", unit), type = "number"),
list(key = "iou", label = "IoU", type = "number"), list(key = "dice", label = "Dice", type = "number"))
cls_rows <- lapply(seq_along(names_), function(j) list(class = names_[j], ref = res$gsum[j], pred = res$psum[j], inter = res$inter[j],
iou = res$iou[j], dice = res$dice[j]))
tables <- list()
charts <- list()
if (KIND == "intervals") {
m_rows <- res$matching
for (r in m_rows) {
values[[sprintf("f1[%s]", tkey(r$threshold))]] <- r$f1
values[[sprintf("precision[%s]", tkey(r$threshold))]] <- r$precision
values[[sprintf("recall[%s]", tkey(r$threshold))]] <- r$recall
if (has_score) values[[sprintf("ap[%s]", tkey(r$threshold))]] <- r$map
}
if (has_score) {
maps <- vapply(m_rows, function(r) r$map, numeric(1))
maps <- maps[!is.na(maps)]
values$map <- if (length(maps)) mean(maps) else NA_real_
for (r in m_rows) {
key <- sprintf("ap_%s", tkey(r$threshold))
cls_cols[[length(cls_cols) + 1L]] <- list(key = key, label = sprintf("AP@%s", tkey(r$threshold)), type = "number")
for (j in seq_along(cls_rows)) cls_rows[[j]][[key]] <- if (is.null(r$ap[[cls_rows[[j]]$class]])) NA_real_ else r$ap[[cls_rows[[j]]$class]]
}
}
tables[[length(tables) + 1L]] <- list(key = "classes", title = "Per class (time overlap)", columns = cls_cols, rows = cls_rows)
mcols <- list(list(key = "threshold", label = "IoU threshold", type = "number"), list(key = "tp", label = "Matched", type = "integer"),
list(key = "fp", label = "False alarms", type = "integer"), list(key = "fn", label = "Missed", type = "integer"),
list(key = "precision", label = "Precision", type = "number"), list(key = "recall", label = "Recall", type = "number"),
list(key = "f1", label = "F1", type = "number"))
if (has_score) mcols[[length(mcols) + 1L]] <- list(key = "map", label = "mAP", type = "number")
tables[[length(tables) + 1L]] <- list(key = "matching", title = "Segments matched at each IoU threshold", columns = mcols,
rows = lapply(m_rows, function(r) r[c("threshold", "tp", "fp", "fn", "precision", "recall", "f1", "map")]))
pc <- character(0); pm <- character(0); pv <- numeric(0)
for (r in m_rows) for (km in list(c("f1", "F1"), c("precision", "Precision"), c("recall", "Recall"))) if (!is.na(r[[km[1]]])) {
pc <- c(pc, sprintf("IoU %s", tkey(r$threshold))); pm <- c(pm, km[2]); pv <- c(pv, r[[km[1]]])
}
if (length(pv)) {
charts[[length(charts) + 1L]] <- cs_chart("f1-at-iou", "cleveland-dot", "Segment F1, precision and recall by IoU threshold", list(
category = cs_col("IoU threshold", pc, "categorical", levels = vapply(m_rows, function(r) sprintf("IoU %s", tkey(r$threshold)), character(1))),
value = cs_col("Share", pv, "numeric"),
group = cs_col("Measure", pm, "categorical", levels = c("F1", "Precision", "Recall"))))
}
} else {
tables[[length(tables) + 1L]] <- list(key = "classes", title = "Per class (pixels summed over images)", columns = cls_cols, rows = cls_rows)
tables[[length(tables) + 1L]] <- list(key = "images", title = "Mean IoU per image", rows = utils::head(group_rows, 500),
columns = c(list(list(key = "group", label = GROUP, type = "string")), if (!is.null(FRAME)) list(list(key = "frame", label = FRAME, type = "number")),
list(list(key = "miou", label = "Mean IoU", type = "number"))),
note = if (length(group_rows) > 500) "First 500 images." else NULL)
}
dc <- character(0); dm <- character(0); dv <- numeric(0)
for (j in seq_along(names_)) for (km in list(c("iou", "IoU"), c("dice", "Dice"))) if (!is.na(res[[km[1]]][j])) {
dc <- c(dc, names_[j]); dm <- c(dm, km[2]); dv <- c(dv, res[[km[1]]][j])
}
if (length(dv)) {
charts <- c(list(cs_chart("by-class", "cleveland-dot", "IoU and Dice by class", list(
category = cs_col(LABEL, dc, "categorical", levels = names_), value = cs_col("Overlap", dv, "numeric"),
group = cs_col("Measure", dm, "categorical", levels = c("IoU", "Dice"))))), charts)
}
what <- if (KIND == "masks") "pixel accuracy" else "time-weighted accuracy"
summary <- sprintf("Across %d %s and %d classes, mean IoU = %s, mean Dice = %s and %s = %s.", n_groups, if (KIND == "masks") "images" else "recordings",
length(names_), f3(res$miou), f3(res$mean_dice), what, f3(res$accuracy))
if (KIND == "intervals") {
summary <- paste0(summary, " Segment F1: ", paste(vapply(res$matching, function(r) sprintf("%s at IoU %s", f3(r$f1), tkey(r$threshold)), character(1)), collapse = ", "), ".")
if (has_score && !is.na(values$map)) summary <- paste0(summary, sprintf(" mAP over the thresholds = %s.", f3(values$map)))
}
cs_publish(list(
method = "evaluate.segments",
methodVersion = "1.1.0",
title = "Segmentation quality",
engine = cs_engine_info("nanoparquet"),
n = nrow(df),
summary = summary,
statistics = list(list(key = "miou", label = "Mean IoU", value = res$miou), list(key = "mean_dice", label = "Mean Dice", value = res$mean_dice),
list(key = "accuracy", label = if (KIND == "masks") "Pixel accuracy" else "Time-weighted accuracy", value = res$accuracy)),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(if (is.null(REF_ROLES)) sprintf("Reference rows: %s = %s; predictions: %s = %s. ", SOURCE, st$reference, SOURCE, st$prediction)
else "Reference rows come from the reference table; this table's rows are the predictions. ",
if (KIND == "masks") paste0("Masks are compared on their run lengths (no pixels decoded)", if (BACKGROUND) "; unlabeled pixels form a background class" else "",
if (!is.null(CROWD)) "; crowd regions are left out of scoring" else "", ".")
else paste0("Segments match within a recording and class, ", if (!is.null(SCORE)) "highest score first." else "earliest first."))),
charts = charts,
values = values
))
Across 10 images and 5 classes, mean IoU = 0.495, mean Dice = 0.598 and pixel accuracy = 0.773.
- Mean IoU
- 0.4946
- Mean Dice
- 0.5977
- Pixel accuracy
- 0.7735
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- The reference is complete — Regions or segments missing from the reference turn correct predictions into errors.
- Reference classes don't overlap — Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.
Per class (pixels summed over images)
| label | Reference pixels | Predicted pixels | Overlap (pixels) | IoU | Dice |
|---|---|---|---|---|---|
| bicycle | 9,844 | 14,196 | 7,857 | 0.4855 | 0.6537 |
| car | 59,682 | 26,067 | 23,959 | 0.3877 | 0.5588 |
| dog | 0 | 3,012 | 0 | 0 | 0 |
| person | 33,581 | 30,231 | 29,266 | 0.8472 | 0.9173 |
| (background) | 102,433 | 125,542 | 97,893 | 0.7525 | 0.8588 |
Mean IoU per image
| media_id | Mean IoU |
|---|---|
| img01 | 0.5896 |
| img02 | 0.6133 |
| img03 | 0.3908 |
| img04 | 0.3639 |
| img05 | 0.6776 |
| img06 | 0.6747 |
| img07 | 0.4281 |
| img08 | 0.8811 |
| img09 | 0.4880 |
| img10 | 0.1023 |
- Reference rows: source = annotation; predictions: source = prediction. Masks are compared on their run lengths (no pixels decoded); unlabeled pixels form a background class; crowd regions are left out of scoring.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Segmentation quality (IoU, Dice, segment F1)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.segments 1.1.0 · spec a232974b1dc8e926
# Dataset: img4_boxes (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.evaluate import detection as det # RLE runs (twin: cs_eval_det_runs)
from codesplash.evaluate import segmentation as seg # twin: codesplashr cs_eval_seg_*
from codesplash.evaluate.stacked import flags, image_keys, stacked # twin: cs_eval_stacked
from codesplash.vision import boxes as vb # COCO RLE strings (twin: cs_rle_*)
# %% Data
GROUP = "media_id"
FRAME = None
LABEL = "label"
SOURCE = "source"
MASK = "mask_rle"
WIDTH = "image_width"
HEIGHT = "image_height"
CROWD = "iscrowd"
START = None
END = None
SCORE = None
KIND = "masks" # masks | intervals
BACKGROUND = True
THRESHOLDS = [float(t) for t in [0.1, 0.25, 0.5]] or [0.5]
THRESHOLDS = sorted(set(THRESHOLDS))
REF_LEVEL = None
SOURCE_LEVELS = ["annotation", "prediction"] # stored order
# Reference rows from a second table (option reference_table): its own column for each role, or None.
REF_ROLES = None
columns = list(dict.fromkeys(c for c in [GROUP, FRAME, LABEL, SOURCE, MASK, WIDTH, HEIGHT, CROWD, START, END, SCORE] if c))
df = pd.read_parquet("tests/parity/fixtures/img4_boxes.parquet", columns=columns)
if KIND == "masks" and not (MASK and WIDTH and HEIGHT):
cs.cs_error("CS_E_INVALID_OPTION", option="Segments are", allowed="time intervals unless the mask, width and height columns are set", value="masks")
if KIND == "intervals" and not (START and END):
cs.cs_error("CS_E_INVALID_OPTION", option="Segments are", allowed="masks unless the start and end columns are set", value="time intervals")
pre_warnings = []
if REF_ROLES is not None:
# The reference table's rows go above this table's rows under an added source column (twin: cs_eval_with_reference).
from codesplash.graph import dataset_option # the table the host wrote for the option
from codesplash.evaluate.stacked import with_reference
w = with_reference(df, dataset_option("target/academy-parity/run-8142/evaluate.segments/masks-background-crowd/out-python", "reference_table"),
{"group": GROUP, "frame": FRAME, "label": LABEL, "mask": MASK, "width": WIDTH, "height": HEIGHT, "crowd": CROWD,
"start": START, "end": END, "score": SCORE}, REF_ROLES,
{"frame": "Frame", **({"mask": "Mask", "width": "Image width", "height": "Image height"} if KIND == "masks" else {"start": "Start", "end": "End"})},
SOURCE, REF_LEVEL, ["group", "label"] + (["mask", "width", "height"] if KIND == "masks" else ["start", "end"]))
df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
GROUP, FRAME, LABEL, MASK, WIDTH, HEIGHT = wc["group"], wc["frame"], wc["label"], wc["mask"], wc["width"], wc["height"]
CROWD, START, END = wc["crowd"], wc["start"], wc["end"]
SOURCE, REF_LEVEL, SOURCE_LEVELS = w["source"], w["reference"], w["levels"]
elif SOURCE is None:
cs.cs_error("CS_E_INVALID_OPTION", option="Reference table", allowed="a table of reference rows unless the Reference or prediction column is set", value="none")
needed = [GROUP, LABEL, SOURCE] + ([MASK, WIDTH, HEIGHT] if KIND == "masks" else [START, END])
numeric = [WIDTH, HEIGHT] if KIND == "masks" else [c for c in [START, END, SCORE] if c]
st = stacked(df, needed, numeric, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
if int(is_ref.sum()) == 0 or int((~is_ref).sum()) == 0:
cs.cs_error("CS_E_GROUP_COUNT", column=SOURCE, expected=2, k=1)
labels_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object)
crowd = flags(df[CROWD]) if (CROWD and KIND == "masks") else np.zeros(len(df), dtype=bool)
crowd[~is_ref] = False
classes = sorted(set(labels_all[~crowd].tolist()))
if KIND == "masks":
# %% Masks → runs, per image
img_idx, images = image_keys(df[GROUP], df[FRAME] if FRAME else None)
ws, hs = df[WIDTH].to_numpy(dtype=float), df[HEIGHT].to_numpy(dtype=float)
runs, n_bad = [], 0
for s, w, h in zip(df[MASK].tolist(), ws, hs):
try:
runs.append(det.runs_from_counts(vb.string_to_counts(str(s)), int(h), int(w)))
except (ValueError, OverflowError):
runs.append(None)
n_bad += 1
if n_bad:
cs.cs_error("CS_E_INVALID_VALUES", column=MASK, requirement="a COCO RLE string that covers width × height pixels", count=n_bad)
ims = [{"n": None, "ref": {}, "pred": {}, "void": []} for _ in images]
for i, r in enumerate(runs):
im = ims[int(img_idx[i])]
n = float(r[2][0]) * float(r[2][1])
if im["n"] is None:
im["n"], im["size"] = n, r[2]
elif im["size"] != r[2]:
cs.cs_error("CS_E_INVALID_VALUES", column=f"{WIDTH} and {HEIGHT}", requirement="the same size for every mask of an image", count=1)
if crowd[i]:
im["void"].append(r[:2])
else:
side = im["ref"] if is_ref[i] else im["pred"]
side.setdefault(labels_all[i], []).append(r[:2])
res = seg.mask_scores(ims, classes, BACKGROUND)
names = res["classes"]
n_ref = int(np.sum(is_ref & ~crowd))
n_pred = int(np.sum(~is_ref))
unit = "pixels"
group_rows = [{"group": m, "frame": None if f == float("-inf") else f, "miou": res["per_image"][i]} for i, (m, f) in enumerate(images)]
n_groups = len(images)
else:
# %% Intervals per recording
s_all, e_all = df[START].to_numpy(dtype=float), df[END].to_numpy(dtype=float)
bad = e_all < s_all
if bad.any():
cs.cs_error("CS_E_INVALID_VALUES", column=END, requirement=f"at least {START}", count=int(bad.sum()))
sc_all = df[SCORE].to_numpy(dtype=float, na_value=np.nan) if SCORE else np.full(len(df), np.nan)
has_score = SCORE is not None
if has_score:
miss = ~is_ref & np.isnan(sc_all)
if miss.any():
warnings.append(f"{int(miss.sum())} predicted segments have no {SCORE} and were left out.")
keep = ~miss
df, is_ref, labels_all, s_all, e_all, sc_all = df.loc[keep].reset_index(drop=True), is_ref[keep], labels_all[keep], s_all[keep], e_all[keep], sc_all[keep]
classes = sorted(set(labels_all.tolist()))
grp = np.asarray([str(x) for x in df[GROUP].tolist()], dtype=object)
groups = sorted(set(grp.tolist()))
recs = []
for g in groups:
rows = np.flatnonzero(grp == g)
recs.append({"ref": [(s_all[i], e_all[i], labels_all[i]) for i in rows if is_ref[i]],
"pred": [(s_all[i], e_all[i], labels_all[i], float(sc_all[i]) if has_score else 0.0, int(i)) for i in rows if not is_ref[i]]})
res = seg.interval_scores(recs, classes, THRESHOLDS, has_score)
names = res["classes"]
n_ref, n_pred = res["n_ref"], res["n_pred"]
unit = "seconds"
n_groups = len(groups)
# %% Assumptions
assumptions = [
{"key": "complete", "label": "The reference is complete", "status": "info",
"detail": "Regions or segments missing from the reference turn correct predictions into errors."},
{"key": "overlap", "label": "Reference classes don't overlap", "status": "info",
"detail": "Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area."},
]
# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
tkey = lambda t: "%g" % t
values = {"kind": KIND, "n_groups": n_groups, "n_classes": len(names), "n_reference": n_ref, "n_predictions": n_pred,
"accuracy": res["accuracy"], "miou": res["miou"], "mean_dice": res["mean_dice"], "fw_iou": res["fw_iou"],
"scored": res.get("scored", float(np.sum(res["gsum"]))), "ignored": res.get("ignored"), "map": None}
for j, c in enumerate(names):
values[f"iou[{c}]"] = res["iou"][j]
values[f"dice[{c}]"] = res["dice"][j]
cls_cols = [{"key": "class", "label": LABEL, "type": "string"}, {"key": "ref", "label": f"Reference {unit}", "type": "number"},
{"key": "pred", "label": f"Predicted {unit}", "type": "number"}, {"key": "inter", "label": f"Overlap ({unit})", "type": "number"},
{"key": "iou", "label": "IoU", "type": "number"}, {"key": "dice", "label": "Dice", "type": "number"}]
cls_rows = [{"class": c, "ref": float(res["gsum"][j]), "pred": float(res["psum"][j]), "inter": float(res["inter"][j]),
"iou": res["iou"][j], "dice": res["dice"][j]} for j, c in enumerate(names)]
tables = []
charts = []
if KIND == "intervals":
m_rows = res["matching"]
for r in m_rows:
values[f"f1[{tkey(r['threshold'])}]"] = r["f1"]
values[f"precision[{tkey(r['threshold'])}]"] = r["precision"]
values[f"recall[{tkey(r['threshold'])}]"] = r["recall"]
if has_score:
values[f"ap[{tkey(r['threshold'])}]"] = r["map"]
if has_score:
maps = [r["map"] for r in m_rows if r["map"] is not None]
values["map"] = float(np.mean(maps)) if maps else None
for r in m_rows:
cls_cols.append({"key": f"ap_{tkey(r['threshold'])}", "label": f"AP@{tkey(r['threshold'])}", "type": "number"})
for row in cls_rows:
row[f"ap_{tkey(r['threshold'])}"] = r["ap"].get(row["class"])
tables.append({"key": "classes", "title": "Per class (time overlap)", "columns": cls_cols, "rows": cls_rows})
tables.append({"key": "matching", "title": "Segments matched at each IoU threshold",
"columns": [{"key": "threshold", "label": "IoU threshold", "type": "number"}, {"key": "tp", "label": "Matched", "type": "integer"},
{"key": "fp", "label": "False alarms", "type": "integer"}, {"key": "fn", "label": "Missed", "type": "integer"},
{"key": "precision", "label": "Precision", "type": "number"}, {"key": "recall", "label": "Recall", "type": "number"},
{"key": "f1", "label": "F1", "type": "number"}] + ([{"key": "map", "label": "mAP", "type": "number"}] if has_score else []),
"rows": [{k: r[k] for k in ("threshold", "tp", "fp", "fn", "precision", "recall", "f1", "map")} for r in m_rows]})
pts = [(f"IoU {tkey(r['threshold'])}", lab, r[key]) for r in m_rows for key, lab in (("f1", "F1"), ("precision", "Precision"), ("recall", "Recall")) if r[key] is not None]
if pts:
charts.append(cs.chart("f1-at-iou", "cleveland-dot", "Segment F1, precision and recall by IoU threshold", {
"category": cs.col("IoU threshold", [p[0] for p in pts], "categorical", levels=[f"IoU {tkey(r['threshold'])}" for r in m_rows]),
"value": cs.col("Share", [p[2] for p in pts], "numeric"),
"group": cs.col("Measure", [p[1] for p in pts], "categorical", levels=["F1", "Precision", "Recall"])}))
else:
tables.append({"key": "classes", "title": "Per class (pixels summed over images)", "columns": cls_cols, "rows": cls_rows})
tables.append({"key": "images", "title": "Mean IoU per image", "rows": group_rows[:500],
"columns": [{"key": "group", "label": GROUP, "type": "string"}] + ([{"key": "frame", "label": FRAME, "type": "number"}] if FRAME else [])
+ [{"key": "miou", "label": "Mean IoU", "type": "number"}], "note": "First 500 images." if len(group_rows) > 500 else None})
dots = [(c, m, res[key][j]) for j, c in enumerate(names) for key, m in (("iou", "IoU"), ("dice", "Dice")) if res[key][j] is not None]
if dots:
charts.insert(0, cs.chart("by-class", "cleveland-dot", "IoU and Dice by class", {
"category": cs.col(LABEL, [d[0] for d in dots], "categorical", levels=names),
"value": cs.col("Overlap", [d[2] for d in dots], "numeric"),
"group": cs.col("Measure", [d[1] for d in dots], "categorical", levels=["IoU", "Dice"])}))
what = "pixel accuracy" if KIND == "masks" else "time-weighted accuracy"
summary = (f"Across {n_groups} {'images' if KIND == 'masks' else 'recordings'} and {len(names)} classes, mean IoU = {f3(res['miou'])}, "
f"mean Dice = {f3(res['mean_dice'])} and {what} = {f3(res['accuracy'])}.")
if KIND == "intervals":
summary += " Segment F1: " + ", ".join(f"{f3(r['f1'])} at IoU {tkey(r['threshold'])}" for r in res["matching"]) + "."
if has_score and values["map"] is not None:
summary += f" mAP over the thresholds = {f3(values['map'])}."
cs.publish({
"method": "evaluate.segments",
"methodVersion": "1.1.0",
"title": "Segmentation quality",
"engine": cs.engine_info("pandas", "numpy"),
"n": int(len(df)),
"summary": summary,
"statistics": [{"key": "miou", "label": "Mean IoU", "value": res["miou"]}, {"key": "mean_dice", "label": "Mean Dice", "value": res["mean_dice"]},
{"key": "accuracy", "label": "Pixel accuracy" if KIND == "masks" else "Time-weighted accuracy", "value": res["accuracy"]}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [(f"Reference rows: {SOURCE} = {st['reference']}; predictions: {SOURCE} = {st['prediction']}. " if REF_ROLES is None
else "Reference rows come from the reference table; this table's rows are the predictions. ")
+ ("Masks are compared on their run lengths (no pixels decoded)" + ("; unlabeled pixels form a background class" if BACKGROUND else "")
+ ("; crowd regions are left out of scoring" if CROWD else "") + "." if KIND == "masks"
else "Segments match within a recording and class, " + ("highest score first." if SCORE else "earliest first."))],
"charts": charts,
"values": values,
})
Mean IoU is 0.495 while pixel accuracy is 0.773: the large background inflates accuracy. Here one class, dog, has IoU 0, which pixel accuracy hides.
Check: semantic segmentation
CheckpointCheck yourself
What lets an FCN accept images of any size?
Show the answer
Answer: a
A dense layer has a fixed number of inputs; a convolution slides over whatever grid it gets.
Check yourself
Labelers marked object borders as "void". What should training and scoring do with those pixels?
Show the answer
Answer: b
Void pixels are unknown, not background. Scores with and without them aren't comparable, so say how they were handled.
Check yourself
A 3-tap kernel with dilation 6 spans how many inputs?
Show the answer
Answer: 13
2 × 6 + 1 = 13, still with 3 weights. DeepLab's pyramid runs rates like 6, 12 and 18 in parallel.
Check yourself
Why does DeepLab dilate its convolutions instead of downsampling further?
Show the answer
Answer: a
Downsampling widens the view but loses resolution. Dilation widens the view at the same resolution and parameter count.
Check yourself
You need to count the people in each photo. Is Semantic segmentation (DeepLabV3) the right tool?
Show the answer
Answer: b
Semantic segmentation labels area, not instances. Its person share tells you how much of the image is people, not how many.
Check yourself
What does pyramid pooling add to each pixel's features?
Show the answer
Answer: a
Context resolves ambiguous pixels: water in a stadium is likelier a pool than a lake.
Check yourself
A 4 × 4 feature map holds the numbers 0 to 15. What value does the global-average branch of pyramid pooling give every pixel?
Show the answer
Answer: 7.5
The mean of 0…15 is 7.5. The same value is copied to every pixel as scene-wide context.
Check yourself
A model labels every pixel of street scenes as road or background and never finds the small "bicycle" class. Which score shows the failure?
Show the answer
Answer: b
Pixel accuracy counts pixels and bicycles are few. Mean IoU gives each class equal weight.
Recap
Recap- Semantic segmentation labels area, not instances; use detection or instance masks to count.
- FCNs score pixels with convolutions only, upsample and add detail from earlier layers; void pixels stay out.
- DeepLab's dilated kernels span 2d + 1 inputs with the same weights; PSPNet stacks pooled scene context beside each pixel.
- Score with mean IoU per class; pixel accuracy is dominated by the background.
Concepts in this lesson