Learning curves: would more data help?
Before you spend money on more rows or a bigger model, plot training and validation scores as rows grow. The shapes tell you which spending will pay.
What runs in CodeSplash
- Decision tree (CART) Verified in Python and R
You will be able to
- Read a learning curve for bias, variance and the value of more rows
- Tell a learning curve from a validation curve
- Act on the verdict in the Diagnostics tab
Read first
Two lines over rows
ReadA learning curveLearning curveModel score as the training set grows; shows whether more data would still help. re-fits the same recipe on growing shares of each fold's training rows. The validation rows stay fixed, so every point is scored on the same rows.
Read two things: how far apart the training and validation lines are, and whether validation is still improving at the right-hand end.
View data
| training rows | accuracy | set | lower | upper |
|---|---|---|---|---|
| 100 | 0.9936 | train | 0.9896 | 0.9976 |
| 100 | 0.7039 | validation | 0.6739 | 0.7339 |
| 200 | 0.9737 | train | 0.9697 | 0.9777 |
| 200 | 0.7255 | validation | 0.7043 | 0.7467 |
| 400 | 0.9522 | train | 0.9482 | 0.9562 |
| 400 | 0.7425 | validation | 0.7275 | 0.7575 |
| 800 | 0.9399 | train | 0.9359 | 0.9439 |
| 800 | 0.7601 | validation | 0.7495 | 0.7707 |
| 1,600 | 0.9128 | train | 0.9088 | 0.9168 |
| 1,600 | 0.8070 | validation | 0.7995 | 0.8145 |
| 3,200 | 0.9044 | train | 0.9004 | 0.9084 |
| 3,200 | 0.8576 | validation | 0.8523 | 0.8629 |
| 6,400 | 0.8784 | train | 0.8744 | 0.8824 |
| 6,400 | 0.8728 | validation | 0.8691 | 0.8766 |
Read the shape
PredictPredict first
Training and validation scores have met, and both are flat at a mediocre AUC. Adding rows has stopped helping. What will help most?
Reveal
A more flexible model or better features. That shape is bias. The model already extracts all it can, so more rows won't help, and a stronger penalty would make things worse. A wide gap with validation still climbing would have said the opposite.
Three pictures
Read| The picture | The diagnosis | The move |
|---|---|---|
| Wide gap, validation still rising | Variance | More rows, or more regularization |
| Lines meet at a poor score | Bias | More flexibility, or better features |
| Lines close at a good score, flat | Balanced | Stop here, or look elsewhere |
Learning curve varies rows. Validation curve varies one hyperparameter, and that's the place to look for the sweet spot once you know you have a variance or bias problem.
Half the rows
ReadThe cost of fewer rows can be measured directly. This run fits a tree of depth 4 on half of each fold's training rows, 213 rows, and scores all validation rows as usual: cross-validated AUC 0.779.
The option is Share of training rows. It's what the Diagnostics tab sets at each point of the curve, along with Also score training rows for the upper line.
Decision tree (CART): cross-validated ROC AUC 0.779 ± 0.066 over 5 folds.
- CV ROC AUC
- 0.7792
- SD across folds
- 0.0664
Cross-validation
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 86 | 0.8336 | 3.431 | 0.8256 | 0.8261 |
| 2 | 1 | 85 | 0.6905 | 3.229 | 0.7765 | 0.7243 |
| 3 | 1 | 85 | 0.7575 | 1.716 | 0.7294 | 0.6801 |
| 4 | 1 | 85 | 0.7585 | 3.162 | 0.7412 | 0.7162 |
| 5 | 1 | 85 | 0.8559 | 2.305 | 0.7882 | 0.7395 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Decision tree (CART)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.tree 1.0.0 · spec 6790f4f937df968b
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data and split plan
TARGET <- "diabetic"
FEATURES <- c("glu", "bmi", "age", "ped")
TASK <- "binary"
CLASSES <- c("false", "true")
POSITIVE <- "true"
METRIC <- "roc_auc"
SEED <- 42
PARAMS <- list(
max_depth = 4,
min_samples_split = 10,
min_samples_leaf = 5,
criterion = "gini",
min_impurity_decrease = 0,
ccp_alpha = 0
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.tree/learning_curve_half/folds.parquet") # host-written folds: identical in Python and R
design <- cs_ml_design(
df, FEATURES,
kinds = list(
glu = "numeric",
bmi = "numeric",
age = "numeric",
ped = "numeric"
),
levels = list(
),
impute = "median",
scale = "none",
indicators = FALSE
)
target <- cs_ml_encode_target(df[[TARGET]], TASK, CLASSES, POSITIVE)
y <- target$fit
y_index <- target$index
weights <- cs_ml_class_weights(y_index, TASK, "none", plan$train)
run <- cs_ml_run(TASK, CLASSES, POSITIVE, METRIC)
out <- cs_ml_out_dir("target/academy-parity/run-8142/learn.tree/learning_curve_half/out-r")
warnings <- list()
sample_weights <- function(rows) if (is.null(weights)) NULL else weights[rows + 1L]
rows_of <- function(rows) df[rows + 1L, , drop = FALSE]
RESAMPLE <- "none"
if (RESAMPLE != "none" && TASK == "regression") {
warnings <- c(warnings, list("Resampling applies to classification only — ignored for this regression target."))
}
resampled <- NULL # the final model's resampling summary
notes <- list()
# A fit's design matrix, targets and weights: training rows only, resampled when asked
# (cs_ml_resample — the same rows in Python, from the shared random stream).
training_set <- function(X, rows, fold_id, repeat_) {
yy <- y[rows + 1L]
ww <- sample_weights(rows)
if (RESAMPLE == "none" || TASK == "regression") return(list(X = X, y = yy, w = ww))
r <- cs_ml_resample(X, yy, ww, RESAMPLE, ratio = 1, k = as.integer(5),
seed = cs_ml_resample_seed(SEED, fold_id, repeat_))
if (fold_id == 0) resampled <<- r$info
r
}
fit_on <- function(s) fit_model(s$X, s$y, s$w)
# %% Model
# CART with scikit-learn's DecisionTree rules and a deterministic split search (features in design
# order) — the codesplash twin, identical in R and Python (rpart differs: surrogates, cp scaling,
# internal cross-validation).
fit_model <- function(X, y, w) {
k <- if (TASK == "regression") 0L else if (TASK == "binary") 2L else length(CLASSES)
cs_ml_cart_fit(X, y, TASK, k, criterion = PARAMS$criterion, max_depth = PARAMS$max_depth,
min_samples_split = as.integer(PARAMS$min_samples_split),
min_samples_leaf = as.integer(PARAMS$min_samples_leaf),
min_impurity_decrease = PARAMS$min_impurity_decrease, ccp_alpha = PARAMS$ccp_alpha, w = w)
}
predict_model <- function(model, X) {
p <- cs_ml_cart_predict(model, X)
if (TASK == "binary") p[, 2] else p
}
feature_importance <- function(model, names) cs_ml_cart_importances(model, names)
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path)
classes <- if (TASK == "binary") c(setdiff(CLASSES, POSITIVE)[1], POSITIVE) else if (length(CLASSES)) CLASSES else NULL
list(list(key = "model", path = path, format = "rds"), cs_ml_tree_json(directory, model, names_, classes))
}
load_model <- function(directory) readRDS(file.path(directory, "model.rds"))
# %% Cross-validation
folds <- if (0 > 0) utils::head(plan$folds, 0) else plan$folds
progress <- cs_progress("Cross-validating", total = length(folds))
for (i in seq_along(folds)) {
fold <- folds[[i]]
prep <- cs_ml_design_fit(design, rows_of(fold$train))
model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(fold$train)), fold$train, fold$id, fold$repeat_))
cs_ml_add(run, fold$id, fold$repeat_, "valid", fold$valid, y, y_index,
predict_model(model, cs_ml_design_apply(prep, rows_of(fold$valid))))
# Training-row predictions for learning / validation curves (never scored as cross-validation).
cs_ml_add(run, fold$id, fold$repeat_, "train", fold$train, y, y_index,
predict_model(model, cs_ml_design_apply(prep, rows_of(fold$train))))
cs_progress_update(progress, i, sprintf("Fold %d of %d", i, length(folds)))
}
cs_ml_lap(run, "cv_seconds")
# %% Final model
artifacts <- list()
importance <- NULL
prep <- cs_ml_design_fit(design, rows_of(plan$train))
names_ <- cs_ml_design_names(prep)
if (FALSE) {
model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(plan$train)), plan$train, 0L, 0L))
if (!is.null(resampled)) {
warnings <- c(warnings, as.list(resampled$notes))
notes <- c(notes, list(cs_ml_resample_describe(resampled)))
}
if (length(plan$test)) {
cs_ml_add(run, 0L, 0L, "test", plan$test, y, y_index,
predict_model(model, cs_ml_design_apply(prep, rows_of(plan$test))))
}
importance <- feature_importance(model, names_)
artifacts[[length(artifacts) + 1L]] <- list(
key = "design", path = cs_ml_save_json(cs_ml_design_json(prep), file.path(out, "design.json")), format = "json"
)
artifacts <- c(artifacts, save_model(model, out))
cs_ml_lap(run, "final_seconds")
}
artifacts[[length(artifacts) + 1L]] <- list(key = "predictions", path = cs_ml_write(run, out), format = "parquet")
cs_progress_done(progress)
# %% Result
cs_publish(cs_ml_result(
run,
title = "Decision tree (CART)",
engine = cs_engine_info("stats", "nanoparquet"),
n_features = length(names_),
n_train = length(plan$train),
n_test = length(plan$test),
params = PARAMS,
features = names_,
importance = importance,
artifacts = artifacts,
warnings = warnings,
notes = notes
))
Decision tree (CART): cross-validated ROC AUC 0.779 ± 0.066 over 5 folds.
- CV ROC AUC
- 0.7792
- SD across folds
- 0.0664
Cross-validation
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 86 | 0.8336 | 3.431 | 0.8256 | 0.8261 |
| 2 | 1 | 85 | 0.6905 | 3.229 | 0.7765 | 0.7243 |
| 3 | 1 | 85 | 0.7575 | 1.716 | 0.7294 | 0.6801 |
| 4 | 1 | 85 | 0.7585 | 3.162 | 0.7412 | 0.7162 |
| 5 | 1 | 85 | 0.8559 | 2.305 | 0.7882 | 0.7395 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Decision tree (CART)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.tree 1.0.0 · spec 6790f4f937df968b
# Dataset: ml_pima (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 ml as csml
from codesplash.ml.tree import CART, tree_json
# %% Data and split plan
TARGET = "diabetic"
FEATURES = ["glu", "bmi", "age", "ped"]
TASK = "binary"
CLASSES = ["false", "true"]
POSITIVE = "true"
METRIC = "roc_auc"
SEED = 42
PARAMS = {
"max_depth": 4,
"min_samples_split": 10,
"min_samples_leaf": 5,
"criterion": "gini",
"min_impurity_decrease": 0,
"ccp_alpha": 0,
}
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.tree/learning_curve_half/folds.parquet") # host-written folds: identical in Python and R
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"glu": "numeric",
"bmi": "numeric",
"age": "numeric",
"ped": "numeric",
},
levels={
},
impute="median",
scale="none",
indicators=False,
)
y, y_index = csml.encode_target(df[TARGET], TASK, CLASSES, POSITIVE)
weights = csml.class_weights(y_index, TASK, "none", plan.train)
run = csml.LearnerRun(TASK, CLASSES, POSITIVE, METRIC)
out = csml.out_dir("target/academy-parity/run-8142/learn.tree/learning_curve_half/out-python")
warnings = []
def sample_weights(rows):
return None if weights is None else weights[rows]
RESAMPLE = "none"
if RESAMPLE != "none" and TASK == "regression":
warnings.append("Resampling applies to classification only — ignored for this regression target.")
resampled = None # the final model's resampling summary
notes = []
def training_set(X, rows, fold_id, repeat):
"""A fit's design matrix, targets and weights: training rows only, resampled when asked
(codesplash.ml.resample — the same rows in R, from the shared random stream)."""
yy, ww = y[rows], sample_weights(rows)
if RESAMPLE == "none" or TASK == "regression":
return X, yy, ww
from codesplash.ml import resample as csres
X2, y2, w2, info = csres.resample(
X, yy, ww, RESAMPLE, ratio=1, k=5, seed=csres.resample_seed(SEED, fold_id, repeat)
)
if fold_id == 0:
global resampled
resampled = info
return X2, y2, w2
# %% Model
# CART with scikit-learn's DecisionTree rules and a deterministic split search (features in design
# order) — the codesplash twin, identical in Python and R.
def fit_model(X, y, w):
k = 0 if TASK == "regression" else (2 if TASK == "binary" else len(CLASSES))
model = CART(
TASK,
k,
criterion=PARAMS["criterion"],
max_depth=PARAMS["max_depth"],
min_samples_split=int(PARAMS["min_samples_split"]),
min_samples_leaf=int(PARAMS["min_samples_leaf"]),
min_impurity_decrease=PARAMS["min_impurity_decrease"],
ccp_alpha=PARAMS["ccp_alpha"],
)
return model.fit(X, y, w)
def predict_model(model, X):
p = model.predict(X)
return p[:, 1] if TASK == "binary" else p
def feature_importance(model, names):
return model.importances(names)
def save_model(model, directory):
import joblib
path = os.path.join(directory, "model.joblib")
joblib.dump(model, path)
if TASK == "binary":
classes = [[c for c in CLASSES if c != POSITIVE][0], POSITIVE] # probabilities: [other, positive]
else:
classes = CLASSES or None
return [{"key": "model", "path": path, "format": "joblib"}, tree_json(directory, model, names, classes)]
def load_model(directory):
import joblib
return joblib.load(os.path.join(directory, "model.joblib"))
# %% Cross-validation
folds = plan.folds[: 0] if 0 else plan.folds
progress = cs.progress("Cross-validating", total=len(folds))
for i, fold in enumerate(folds):
prep = design.fit(df.iloc[fold.train])
model = fit_model(*training_set(prep.transform(df.iloc[fold.train]), fold.train, fold.id, fold.repeat))
run.add(fold.id, fold.repeat, "valid", fold.valid, y, y_index, predict_model(model, prep.transform(df.iloc[fold.valid])))
# Training-row predictions for learning / validation curves (never scored as cross-validation).
run.add(fold.id, fold.repeat, "train", fold.train, y, y_index, predict_model(model, prep.transform(df.iloc[fold.train])))
progress.update(i + 1, f"Fold {i + 1} of {len(folds)}")
run.lap("cv_seconds")
# %% Final model
artifacts = []
importance = None
prep = design.fit(df.iloc[plan.train])
names = prep.names
if False:
model = fit_model(*training_set(prep.transform(df.iloc[plan.train]), plan.train, 0, 0))
if resampled is not None:
from codesplash.ml import resample as csres
warnings.extend(resampled["notes"])
notes.append(csres.describe(resampled))
if len(plan.test):
run.add(0, 0, "test", plan.test, y, y_index, predict_model(model, prep.transform(df.iloc[plan.test])))
importance = feature_importance(model, names)
artifacts.append({"key": "design", "path": csml.save_json(prep.to_json(), os.path.join(out, "design.json")), "format": "json"})
artifacts.extend(save_model(model, out))
run.lap("final_seconds")
artifacts.append({"key": "predictions", "path": run.write(out), "format": "parquet"})
progress.done()
# %% Result
cs.publish(
run.result(
title="Decision tree (CART)",
engine=cs.engine_info("numpy", "numpy", "pandas"),
n_features=len(names),
n_train=len(plan.train),
n_test=len(plan.test),
params=PARAMS,
features=names,
importance=importance,
artifacts=artifacts,
warnings=warnings,
notes=notes,
)
)
Before you spend
ReflectThink of a model you've wanted more data for. How much would it cost to double the rows? A learning curve costs a few minutes. What would you need to see on it to justify that spending, and what would make you spend on features instead?
Check your understanding
CheckpointCheck yourself
Training AUC is 0.99 at all sizes. Validation AUC rises from 0.70 to 0.80 and is still climbing at the end. What's the best reading?
Show the answer
Answer: a
A persistent gap with a rising validation line is the textbook case for more rows. Regularizing can close some of the gap more cheaply.
Check yourself
Why are validation rows kept fixed as the training share grows?
Show the answer
Answer: a
If the validation rows changed too, some of each step would be measuring a harder or easier set of rows.
Check yourself
You want to know which Maximum depth to use. Which should you compute?
Show the answer
Answer: b
A validation curve sweeps one hyperparameter and shows training and validation scores across it.
Compute both
In the appIn a run's Diagnostics tab, press Compute under Learning curve. The banner reads More data would help, Overfitting (variance), Underfitting (bias), Balanced or Unclear. The re-fits are saved as hidden trials of the run, so they don't crowd the leaderboard.
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold, learning_curve
from sklearn.tree import DecisionTreeClassifier
df = pd.read_csv("pima.csv")
X, y = df.drop(columns="diabetic"), df["diabetic"]
cv = StratifiedKFold(5, shuffle=True, random_state=1)
sizes, tr, va = learning_curve(DecisionTreeClassifier(max_depth=4, random_state=1), X, y, cv=cv,
scoring="roc_auc", train_sizes=[0.1, 0.25, 0.5, 0.75, 1.0])
for s, a, b in zip(sizes, tr.mean(axis=1), va.mean(axis=1)):
print(s, round(a, 3), round(b, 3))library(rpart)
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
auc <- function(y, p) as.numeric(pROC::auc(y, p, quiet = TRUE))
set.seed(1)
fold <- sample(rep(1:5, length.out = nrow(df)))
for (share in c(0.25, 0.5, 0.75, 1)) {
s <- sapply(1:5, function(k) {
tr <- df[fold != k, ]; tr <- tr[sample(nrow(tr), round(share * nrow(tr))), ]
fit <- rpart(type ~ ., tr, control = rpart.control(maxdepth = 4, cp = 0))
c(train = auc(tr$type, predict(fit)[, "Yes"]),
valid = auc(df$type[fold == k], predict(fit, df[fold == k, ])[, "Yes"]))
})
cat(share, round(rowMeans(s), 3), "\n")
}Recap
Recap- A learning curve shows whether more rows would pay.
- A gap means variance, and a poor meeting point means bias.
- A validation curve finds the setting once you know which problem you have.
Concepts in this lesson