Sign in

Reporting

Evaluation reporting

A report builder that collects evaluation results, ranks them on one metric and writes them as Markdown, JSON and HTML with an SVG bar chart.

Overview

An evaluation is not finished when the numbers exist in memory. They have to reach people and later programs in a form that can be trusted and compared. Reporting gathers one set of metrics per model, ranks the models on a chosen metric, and writes the same content in three shapes: a table a person can read in a review, a full-precision file a program can load, and a page with a chart. The chart is drawn from the numbers by simple arithmetic, with no plotting library.

A short history

Reporting results in a fixed, repeatable form is an engineering and scientific practice with no single inventor. It follows the reproducible research movement in statistics and computing, which asks that every published number can be regenerated from code and data. In machine learning, Margaret Mitchell and colleagues proposed model cards in 2019 as a standard short report on a model's measured performance and limits, which made structured reports a common expectation.

How it works

  1. Create a Report with a title, the primary_metric and its direction (higher_is_better).
  2. Call add_result(name, metrics) once per model or run, and add_note for context such as the data split.
  3. ranking sorts the results from best to worst on the primary metric. Results that lack the metric go last. best returns the first name.
  4. to_markdown writes a table with values rounded to float_digits. to_json keeps full precision.
  5. bar_chart computes one rectangle per result, with a height in proportion to the value, and bar_chart_svg writes those rectangles as SVG.
  6. to_html builds a self-contained page, and save writes the chosen formats into a directory.

Watch out for

  • Rounded tables can show two models as equal when they differ, or hide that a difference is tiny. Compare using the JSON values.
  • Setting higher_is_better wrongly for a loss ranks the worst model first, and the report will name it the best without any warning.
  • A ranking on one metric says nothing about the others, so the best model on AUC can be the worst on log loss.
  • Bars grow from zero, so metrics that differ only in the third decimal look the same height. That is honest, but it means the chart cannot show small gaps.
  • A report holds single numbers with no spread, so a small gap between two models may be noise. Add the standard deviation over folds as a metric of its own.

Use cases

When to use it

At the end of an evaluation or a model comparison, when the numbers have to leave the process. Keep the JSON as the source of truth and treat Markdown and HTML as views of it.

In industry

Regulated lending
A bank's model validation group needs a written record of each candidate model's metrics and the data split used before a credit model may go live.
Product teams
After a weekly retraining run, a ranked table of candidates is posted so that engineers and managers see the same numbers and the same winner.
Research groups
A lab keeps the JSON results of every experiment and generates the comparison tables in its papers from them, so the tables cannot drift from the runs.

Choosing it: what must hold

  • Metrics already computed for each model or run on the same data split.
  • One primary metric and an agreed direction, higher or lower, so results can be ranked.
  • Readers outside the training process who need the numbers in a fixed form.

When to choose something else

IfUse instead
You need to follow metric curves during training, not a final summaryThe experiment tracking lesson
The numbers have not been computed yetThe evaluation metrics lesson, then this one
Readers need to filter and explore many runs interactivelyA tracking server or a dashboard tool, with this report kept as the fixed record

Math foundations

  1. Ranking

    best=arg⁡max⁡m  s⋅vm,s={+1higher is better−1lower is better\text{best} = \arg\max_{m}\; s \cdot v_m, \qquad s = \begin{cases} +1 & \text{higher is better} \\ -1 & \text{lower is better} \end{cases}

    The direction flag turns both cases into one rule: multiply by a sign and take the largest. All results are sorted by the same key.

  2. Height of a bar

    hm=H⋅∣vm∣vhigh−vlow,vhigh=max⁡(max⁡mvm, 0),vlow=min⁡(min⁡mvm, 0)h_m = H \cdot \frac{|v_m|}{v_{\text{high}} - v_{\text{low}}}, \qquad v_{\text{high}} = \max\big(\max_m v_m,\, 0\big), \quad v_{\text{low}} = \min\big(\min_m v_m,\, 0\big)

    Each bar's height in pixels is in proportion to its value. The span always includes zero, so the picture never exaggerates a difference by cutting off the axis.

  3. Position of the zero line

    y0=ytop+H⋅vhighvhigh−vlowy_0 = y_{\text{top}} + H \cdot \frac{v_{\text{high}}}{v_{\text{high}} - v_{\text{low}}}

    Pixel rows count downward. Positive bars rise from this line and negative bars hang below it.

Symbols

vmv_m
value of the metric for result m
ss
sign that encodes the direction of the metric
hmh_m
height of the bar of result m in pixels
HH
height of the plotting area in pixels
vhigh, vlowv_{\text{high}},\, v_{\text{low}}
top and bottom of the value span, always including zero
y0y_0
pixel row of the value zero
ytopy_{\text{top}}
top margin of the chart in pixels

Worked by hand

Two models have AUC 0.88 and 0.81. The default chart is 240 pixels high with a top margin of 20 and a bottom margin of 40, so H=240−20−40=180H = 240 - 20 - 40 = 180.

vhigh=max⁡(0.88, 0)=0.88,vlow=min⁡(0.81, 0)=0v_{\text{high}} = \max(0.88,\, 0) = 0.88, \qquad v_{\text{low}} = \min(0.81,\, 0) = 0
h1=180×0.880.88=180,h2=180×0.810.88=165.7h_1 = 180 \times \frac{0.88}{0.88} = 180, \qquad h_2 = 180 \times \frac{0.81}{0.88} = 165.7
y0=20+180×0.880.88=200y_0 = 20 + 180 \times \frac{0.88}{0.88} = 200

The best model fills the plotting area and the other bar is 165.7 pixels tall. The two heights stand in the same ratio as the two values, 0.92.

Visual example

Loading the example.

Try this

  • Switch primary_metric to mae and leave higher_is_better on True: the report names the worst model as best.
  • Drag the baseline's r2 below zero and watch the zero line move up from the bottom of the chart.
  • Click the Markdown and JSON nodes to read the same ranking in the other two formats.

Code sample

import tempfile
from impl import Report
from config import ReportingConfig

report = Report(ReportingConfig(title="Churn models", primary_metric="auc"))
report.add_result("logistic", {"auc": 0.81, "log_loss": 0.47})
report.add_result("boosted", {"auc": 0.88, "log_loss": 0.39})
report.add_note("validation split 2024-06")
print(report.best())               # boosted
print(report.to_markdown())
print(report.save(tempfile.mkdtemp()))   # {'md': '.../report.md', 'json': ..., 'html': ...}
Read the implementation (222 lines)
"""Results and report generation: collect metrics per model, rank them, write Markdown, JSON and HTML.

Standard library and NumPy only, no plotting library. The bar chart is computed here (bar heights from the
values) and written as a small SVG string that any browser shows.
"""
from __future__ import annotations

import html
import json
import os

import numpy as np

try:
    from .config import ReportingConfig
except ImportError:  # run from the template's own folder
    from config import ReportingConfig


def _plain(value):
    """Turn NumPy scalars and arrays into plain Python so json can write them."""
    if isinstance(value, np.ndarray):
        return value.tolist()
    if isinstance(value, np.generic):
        return value.item()
    return value


class Report:
    """Collect named results (each a dict of metric name to number) and render them.

    Typical flow: `add_result` once per model or run, optional `add_note`, then `to_markdown`, `to_html`,
    `to_json` or `save`.
    """

    def __init__(self, config: ReportingConfig | None = None) -> None:
        self.config = config or ReportingConfig()
        self.results: dict[str, dict] = {}
        self.notes: list[str] = []

    # ------------------------------------------------------------------------------------------ collect
    def add_result(self, name: str, metrics: dict) -> None:
        """Record the metrics of one model or run. Values must be numbers. A repeated name is an error."""
        if name in self.results:
            raise ValueError(f"result {name!r} was already added")
        clean = {}
        for metric, value in metrics.items():
            value = _plain(value)
            if isinstance(value, bool) or not isinstance(value, (int, float)):
                raise ValueError(f"metric {metric!r} of {name!r} must be a number, got {type(value).__name__}")
            clean[str(metric)] = value
        if not clean:
            raise ValueError(f"result {name!r} has no metrics")
        self.results[name] = clean

    def add_note(self, text: str) -> None:
        """Add a free-text line shown under the table (data version, caveats, ...)."""
        self.notes.append(str(text))

    # ------------------------------------------------------------------------------------------ analyse
    def metric_names(self) -> list[str]:
        """Every metric that appears in any result, in first-seen order."""
        names: list[str] = []
        for metrics in self.results.values():
            names.extend(m for m in metrics if m not in names)
        return names

    def primary_metric(self) -> str:
        """The metric used for ranking."""
        if not self.results:
            raise ValueError("the report has no results yet")
        return self.config.primary_metric or self.metric_names()[0]

    def ranking(self) -> list[str]:
        """Result names from best to worst on the primary metric. Results without it come last."""
        metric = self.primary_metric()
        sign = -1.0 if self.config.higher_is_better else 1.0
        have = [name for name, m in self.results.items() if metric in m]
        lack = [name for name, m in self.results.items() if metric not in m]
        return sorted(have, key=lambda name: sign * self.results[name][metric]) + lack

    def best(self) -> str:
        """Name of the best result on the primary metric."""
        return self.ranking()[0]

    def _cell(self, value) -> str:
        if value is None:
            return "-"
        return str(value) if isinstance(value, int) else f"{value:.{self.config.float_digits}f}"

    def rows(self) -> tuple[list[str], list[list[str]]]:
        """(header, rows) of the results table as strings, best result first."""
        metrics = self.metric_names()
        header = ["name"] + metrics
        body = [[name] + [self._cell(self.results[name].get(m)) for m in metrics] for name in self.ranking()]
        return header, body

    # ------------------------------------------------------------------------------------------- render
    def to_markdown(self) -> str:
        """The report as Markdown: title, best line, table, notes."""
        header, body = self.rows()
        metric, best = self.primary_metric(), self.best()
        lines = [
            f"# {self.config.title}",
            "",
            f"Best on `{metric}`: **{best}** ({self._cell(self.results[best][metric])})",
            "",
            "| " + " | ".join(header) + " |",
            "|" + "|".join(["---"] * len(header)) + "|",
        ]
        lines += ["| " + " | ".join(cell.replace("|", "\\|") for cell in row) + " |" for row in body]
        if self.notes:
            lines += ["", "## Notes", ""] + [f"- {note}" for note in self.notes]
        return "\n".join(lines) + "\n"

    def to_json(self) -> str:
        """Machine-readable form with full precision: config, primary metric, best, ranking, results, notes."""
        return json.dumps(
            {
                "title": self.config.title,
                "primary_metric": self.primary_metric(),
                "higher_is_better": self.config.higher_is_better,
                "best": self.best(),
                "ranking": self.ranking(),
                "results": self.results,
                "notes": self.notes,
            },
            indent=2,
        )

    def bar_chart(self, metric: str | None = None, width: int = 480, height: int = 240) -> dict:
        """The numbers a bar chart of one metric is made of.

        Returns {"metric", "names", "values", "bars"} where each bar is a dict with x, y, width and height
        in pixels. Bars grow from the zero line; a bar's height is proportional to |value|.
        """
        metric = metric or self.primary_metric()
        names = [name for name in self.ranking() if metric in self.results[name]]
        values = [float(self.results[name][metric]) for name in names]
        if not names:
            raise ValueError(f"no result has the metric {metric!r}")
        top, bottom, left = 20.0, 40.0, 10.0
        plot_h = height - top - bottom
        high, low = max(max(values), 0.0), min(min(values), 0.0)
        span = (high - low) or 1.0
        zero_y = top + plot_h * high / span               # pixel row of the value 0
        slot = (width - 2 * left) / len(names)
        bars = []
        for i, value in enumerate(values):
            bar_h = plot_h * abs(value) / span
            bars.append({
                "x": left + i * slot + slot * 0.15,
                "y": zero_y - bar_h if value >= 0 else zero_y,
                "width": slot * 0.7,
                "height": bar_h,
            })
        return {"metric": metric, "names": names, "values": values, "bars": bars, "zero_y": zero_y,
                "width": width, "height": height}

    def bar_chart_svg(self, metric: str | None = None, width: int = 480, height: int = 240) -> str:
        """An SVG bar chart of one metric (default: the primary metric), one labelled bar per result."""
        chart = self.bar_chart(metric, width, height)
        parts = [
            f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" '
            f'viewBox="0 0 {width} {height}" role="img">',
            f"<title>{html.escape(chart['metric'])}</title>",
            f'<line x1="0" y1="{chart["zero_y"]:.2f}" x2="{width}" y2="{chart["zero_y"]:.2f}" stroke="#444"/>',
        ]
        for name, value, bar in zip(chart["names"], chart["values"], chart["bars"]):
            middle = bar["x"] + bar["width"] / 2
            parts.append(
                f'<rect x="{bar["x"]:.2f}" y="{bar["y"]:.2f}" width="{bar["width"]:.2f}" '
                f'height="{bar["height"]:.2f}" fill="#4878a8"/>'
            )
            parts.append(
                f'<text x="{middle:.2f}" y="{bar["y"] - 4:.2f}" text-anchor="middle" font-size="11">'
                f"{self._cell(value)}</text>"
            )
            parts.append(
                f'<text x="{middle:.2f}" y="{height - 12}" text-anchor="middle" font-size="11">'
                f"{html.escape(name)}</text>"
            )
        parts.append("</svg>")
        return "\n".join(parts)

    def to_html(self) -> str:
        """A self-contained, well-formed HTML page: title, best line, table, chart, notes."""
        header, body = self.rows()
        metric, best = self.primary_metric(), self.best()
        esc = html.escape
        out = [
            '<html lang="en">',
            f"<head><meta charset=\"utf-8\"/><title>{esc(self.config.title)}</title></head>",
            "<body>",
            f"<h1>{esc(self.config.title)}</h1>",
            f"<p>Best on <code>{esc(metric)}</code>: <strong>{esc(best)}</strong> "
            f"({self._cell(self.results[best][metric])})</p>",
            "<table>",
            "<tr>" + "".join(f"<th>{esc(cell)}</th>" for cell in header) + "</tr>",
        ]
        out += ["<tr>" + "".join(f"<td>{esc(cell)}</td>" for cell in row) + "</tr>" for row in body]
        out.append("</table>")
        if self.config.include_chart:
            out.append(self.bar_chart_svg())
        if self.notes:
            out.append("<ul>" + "".join(f"<li>{esc(note)}</li>" for note in self.notes) + "</ul>")
        out += ["</body>", "</html>"]
        return "\n".join(out) + "\n"

    def save(self, directory: str, stem: str = "report", formats: tuple = ("md", "json", "html")) -> dict:
        """Write the report into `directory` and return {format: path}. formats: any of "md", "json", "html"."""
        writers = {"md": self.to_markdown, "json": self.to_json, "html": self.to_html}
        unknown = [f for f in formats if f not in writers]
        if unknown:
            raise ValueError(f"unknown formats {unknown}, choose from {sorted(writers)}")
        os.makedirs(directory, exist_ok=True)
        paths = {}
        for fmt in formats:
            paths[fmt] = os.path.join(directory, f"{stem}.{fmt}")
            with open(paths[fmt], "w", encoding="utf-8") as handle:
                handle.write(writers[fmt]())
        return paths
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Create Report(ReportingConfig(primary_metric="log_loss", higher_is_better=False)), add three results with add_result, and print ranking(), best() and to_markdown(). Then call bar_chart() and check by hand that one bar's height matches the formula.

Check on learning

  1. Why keep the JSON as the source of truth and treat the Markdown table as a view, instead of the other way round?
    A way to think about it

    Ask which one a later program can read back without loss, and what float_digits does to the Markdown values.

  2. Two models score 0.912 and 0.915. A chart whose axis starts at 0.90 would make the second bar look much taller. The template starts bars at zero. What is gained and what is lost?
    A way to think about it

    Compare the ratio of the bar heights with the ratio of the values in both designs. Then ask what a reader concludes at a glance.

  3. The report names model B as best on accuracy by 0.3 percentage points. What else would you want to know before acting on that?
    A way to think about it

    Think about the size of the test set, how much the score moves between folds or seeds, and how B does on the other metrics in the table.

  4. A result is added without the primary metric. The template ranks it last. What could go wrong if it were silently left out, or treated as zero?
    A way to think about it

    Consider a loss, where lower is better. Check where a value of zero would land in the ranking.