Repository navigation
Measuring and drawing
The measures are declared with the pipeline, before a single number exists, and the charts are drawn from what the run already kept. A measure chosen after seeing the result is a measure chosen because of the result; declared first, every run is measured the same way whether it turned out well or not. The one rule to remember: choose the measures before the run, and never tune against the test rows' numbers.
| You want to… | Write |
|---|---|
| declare a report before anything learns | .Report(report => report.Measure(…).On(…).As(…)) |
| measure a class | .Measure(Metric.Accuracy, Metric.Precision, Metric.Recall, Metric.ConfusionMatrix) |
| measure how a model ranks its rows and how its chances hold |
Metric.F1, Metric.Auc, Metric.Brier
|
| measure an amount |
Metric.Rmse, Metric.Mae, Metric.R2, Metric.Mape
|
| measure shares in an order |
Metric.Emd, Metric.Rps, Metric.Kl
|
| say which parts are measured and how they are shown | .On(Part.Train, Part.Validation, Part.Test).As(Shown.Numbers, Shown.Drawn) |
| write the report as a page | trained.Measures!.Report().ToHtml() |
| draw the loss curve | trained.History!.LossCurve() |
| see how alike the parts are |
.Likeness(warnAbove) below the split |
| keep the training rows a served model is watched against |
.Watch(warnAbove) below the split |
| measure a window of served rows against them | prepared.Watched(window) |
| draw the windows one beside another | windows.Distances() |
| measure an ensemble beside each member | ensemble.Measures!.BarsWithMembers() |
| see which columns the answers lean on | trained.Leaning(rows, new Redraws(seed: 1, repeats: 5)) |
| see what the answers do as a column moves | trained.Curve(rows, new Moving("age", 10)) |
| see what one row's answer is made of | trained.MakeUp(rows, row: 0, new Redraws(1, 100)) |
| give an answer the width it is worth | trained.WithInterval(0.1) |
| measure how often the answer lands within it |
Metric.Coverage, Metric.Width
|
| lay what the folds measured beside one another |
MeasuresAcross.Of(measures) · across.AcrossFolds()
|
| show a correlation as numbers or a picture | .Correlation(columns, Shown.Numbers, Coefficient.Spearman) |
The rest of this page explains each one.
using DeepSharp.Charts;
using DeepSharp.Learners.Networks;
using DeepSharp.Pipelines;
var pipeline = Pdd.Create()
.ReadCsv("titanic.csv")
.Declare(schema => schema.Integer("survived").Category("sex").Optional("age", ColumnKind.Number).Number("fare"))
.SplitStratified("survived", train: 0.70, validation: 0.15)
.Target("survived")
.FillMissing(fill => fill.Median("age"))
.EncodeCategories()
.Normalise("age", "fare")
.Report(report => report // declared before anything learns
.Measure(Metric.Accuracy, Metric.Precision, Metric.Recall, Metric.ConfusionMatrix)
.On(Part.Train, Part.Validation, Part.Test)
.As(Shown.Numbers, Shown.Drawn))
.WithTensorflow(network => network
.Dense(16).Relu().Dense(1).Adam(0.01).BinaryCrossEntropy().Run(seed: 20260929, epochs: 100))
.Build();
var trained = pipeline.Train();
File.WriteAllText("titanic-report.html", trained.Measures!.Report().ToHtml());
File.WriteAllText("titanic-loss.svg", trained.History!.LossCurve());A model that beats the average by nothing is a model that learned nothing, and that comparison is worth more than any single number.
The test rows' measures stand last, because they are the ones you are not allowed to tune against.
Measures!.Report() is the report as the declaration said its measures are shown, and ToHtml() is that page — which is
also what a notebook block shows when you ask it for the report.
- the loss curve
- the learning rate
- the confusion matrix
- predicted against actual
- the residuals
- the measures as bars
- the reliability curve
- the windows a served model met, each column's distance from the training rows
All are SVG, with no viewer to start and nothing recomputed. That is DeepSharp.Charts, which draws with MatPlotLibNet
and is a package of its own: a project that serves a model and draws nothing never carries it.
| Measure | What it is |
|---|---|
Metric.F1 |
the harmonic mean of precision and recall, label by label and averaged |
Metric.Auc |
the area under the curve a threshold sweeps out — the chance a row that holds a class is given more of it than a row that does not |
Metric.Brier |
the Brier score: the squared distance between each chance said and the class held |
Metric.Auc is taken of the chances themselves before any threshold, so a model is measured on how it ranks its rows.
The Brier score answers whether a model that says seventy per cent is right seven times in ten.
Drawn, the Brier score stands beside the reliability curve: the rows sorted by the chance said and dealt into ten bins of as many rows each, the chance said in a bin against how often its rows held the class.
All three are scikit-learn's, held to it to twelve places. What they refuse:
- A part in which every row holds a class, or none does, has no area under the curve and is refused; scikit-learn says the area is not defined there and gives no number.
- Labels of which a row holds any number are refused for the Brier score: scikit-learn takes each row for one class of many, warns that the chances do not add up to one, and gives a number that measures nothing these labels mean.
The expected calibration error is not built: binned, it misjudges most the models that are best calibrated, and the Brier score bins nothing.
Metric.Mape is the mean absolute percentage error, as a share: each error's size over its answer's.
A part that holds an answer of nought is refused, naming the row. Scikit-learn divides by the smallest number above nought instead, which makes that row's error as large as a number gets and the measure say nothing else.
.Likeness(warnAbove) below the split sets out, column by column, how far apart training, validation and test are, each
distance beside the rows it was worked out from:
- for a column of numbers, the two-sample Kolmogorov–Smirnov distance, ties taken whole as scipy takes them;
- for a column of words, the total variation — half the sum of how far each word's share differs.
A distance above warnAbove is flagged. The bound has no default, because how far apart is too far depends on how many
rows a part holds.
It reads the features of every part and never the answer, and it warns and never refuses:
- a validation part unlike the training rows is a poorer guide to stop on;
- a test part unlike them explains a measurement that disappoints.
A notebook draws it as a table.
The likeness of the parts is measured once, while every row is there. A model that ships meets rows nobody had then, and
the pipeline it serves behind is read from its file, which keeps what the steps learned and not the rows they learned it
from. .Watch(warnAbove) below the split is the step that keeps them: the training rows of every column it watches, each
value once with how many rows hold it. It changes nothing a replay does.
prepared.Watched(window) then measures a window of served rows — a day of them, an hour, as you group them — against
those rows, by the same two distances and the same rule as the likeness of the parts:
using DeepSharp.Charts;
using DeepSharp.Pipelines;
// The pipeline a model serves behind, read from its file: it declared .Watch(0.1) below its split.
var prepared = PreparedData.FromJson(File.ReadAllText("flocks.pipeline.json"), StepCatalog.BuiltIn());
var windows = new List<WindowLikeness>();
foreach (var day in Directory.GetFiles("served", "*.csv").Order(StringComparer.Ordinal))
{
var window = prepared.Watched(new CsvRowSource(day));
foreach (var column in window.Columns.Where(column => column.Above))
{
Console.WriteLine($"{window.From:yyyy-MM-dd}: {column.Column} is {column.Apart:0.00} away, over {column.WindowRows} rows");
}
windows.Add(window);
}
File.WriteAllText("watched.svg", windows.Distances());- Each column says its distance, whether it is above the bound, and how many rows of the window and of the training rows it was worked out from; the window says the first and last moment it holds in the column its rows are ordered by.
- The window is replayed to where the watch stands, so a category the training rows never held is measured there, not refused.
- Nothing is learned from a window, and none is kept between calls: the series is yours, and
windows.Distances()draws it — a line to each column, under the bound. - There is no least window. A distance over a few rows is noise as much as anything, which the rows beside it say.
Left unnamed, the watch keeps every column but the id, the answer and the columns the rows are ordered or divided in time by, which every window holds otherwise than the training rows. The counts are exact, so a column of numbers with every digit keeps a number for every training row: name the columns to keep the file small. A model trained before its pipeline kept the rows is watched once the pipeline is fitted again with the watch and the model trained behind that fit.
For shares in an order — a flock weighed in bands:
| Measure | What it says |
|---|---|
Metric.Emd |
how many bands the predicted shares have to move, on average over the rows, to be the answer's |
Metric.Rps |
the ranked probability score |
Metric.Kl |
the divergence from the prediction to the answer — infinite where the prediction holds nothing the answer holds, which the report writes and draws as such |
The output says its columns are ordered, or a report that names Emd or Rps is refused where it is written.
R², RMSE and MAE still apply to a distribution, but they are averaged a column at a time, and a prediction one band off scores a low R² over hundreds of bands, which is why the others are there. Pipeline has the definitions.
-
correlation.Correlate()gives Pearson's coefficients and Spearman's between the columns, worked out once from the rows the correlation was kept over. -
.Correlation(columns, Shown.Numbers, Coefficient.Spearman)says which one a notebook shows. -
matrix.Heatmap(Coefficient.Spearman)draws it.
A column that never changes has no coefficient with any other, and its cells are blank in the picture and n/a in the
table, never nought. A profile told .Profile(rankAbove: 0.9) flags two columns of numbers that keep one another's order.
CorrelationMatrix.From(columns, rows) is the same Pearson's and Spearman's coefficients, reachable on a plain table
before any pipeline exists — grouping columns that say the same thing to shape a search's own space, say, worked out
once over every row rather than over one split's training rows, so the groups do not move when the split does.
The same network scores a few percent differently on two divisions of the same rows, as much as most changes move it, so one split cannot say. Searching for a network has the paired comparison that trains the network behind two pipelines on each of many deals and reports the differences with their spread.
A small table measured on one division is measured by that division's luck. Cut the rows into folds (Splitting the rows), train behind each, and lay what every fold measured beside the others:
using DeepSharp.Charts;
using DeepSharp.Learners.Networks;
using DeepSharp.Pipelines;
var space = new SearchSpace([new LogRange("rate", 1e-3, 1e-1), new WholeRange("units", 4, 32)]);
var study = new Study(space, (candidate, network) => network
.Dense(candidate.Whole("units")).Relu().Dense(1)
.Adam(candidate.Number("rate"))
.BinaryCrossEntropy()
.Run(seed: 20260929, epochs: 10))
{
Trials = 6,
Deals = 5, // the five folds are the study's deals
Sampler = new RandomSampler(11),
};
var found = study.Run(fold => Pdd.Create()
.ReadCsv("titanic.csv")
.Declare(schema => schema.Integer("survived", "sibsp", "parch").Category("sex").Optional("age", ColumnKind.Number).Number("fare"))
.SplitAtRandom(0.80, new Fold(5, fold), seed: 100, testSeed: 7)
.Target("survived")
.FillMissing("age", With.Median)
.EncodeCategories()
.Normalise("age", Scale.MidRange)
.Normalise("fare", Scale.MidRange)
.Normalise("sibsp", Scale.MidRange)
.Normalise("parch", Scale.MidRange)
.Report(report => report.Measure(Metric.Accuracy, Metric.Rmse).On(Part.Validation, Part.Test).As(Shown.Numbers))
.Build());
var across = MeasuresAcross.Of([.. found.Winner.Select(network => network.Measures!)]);
foreach (var part in across.Parts)
{
foreach (var measured in part.Values)
{
Console.WriteLine($"{part.Part} {measured.Metric}: {measured.Mean:0.000} ± {measured.Spread:0.000} (the average: {measured.Baseline:0.000})");
}
}
File.WriteAllText("folds.svg", across.AcrossFolds());The spread is the sample standard deviation of the folds' values. It gives no verdict: how wide a spread may be is for the
person who reads it. AcrossFolds() draws a panel to each measure, the mean of each part with its spread as a bar and the
average of the training rows beside it — a model that beats the average by less than its folds differ by is a bar that
reaches across it.
Three questions, asked of the rows as they were read — a category is one value, and a log is undone — by perturbing them and serving them through the model's own pipeline. Nothing is fitted, and every draw comes from a seed you name.
using DeepSharp.Charts;
using DeepSharp.Learners.Networks;
using DeepSharp.Pipelines;
var pipeline = Pdd.Create()
.ReadCsv("titanic.csv")
.Declare(schema => schema.Integer("survived", "sibsp", "parch").Category("sex").Optional("age", ColumnKind.Number).Number("fare"))
.SplitAtRandom(0.70, 0.15, seed: 100, testSeed: 7)
.Target("survived")
.FillMissing("age", With.Median)
.EncodeCategories()
.Normalise("age", Scale.MidRange)
.Normalise("fare", Scale.MidRange)
.Normalise("sibsp", Scale.MidRange)
.Normalise("parch", Scale.MidRange)
.WithTorch(network => network.Dense(8).Relu().Dense(1).Adam(0.01).BinaryCrossEntropy().Run(seed: 1, epochs: 20))
.Build();
var trained = pipeline.Train();
var rows = new CsvRowSource("titanic.csv");
var leaning = trained.Leaning(rows, new Redraws(seed: 1, repeats: 5)); // which columns the answers lean on
var curve = trained.Curve(rows, new Moving("age", 10)); // what they do as age moves from youngest to oldest
var makeUp = trained.MakeUp(rows, row: 0, new Redraws(seed: 1, repeats: 100)); // what the first passenger's answer is made of
File.WriteAllText("leaning.svg", leaning.Leaning());
File.WriteAllText("curve.svg", curve.Curve());
File.WriteAllText("make-up.svg", makeUp.Parts());-
Leaning: how far the answers move, in their own units, when a column's values are shuffled among the rows — column by column, the one the answers move most with first, with the spread over the shuffles. A column the model ignores moves nothing. It needs no answer to compare with, so it is asked of rows whose answers are yet to come; scikit-learn's permutation importance measures a rise in error and needs every answer. -
Curve: what the answers do as one column moves with the rest of each row as it was. A number moves from the smallest to the largest of the rows handed in, at the places you name; a category goes to every value the training rows held, even one the rows handed in lack. -
MakeUp: what each column adds to one row's answer, the mean of sampled Shapley values; they add up to the answer less the background. - Neither seed nor draws has a default: an explanation drawn from a number nobody chose cannot be drawn again, and one drawn once says nothing of how much it owes to that draw.
-
A network, an ensemble and a tree are asked alike (
TrainedMLModelnow serves rows that have arrived), so they can be laid side by side. -
Cost: every question replays the rows it perturbs —
rows × draws × columnsfor the leaning — so hand in a few hundred rows.
A number comes with a margin on either side of it: set rows aside with Calibrate (Splitting the rows), train, and give the model its
interval at a level you name.
using DeepSharp.Learners.Networks;
using DeepSharp.Pipelines;
var trained = Pdd.Create()
.ReadCsv("titanic.csv")
.Declare(schema => schema.Number("fare", "age").Integer("sibsp"))
.Calibrate(0.20)
.SplitAtRandom(0.50, 0.10, seed: 3, testSeed: 7)
.Target("fare")
.Drop("age")
.Normalise("sibsp", Scale.MidRange)
.Report(report => report.Measure(Metric.Mae, Metric.Coverage, Metric.Width).On(Part.Validation, Part.Test).As(Shown.Numbers))
.WithTorch(network => network.Dense(8).Relu().Dense(1).Adam(0.01).MeanSquaredError().Run(seed: 1, epochs: 20))
.Build()
.Train()
.WithInterval(0.10); // nine rows in ten land within the margin
var answers = trained.Predict(new CsvRowSource("titanic.csv"));
Console.WriteLine($"{answers.Answers[0][0]:0.00} between {answers.Lower![0][0]:0.00} and {answers.Upper![0][0]:0.00}");- The margin is the error all but a tenth of the calibration rows stay under, in the answer's own units: the ⌈(n+1)(1−α)⌉-th smallest. It is split conformal prediction, so it wraps any model — a network, an ensemble (the margin of its combined answer), a tree — and is the same on every row.
- The level is required, and too few rows for it are refused, saying how many there are and how many it takes.
- Classes have no interval: a class has a chance, not a width.
-
Metric.CoverageandMetric.Widthmeasure it on the test rows, beside the training rows' average given the same margin. They are left out of the numbers until the model has an interval. - It holds on average, for rows like the calibration rows; it says nothing of one row, and a series whose later rows differ from its earlier ones breaks the promise it rests on. Training further gives a new network, which has no interval.
- It is kept in the model's file, under one key, and a file without one is written exactly as before.
ConformalInterval.FromErrors(errors, alpha) is the same rank-order rule on a plain list of errors the caller hands
in itself, rather than a pipeline's own calibration rows — a margin per kind of row the caller defines, say, each kind
calibrated from the errors of a number the caller derives, not a pipeline's answer.
Searching for a network trains the best few networks of a study as one ensemble. The report measures the ensemble and each member
on the very same rows, the members' answers brought back into the answer's own units before they are combined; BarsWithMembers()
draws a panel to each measure with the ensemble's bar beside every member's and the average's. What the members said together is no one text, so
the ensemble's measures do not cross to a notebook as predictions: each member's do.
One learner a declaration, so the comparison is two declarations that differ in a single line —
.WithML(trainer => trainer.FastTree()) where the other says .WithTensorflow(…).
Everything above that line is the same steps over the same rows in the same parts. The run made for a tree leaves out only the scalings a tree does without, and writes down which, so two learners fed the same rows are compared rather than guessed between.
The report then reads the rows' keys and their answers and nothing of the features, so the two are measured on the same rows, by the same metrics, in the answer's own units. See ML.NET learner.
Next: Naming the network · Every measure and every chart: Networks