Cross-validation
Give every training row one turn on the held-out side, then read the average and its spread. See what the number of folds trades away.
What runs in CodeSplash
- Random forest Verified in Python and R
You will be able to
- Describe how k-fold cross-validation produces out-of-fold predictions
- Explain what the cross-validated score estimates
- Choose a number of folds, knowing what it trades
Read first
Every row takes a turn
ReadA single split wastes data and depends on luck. Cross-validationCross-validationRotates which part of the data is held out, so every row is used for both training and validation. uses every training row for both jobs:
- Cut the training rows into folds.
- For each fold, fit on the other folds and predict this one.
- Score each fold, then average.
Each row's prediction comes from a model that never saw it. These are out-of-foldOut-of-fold predictionA row's prediction from the cross-validation model that didn't train on that row. predictions, and most of the Evaluation tab is built from them.
Count the rows
PredictPredict first
Pima has 426 training rows and 5 folds. How many rows does each of the five models train on?
Make your guess between 0 and 426 rows, then reveal.
Reveal
About 341: four fifths of the rows. With 2 folds each model sees half the rows, so the estimate is pessimistic for a model fitted on all of them. More folds close that gap, at the cost of more fits.
Change the folds
ExploreMove Folds k and read how This scheme compares with True new-data error, and how much it swings across datasets in Its SD across datasets.
DExplorable · Cross-validation folds
Which rows should be held out so the score predicts real performance?
Each scheme has a tempting shortcut: training error, plain random folds, or the best score from a search. Will the shortcut here look better than the true error on new data?
Scheme
Commit your prediction above to see the result
Make your prediction to see the result.
Press two folds on a small sample. Each model sees half the rows, and the estimate turns pessimistic and jumpy. Five or ten folds is the usual compromise.
What the score estimates
ReadThe average doesn't describe any one fitted model. It estimates how well this recipe (learner, settings, preprocessing) does when given about this many rows.
After cross-validation the app refits the recipe on all training rows to get the final model, and that's the one that scores the test set. Here: cross-validated AUC 0.835, test AUC 0.793.
Random forest: cross-validated ROC AUC 0.835 ± 0.025 over 5 folds; ROC AUC on the locked test set 0.793 (n = 106).
- CV ROC AUC
- 0.8350
- SD across folds
- 0.0252
- Test ROC AUC
- 0.7928
Cross-validation
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 86 | 0.8708 | 0.4292 | 0.8140 | 0.7919 |
| 2 | 1 | 85 | 0.8070 | 0.4964 | 0.7765 | 0.7152 |
| 3 | 1 | 85 | 0.8221 | 0.4836 | 0.8000 | 0.7328 |
| 4 | 1 | 85 | 0.8255 | 0.4856 | 0.7765 | 0.7516 |
| 5 | 1 | 85 | 0.8498 | 0.4441 | 0.7529 | 0.7211 |
Feature importance
| Feature | Importance |
|---|---|
| glu | 0.2929 |
| age | 0.1482 |
| bmi | 0.1481 |
| ped | 0.1469 |
| skin | 0.0963 |
| npreg | 0.0885 |
| bp | 0.0791 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Random forest
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.random_forest 1.0.1 · spec b23f0c5f4083ddc6
# 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)
suppressPackageStartupMessages(library(lightgbm))
# %% Data and split plan
TARGET <- "diabetic"
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
TASK <- "binary"
CLASSES <- c("false", "true")
POSITIVE <- "true"
METRIC <- "roc_auc"
SEED <- 42
PARAMS <- list(
n_estimators = 500,
max_features = "auto",
feature_fraction = 0.5,
max_depth = NULL,
min_samples_leaf = 1,
min_samples_split = 2,
bootstrap = TRUE,
sample_fraction = 1,
implementation = "classic",
threads = 1
)
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.random_forest/binary_pima/folds.parquet") # host-written folds: identical in Python and R
design <- cs_ml_design(
df, FEATURES,
kinds = list(
npreg = "numeric",
glu = "numeric",
bp = "numeric",
skin = "numeric",
bmi = "numeric",
ped = "numeric",
age = "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.random_forest/binary_pima/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
FOREST_KIND <- "rf"
forest_mtry <- function(p) {
cs_ml_mtry(PARAMS$max_features, PARAMS$feature_fraction, p, TASK,
auto_regression = if (FOREST_KIND == "rf") "third" else "all")
}
fit_model <- function(X, y, w) {
p <- ncol(X)
m <- forest_mtry(p)
bootstrap <- isTRUE(PARAMS$bootstrap)
fraction <- if (is.null(PARAMS$sample_fraction)) 1 else PARAMS$sample_fraction
if (identical(PARAMS$implementation, "lightgbm")) {
# LightGBM random-forest mode: the same core (and numbers) in Python and R.
params <- cs_ml_lgb_rf_params(TASK, length(CLASSES), m, p, PARAMS$max_depth, PARAMS$min_samples_leaf,
bootstrap, fraction, SEED, PARAMS$threads)
return(lgb.train(params, lgb.Dataset(unname(X), label = y, weight = w),
nrounds = as.integer(PARAMS$n_estimators), verbose = -1L))
}
colnames(X) <- paste0("f", seq_len(p)) # ranger needs syntactic names
regression <- TASK == "regression"
yy <- if (regression) y else factor(y, levels = if (TASK == "binary") c(0, 1) else seq_along(CLASSES) - 1L)
ranger::ranger(
x = X, y = yy,
num.trees = as.integer(PARAMS$n_estimators),
mtry = m, # = scikit-learn max_features (integer)
max.depth = if (is.null(PARAMS$max_depth)) 0L else as.integer(PARAMS$max_depth), # 0 = unlimited
min.node.size = as.integer(PARAMS$min_samples_split), # = min_samples_split
min.bucket = as.integer(PARAMS$min_samples_leaf), # = min_samples_leaf
replace = bootstrap, # = bootstrap
sample.fraction = if (bootstrap) fraction else 1, # = max_samples
splitrule = if (FOREST_KIND == "extra") "extratrees" else if (regression) "variance" else "gini",
num.random.splits = 1L, # extra trees: one random cut per feature
probability = !regression, # probability forest = mean leaf class shares
case.weights = w,
importance = "impurity",
seed = SEED,
num.threads = as.integer(PARAMS$threads),
verbose = FALSE
)
}
predict_model <- function(model, X) {
if (inherits(model, "lgb.Booster")) return(predict(model, unname(X)))
colnames(X) <- paste0("f", seq_len(ncol(X)))
p <- predict(model, data = X, num.threads = as.integer(PARAMS$threads))$predictions
if (TASK == "regression") return(as.numeric(p))
out <- matrix(0, nrow(X), length(CLASSES))
out[, as.integer(colnames(p)) + 1L] <- p # classes absent from the training rows stay 0
if (TASK == "binary") out[, 2] else out
}
feature_importance <- function(model, names) {
if (inherits(model, "lgb.Booster")) {
imp <- lgb.importance(model, percentage = TRUE) # split gain share (= Python feature_importance)
idx <- as.integer(sub("^Column_", "", imp$Feature)) + 1L
return(stats::setNames(as.list(imp$Gain), names[idx]))
}
# Mean decrease in impurity, normalized to sum to 1 (= scikit-learn feature_importances_).
v <- model$variable.importance
total <- sum(v)
stats::setNames(as.list(if (total > 0) v / total else v), names[as.integer(sub("^f", "", names(v)))])
}
save_model <- function(model, directory) {
if (inherits(model, "lgb.Booster")) {
path <- file.path(directory, "model.txt")
lgb.save(model, path)
return(list(list(key = "model", path = path, format = "lightgbm-txt")))
}
path <- file.path(directory, "model.rds")
saveRDS(model, path)
list(list(key = "model", path = path, format = "rds"))
}
load_model <- function(directory) {
if (file.exists(file.path(directory, "model.txt"))) return(lgb.load(file.path(directory, "model.txt")))
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))))
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 (TRUE) {
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 = "Random forest",
engine = cs_engine_info("ranger", "lightgbm", "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
))
Random forest: cross-validated ROC AUC 0.837 ± 0.031 over 5 folds; ROC AUC on the locked test set 0.786 (n = 106).
- CV ROC AUC
- 0.8371
- SD across folds
- 0.0312
- Test ROC AUC
- 0.7863
Cross-validation
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 86 | 0.8842 | 0.4182 | 0.8140 | 0.7834 |
| 2 | 1 | 85 | 0.8080 | 0.4945 | 0.7647 | 0.6974 |
| 3 | 1 | 85 | 0.8239 | 0.4741 | 0.8000 | 0.7328 |
| 4 | 1 | 85 | 0.8167 | 0.4926 | 0.7882 | 0.7603 |
| 5 | 1 | 85 | 0.8525 | 0.4426 | 0.7529 | 0.7211 |
Feature importance
| Feature | Importance |
|---|---|
| glu | 0.2933 |
| age | 0.1517 |
| bmi | 0.1472 |
| ped | 0.1407 |
| skin | 0.0986 |
| npreg | 0.0878 |
| bp | 0.0806 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Random forest
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.random_forest 1.0.1 · spec b23f0c5f4083ddc6
# 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
import lightgbm as lgb
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from codesplash.ml import forest as csforest
# %% Data and split plan
TARGET = "diabetic"
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
TASK = "binary"
CLASSES = ["false", "true"]
POSITIVE = "true"
METRIC = "roc_auc"
SEED = 42
PARAMS = {
"n_estimators": 500,
"max_features": "auto",
"feature_fraction": 0.5,
"max_depth": None,
"min_samples_leaf": 1,
"min_samples_split": 2,
"bootstrap": True,
"sample_fraction": 1,
"implementation": "classic",
"threads": 1,
}
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.random_forest/binary_pima/folds.parquet") # host-written folds: identical in Python and R
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"npreg": "numeric",
"glu": "numeric",
"bp": "numeric",
"skin": "numeric",
"bmi": "numeric",
"ped": "numeric",
"age": "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.random_forest/binary_pima/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
FOREST_KIND = "rf"
def _is_lgb(model):
return type(model).__module__.startswith("lightgbm")
def _mtry(p):
return csforest.mtry(PARAMS["max_features"], PARAMS["feature_fraction"], p, TASK,
auto_regression="third" if FOREST_KIND == "rf" else "all")
def fit_model(X, y, w):
m = _mtry(X.shape[1])
bootstrap = bool(PARAMS.get("bootstrap", False))
if PARAMS.get("implementation") == "lightgbm":
# LightGBM random-forest mode: the same core (and numbers) in Python and R.
params = csforest.lgb_rf_params(TASK, len(CLASSES), m, X.shape[1], PARAMS["max_depth"],
PARAMS["min_samples_leaf"], bootstrap, PARAMS.get("sample_fraction", 1.0),
SEED, PARAMS["threads"])
return lgb.train(params, lgb.Dataset(X, label=y, weight=w), num_boost_round=int(PARAMS["n_estimators"]))
regression = TASK == "regression"
if FOREST_KIND == "extra":
cls = ExtraTreesRegressor if regression else ExtraTreesClassifier
else:
cls = RandomForestRegressor if regression else RandomForestClassifier
fraction = PARAMS.get("sample_fraction", 1.0)
model = cls(
n_estimators=int(PARAMS["n_estimators"]),
criterion="squared_error" if regression else "gini", # = ranger splitrule variance / gini
max_features=m, # = ranger mtry (integer)
max_depth=None if PARAMS["max_depth"] is None else int(PARAMS["max_depth"]),
min_samples_split=int(PARAMS["min_samples_split"]), # = ranger min.node.size
min_samples_leaf=int(PARAMS["min_samples_leaf"]), # = ranger min.bucket
bootstrap=bootstrap, # = ranger replace
max_samples=fraction if bootstrap and fraction < 1 else None, # = ranger sample.fraction
random_state=SEED,
n_jobs=int(PARAMS["threads"]),
)
return model.fit(X, y if regression else y.astype(int), sample_weight=w)
def predict_model(model, X):
if _is_lgb(model):
return model.predict(X)
if TASK == "regression":
return model.predict(X)
prob = csml.full_proba(model, X, len(CLASSES)) # probability forest: mean leaf class shares
return prob[:, 1] if TASK == "binary" else prob
def feature_importance(model, names):
if _is_lgb(model):
# Split gain share, unused features left out (= R lgb.importance()$Gain).
gain = model.feature_importance(importance_type="gain")
total = float(gain.sum()) or 1.0
return {names[i]: float(g) / total for i, g in enumerate(gain) if g > 0}
# Mean decrease in impurity, normalized to sum to 1 (ranger importance = "impurity", normalized).
return {n: float(v) for n, v in zip(names, model.feature_importances_)}
def save_model(model, directory):
if _is_lgb(model):
path = os.path.join(directory, "model.txt")
model.save_model(path)
return [{"key": "model", "path": path, "format": "lightgbm-txt"}]
import joblib
path = os.path.join(directory, "model.joblib")
joblib.dump(model, path)
return [{"key": "model", "path": path, "format": "joblib"}]
def load_model(directory):
if os.path.exists(os.path.join(directory, "model.txt")):
import lightgbm as lgb
return lgb.Booster(model_file=os.path.join(directory, "model.txt"))
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])))
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 True:
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="Random forest",
engine=cs.engine_info("scikit-learn", "lightgbm", "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,
)
)
Read the spread
ReadEach fold has its own score. The Leaderboard shows the mean plus or minus the SD across folds.
That SD tells you how much a score moves with the rows. It doesn't give a confidence interval for the mean, because the folds share training rows, so they're not independent. Treat a model that's ahead by less than this spread as tied until a paired comparison says otherwise.
Check your understanding
CheckpointCheck yourself
What does a 5-fold cross-validated score estimate?
Show the answer
Answer: b
Cross-validation scores a procedure, not one fitted model. It's a close, slightly pessimistic estimate for the model refitted on all rows.
Check yourself
You raise the folds from 5 to 20. What happens?
Show the answer
Answer: a
More folds change the estimate of performance, not the final model. The price is compute, and the fold scores get noisier because each fold is smaller.
Check yourself
You run 5-fold cross-validation with 4 repeats, plus one final refit. How many times does the model get fitted?
Show the answer
Answer: 21
. This is why Quick tuning is worth using first.
Set your folds
In the appIn Validation, Resampling offers k-fold, Stratified k-fold, Grouped k-fold, Time-series (expanding window) and Single validation split. Automatic chooses from your target, such as {{target}}, and roles. Set Folds and Repeats, and read the strip under Split plan.
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold, cross_val_score
df = pd.read_csv("pima.csv")
X, y = df.drop(columns="diabetic"), df["diabetic"]
cv = StratifiedKFold(5, shuffle=True, random_state=1)
rf = RandomForestClassifier(n_estimators=200, random_state=1)
scores = cross_val_score(rf, X, y, cv=cv, scoring="roc_auc")
print(scores.round(3), scores.mean().round(3), scores.std().round(3))library(ranger)
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
set.seed(1)
fold <- sample(rep(1:5, length.out = nrow(df)))
scores <- sapply(1:5, function(k) {
fit <- ranger(type ~ ., df[fold != k, ], num.trees = 200, probability = TRUE, seed = 1)
p <- predict(fit, df[fold == k, ])$predictions[, "Yes"]
as.numeric(pROC::auc(df$type[fold == k], p, quiet = TRUE))
})
round(c(scores, mean = mean(scores), sd = sd(scores)), 3)Recap
Recap- Each row gets predicted once by a model that didn't see it.
- The score estimates a recipe at about this many rows, and the final model is a refit on them all.
- Five or ten folds is the usual trade. Read the spread before believing a small lead.
Concepts in this lesson