Classifying images with a pretrained network
Start from a network pretrained on millions of photos and train only what you need (the head, LoRA updates or the top blocks). Group folds by source, read the gallery of mistakes and see with Grad-CAM where it looks.
What runs in CodeSplash
- Image classifier (pretrained ResNet-50 or DINOv2) Experimental
You will be able to
- Explain why a pretrained network needs far fewer labeled images than training from scratch
- Choose between head-only training, LoRA and fine-tuning the top blocks
- Read a confusion gallery and a Grad-CAM overlay, and say why near-duplicate photos call for grouped folds
Borrowing what a network already knows
ReadA network trained from scratch needs thousands of labeled images per class. A pretrained networkTransfer learningReusing a network trained on a large dataset as the start for a new task, so a few hundred images can be enough. has already learned edges, textures and object parts from millions of photos, so its last layer's output is a good description of almost any picture.
The Image classifier keeps that network and adds a new output layer for your classes. Two networks are offered: ResNet-50ResNet-50A 50-layer convolutional network whose blocks add their input back to their output, which lets very deep networks train., a convolutional network trained on ImageNet photos, and DINOv2DINOv2A vision transformer trained without labels to give look-alike images similar vectors; the small model has 384 values.-small, a vision transformer trained without labels. Both run on this computer after a one-time download you approve.
The folder here holds 30 training images of three patterns: horizontal stripes, vertical stripes and a soft blob.
Train only the head
PredictPredict first
With Head only, the network stays frozen: each image's embedding is computed once and only the output layer learns, 6,147 weights out of 25,616,299. How many held-out images do you expect it to classify correctly?
Reveal
Nearly all of them: 100.0% out of fold. The frozen features already separate the patterns, so a linear layer on top is enough. This is a linear probeLinear probeA penalized linear or logistic model trained on a frozen encoder's vectors; how well it does shows what the vectors already encode., and it is the right first try.
Image classifier (pretrained ResNet-50 or DINOv2): cross-validated log loss 0.001 ± 0.000 over 3 folds; log loss on the locked test set 0.000 (n = 6).
- CV log loss
- 0.0006
- SD across folds
- 0.0002
- Test log loss
- 0.0004
Cross-validation
| Fold | Repeat | n | log loss | accuracy | balanced accuracy | F1 |
|---|---|---|---|---|---|---|
| 1 | 1 | 10 | 0.0005 | 1 | 1 | 1 |
| 2 | 1 | 10 | 0.0005 | 1 | 1 | 1 |
| 3 | 1 | 10 | 0.0008 | 1 | 1 | 1 |
Training curves
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| ResNet-50 | 1 | 0.5422 | — |
| ResNet-50 | 2 | 0.0194 | — |
| ResNet-50 | 3 | 0.0033 | — |
| ResNet-50 | 4 | 0.0010 | — |
| ResNet-50 | 5 | 0.0005 | — |
| ResNet-50 | 6 | 0.0003 | — |
| ResNet-50 | 7 | 0.0002 | — |
| ResNet-50 | 8 | 0.0002 | — |
Most frequent mistakes (out of fold)
| Actual | Predicted | Mistakes | Row | Image | P(predicted) |
|---|
The exact R script · R R version 4.5.1 (2025-06-13)
# Image classifier (pretrained ResNet-50 or DINOv2)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.image_classifier 2.0.0 · spec b56e12ad4eeaebeb
# Dataset: img1_shapes (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# torch for R (LibTorch); the backbone and classifier are codesplashr's cs_img_backbone_* / cs_imgcls_* twins.
# %% Data and split plan
TARGET <- "pattern"
FEATURES <- c()
TASK <- "multiclass"
CLASSES <- c("blob", "hstripes", "vstripes")
POSITIVE <- NULL
METRIC <- "log_loss"
SEED <- 42
PARAMS <- list(
backbone = "resnet50",
training = "head",
train_blocks = 1,
lora_rank = 8,
lora_alpha = 16,
image_size = 64,
epochs = 8,
learning_rate = 0.01,
batch_size = 8,
weight_decay = 0.0001,
early_stopping = 0,
validation_fraction = 0.1,
flip = FALSE,
crop = FALSE,
jitter = FALSE,
semi_supervised = "none",
fixmatch_threshold = 0.95,
fixmatch_weight = 1,
fixmatch_ratio = 2,
fixmatch_flip = FALSE,
loss = "cross_entropy",
focal_gamma = 2,
focal_alpha = NULL,
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
label_smoothing = 0,
mixup_alpha = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img1_shapes.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-48082/learn.image_classifier/multiclass_resnet_head/folds.parquet") # host-written folds: identical in Python and R
design <- cs_ml_design(
df, FEATURES,
kinds = list(
),
levels = list(
),
impute = "median",
scale = "standard",
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-48082/learn.image_classifier/multiclass_resnet_head/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
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
label_smoothing = 0,
mixup_alpha = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-48082/learn.image_classifier/multiclass_resnet_head/out-r")
.deep_folds <- length(if (0 > 0) utils::head(plan$folds, 0) else plan$folds)
.deep_training_set <- training_set
# Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build the
# training set as _ml_learn does.
training_set <- function(X, rows, fold_id, repeat_) {
cs_deep_trainer_set_fold(as.integer(fold_id), .deep_folds, if (fold_id > 0) "cv" else "final")
.deep_training_set(X, rows, fold_id, repeat_)
}
# A pretrained ResNet-50 with a new output layer on torch for R (float64, one thread under Parity).
# Training "head": the backbone stays frozen and only the output layer learns, on each image's embedding.
# Images come from the host's media tensors (cs_media_*): RGB in [0, 1], 64 x 64 pixels after the
# shorter side is resized and the center cropped. The frozen part runs once per image; initial weights, batches,
# augmentation and early-stopping rows come from the shared random stream, so Python's torch trains the same network.
IMAGE <- "path"
df <- cs_imgcls_attach_columns(df, "tests/parity/fixtures/img1_shapes.parquet", IMAGE)
# %% 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\":\"shorter_center_crop\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[64,64]}}", simplifyVector = FALSE), "target/academy-parity/run-48082/learn.image_classifier/multiclass_resnet_head/out-r", df,
"tests/parity/fixtures/img1_shapes.parquet")
media_ids <- cs_media_ids(media, df)
# Rows without a readable image (no path, or a file that can't be decoded) leave the split plan, as every media
# method leaves them out: the host's folds and test set keep their other rows (the same rows in Python),
# CS_W_ROWS_DROPPED counts the rows left out, and with no training image left the run stops (twin: imgcls.readable_plan).
.readable <- cs_imgcls_readable_plan(plan, media, media_ids, IMAGE, y_index, TARGET)
plan <- .readable$plan
READABLE <- .readable$readable
warnings <- c(warnings, .readable$notes)
weights <- cs_ml_class_weights(y_index, TASK, "none", plan$train) # from the rows left
.keyed <- cs_imgcls_add_key_column(df, IMAGE, design) # each row's position, carried through the design
df <- .keyed$df
design <- .keyed$design
NET <- cs_imgcls_network(PARAMS$backbone, cs_imgcls_media_loader(media, media_ids, IMAGE, readable = READABLE))
# `prep` is this fit's design (training) or the saved one (score, explain, embed).
.img_rows <- function(X) cs_imgcls_design_rows(X, prep, IMAGE, nrow(df))
fit_model <- function(X, y, w) {
r <- .img_rows(X)
if (TASK == "binary") {
target <- as.numeric(y); o <- 1L
} else {
target <- cs_deep_one_hot(y, length(CLASSES)); o <- length(CLASSES)
}
cs_imgcls_fit(
NET, r$pos, r$Z, target, w, TASK, o,
training = PARAMS$training,
train_blocks = as.integer(PARAMS$train_blocks),
lora_rank = as.integer(PARAMS$lora_rank),
lora_alpha = as.numeric(PARAMS$lora_alpha),
epochs = as.integer(PARAMS$epochs),
lr = as.numeric(PARAMS$learning_rate),
batch_size = if (is.null(PARAMS$batch_size)) NULL else as.integer(PARAMS$batch_size),
weight_decay = as.numeric(PARAMS$weight_decay),
early_stopping = as.integer(PARAMS$early_stopping) > 0,
validation_fraction = as.numeric(PARAMS$validation_fraction),
patience = max(1L, as.integer(PARAMS$early_stopping)),
flip = isTRUE(PARAMS$flip),
crop = isTRUE(PARAMS$crop),
jitter = isTRUE(PARAMS$jitter),
seed = SEED
)
}
predict_model <- function(model, X) {
r <- .img_rows(X)
cs_imgcls_predict(NET, model, r$pos, r$Z, TASK)
}
feature_importance <- function(model, names) NULL
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path) # the trained blocks and output layer (R arrays); the frozen weights stay in the store
hist <- file.path(directory, "history.parquet")
nanoparquet::write_parquet(cs_deep_history_frame(model$history), hist)
list(list(key = "model", path = path, format = "rds"), list(key = "history", path = hist, format = "parquet"))
}
load_model <- function(directory) {
model <- readRDS(file.path(directory, "model.rds"))
# Explanations that read the network (Grad-CAM in the Explain tab) find the images through these.
model$.gradcam <- function(X, cls = NULL, size = 32L) {
r <- .img_rows(X)
cs_imgcls_gradcam(NET, model, r$pos, r$Z, cls = cls, size = size)
}
model$.thumbnails <- function(X, size = 32L) cs_imgcls_thumbnails(NET, .img_rows(X)$pos, size)
model
}
# %% 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_imgcls_extend(cs_ml_result(
run,
title = "Image classifier (pretrained ResNet-50 or DINOv2)",
engine = cs_engine_info("torch", "codesplashr", "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
), model, run, NET, seq_len(nrow(df)) - 1L, function(rows) .img_rows(cs_ml_design_apply(prep, rows_of(rows)))$Z, CLASSES, ids = media_ids))
Image classifier (pretrained ResNet-50 or DINOv2): cross-validated log loss 0.001 ± 0.000 over 3 folds; log loss on the locked test set 0.000 (n = 6).
- CV log loss
- 0.0006
- SD across folds
- 0.0002
- Test log loss
- 0.0004
Cross-validation
| Fold | Repeat | n | log loss | accuracy | balanced accuracy | F1 |
|---|---|---|---|---|---|---|
| 1 | 1 | 10 | 0.0005 | 1 | 1 | 1 |
| 2 | 1 | 10 | 0.0005 | 1 | 1 | 1 |
| 3 | 1 | 10 | 0.0008 | 1 | 1 | 1 |
Training curves
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| ResNet-50 | 1 | 0.5422 | — |
| ResNet-50 | 2 | 0.0194 | — |
| ResNet-50 | 3 | 0.0033 | — |
| ResNet-50 | 4 | 0.0010 | — |
| ResNet-50 | 5 | 0.0005 | — |
| ResNet-50 | 6 | 0.0003 | — |
| ResNet-50 | 7 | 0.0002 | — |
| ResNet-50 | 8 | 0.0002 | — |
Most frequent mistakes (out of fold)
| Actual | Predicted | Mistakes | Row | Image | P(predicted) |
|---|
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Image classifier (pretrained ResNet-50 or DINOv2)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.image_classifier 2.0.0 · spec b56e12ad4eeaebeb
# Dataset: img1_shapes (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.deep import core as deep
from codesplash.images import classifier as imgcls # twin of codesplashr cs_imgcls_* (same weights, draws and AdamW)
# %% Data and split plan
TARGET = "pattern"
FEATURES = []
TASK = "multiclass"
CLASSES = ["blob", "hstripes", "vstripes"]
POSITIVE = None
METRIC = "log_loss"
SEED = 42
PARAMS = {
"backbone": "resnet50",
"training": "head",
"train_blocks": 1,
"lora_rank": 8,
"lora_alpha": 16,
"image_size": 64,
"epochs": 8,
"learning_rate": 0.01,
"batch_size": 8,
"weight_decay": 0.0001,
"early_stopping": 0,
"validation_fraction": 0.1,
"flip": False,
"crop": False,
"jitter": False,
"semi_supervised": "none",
"fixmatch_threshold": 0.95,
"fixmatch_weight": 1,
"fixmatch_ratio": 2,
"fixmatch_flip": False,
"loss": "cross_entropy",
"focal_gamma": 2,
"focal_alpha": None,
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"label_smoothing": 0,
"mixup_alpha": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
}
df = pd.read_parquet("tests/parity/fixtures/img1_shapes.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-48082/learn.image_classifier/multiclass_resnet_head/folds.parquet") # host-written folds: identical in Python and R
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
},
levels={
},
impute="median",
scale="standard",
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-48082/learn.image_classifier/multiclass_resnet_head/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
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"label_smoothing": 0,
"mixup_alpha": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-48082/learn.image_classifier/multiclass_resnet_head/out-python",
)
_DEEP_FOLDS = len(plan.folds[: 0] if 0 else plan.folds)
_deep_training_set = training_set
def training_set(X, rows, fold_id, repeat):
"""Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build
the training set as _ml_learn does."""
deep_trainer.set_fold(int(fold_id), _DEEP_FOLDS, "cv" if fold_id else "final")
return _deep_training_set(X, rows, fold_id, repeat)
# A pretrained ResNet-50 with a new output layer on PyTorch (float64, one thread under Parity).
# Training "head": the backbone stays frozen and only the output layer learns, on each image's embedding.
# Images come from the host's media tensors (codesplash.media): RGB in [0, 1], 64 × 64 pixels after the
# shorter side is resized and the center cropped. The frozen part runs once per image; initial weights, batches,
# augmentation and early-stopping rows come from the shared random stream, so R's torch trains the same network.
IMAGE = "path"
df = imgcls.attach_columns(df, "tests/parity/fixtures/img1_shapes.parquet", IMAGE)
# %% 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\":\"shorter_center_crop\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[64,64]}}"), "target/academy-parity/run-48082/learn.image_classifier/multiclass_resnet_head/out-python", df, "tests/parity/fixtures/img1_shapes.parquet")
media_ids = cs_media.ids_of(media, df)
# Rows without a readable image (no path, or a file that can't be decoded) leave the split plan, as every media
# method leaves them out: the host's folds and test set keep their other rows (the same rows in R), CS_W_ROWS_DROPPED
# counts the rows left out, and with no training image left the run stops (twin: cs_imgcls_readable_plan).
plan, READABLE, _left_out = imgcls.readable_plan(plan, media, media_ids, IMAGE, y_index, TARGET)
warnings.extend(_left_out)
weights = csml.class_weights(y_index, TASK, "none", plan.train) # from the rows left
df = imgcls.add_key_column(df, IMAGE, design) # each row's position, carried through the design
NET = imgcls.Network(PARAMS["backbone"], imgcls.media_loader(media, media_ids, IMAGE, readable=READABLE))
def _rows(X):
# `prep` is this fit's design (training) or the saved one (score, explain, embed).
return imgcls.design_rows(X, prep, IMAGE, len(df))
def fit_model(X, y, w):
pos, Z = _rows(X)
if TASK == "binary":
target, o = np.asarray(y, dtype=np.float64), 1
else:
target, o = deep.one_hot(y, len(CLASSES)), len(CLASSES)
return imgcls.fit(
NET, pos, Z, target, w, TASK, o,
training=PARAMS["training"],
train_blocks=int(PARAMS["train_blocks"]),
lora_rank=int(PARAMS["lora_rank"]),
lora_alpha=float(PARAMS["lora_alpha"]),
epochs=int(PARAMS["epochs"]),
lr=float(PARAMS["learning_rate"]),
batch_size=None if PARAMS["batch_size"] is None else int(PARAMS["batch_size"]),
weight_decay=float(PARAMS["weight_decay"]),
early_stopping=int(PARAMS["early_stopping"]) > 0,
validation_fraction=float(PARAMS["validation_fraction"]),
patience=max(1, int(PARAMS["early_stopping"])),
flip=bool(PARAMS["flip"]),
crop=bool(PARAMS["crop"]),
jitter=bool(PARAMS["jitter"]),
seed=SEED,
)
def predict_model(model, X):
pos, Z = _rows(X)
return imgcls.predict(NET, model, pos, Z, TASK)
def feature_importance(model, names):
return None
def save_model(model, directory):
import joblib
path = os.path.join(directory, "model.joblib")
joblib.dump(model, path) # the trained blocks and output layer (numpy); the frozen weights stay in the store
hist = os.path.join(directory, "history.parquet")
deep.history_frame(model["history"]).to_parquet(hist, index=False)
return [{"key": "model", "path": path, "format": "joblib"}, {"key": "history", "path": hist, "format": "parquet"}]
def load_model(directory):
import joblib
model = joblib.load(os.path.join(directory, "model.joblib"))
# Explanations that read the network (Grad-CAM in the Explain tab) find the images through these.
model["_gradcam"] = lambda X, cls=None, size=32: imgcls.gradcam(NET, model, *_rows(X), cls=cls, size=size)
model["_thumbnails"] = lambda X, size=32: imgcls.thumbnails(NET, _rows(X)[0], size)
return model
# %% 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(
imgcls.extend(run.result(
title="Image classifier (pretrained ResNet-50 or DINOv2)",
engine=cs.engine_info("torch", "safetensors", "codesplash", "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,
), model, run, NET, np.arange(len(df)), lambda rows: _rows(prep.transform(df.iloc[rows]))[1], CLASSES, ids=media_ids)
)
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.
When the head is not enough
Read| Training | What learns | When |
|---|---|---|
| Head only | The output layer | Few images; classes that look like everyday photos |
| LoRA | Small low-rank updates to the top blocks, plus the head | Moderate data; classes the frozen features half separate |
| Fine-tune top blocks | Every weight of the top blocks, plus the head | Many images; scans, diagrams or other unusual pictures |
LoRALoRAFine-tuning that freezes a weight matrix W and trains a small low-rank update B·A added to it, scaled by α/r. adds a product of two thin matrices to each targeted weight, so a block changes while a sliver of the network trains. Here DINOv2's top block adapts with 6,529 trainable weights and tells striped from plain images with an AUC of 1.
AugmentationData augmentationTraining on randomly changed copies of each image (flipped, shifted, recolored) so the model ignores those changes. trains on flipped, shifted and recolored copies, the same in Python and R. It is off by default: use only changes that keep the class.
Photos of the same thing
PredictPredict first
Each pattern here comes from 4 sources, with 3 near-identical shots per source. With a random split, two shots of one source can land on both sides of a fold. What does that do to the cross-validated score?
Reveal
It inflates the score. The model is tested on a near copy of a picture it trained on, which says little about a new source. The LoRA case above groups the folds by source, so every source's shots stay together. Setup warns when an image column has no grouping and offers Group folds by source when the folder has that column.
Mistakes and where the network looks
ReadThe confusion gallery shows the images behind the most frequent mistakes, the surest wrong answer first. This model was stopped after one short epoch on 28-pixel images, so it still mixes classes up: 2 kinds of mistake appear, and its out-of-fold accuracy is 40.0%.
Image classifier (pretrained ResNet-50 or DINOv2): cross-validated log loss 1.004 ± 0.026 over 3 folds; log loss on the locked test set 0.829 (n = 6).
- CV log loss
- 1.004
- SD across folds
- 0.0265
- Test log loss
- 0.8295
Cross-validation
| Fold | Repeat | n | log loss | accuracy | balanced accuracy | F1 |
|---|---|---|---|---|---|---|
| 1 | 1 | 10 | 1.035 | 0.3000 | 0.3333 | 0.1538 |
| 2 | 1 | 10 | 0.9851 | 0.4000 | 0.3333 | 0.1905 |
| 3 | 1 | 10 | 0.9937 | 0.5000 | 0.5556 | 0.4485 |
Training curves
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| ResNet-50 | 1 | 1.180 | — |
Most frequent mistakes (out of fold)
| Actual | Predicted | Mistakes | Row | Image | P(predicted) |
|---|---|---|---|---|---|
| vstripes | hstripes | 10 | 13 | a5b4d35cf856a06f1a8260dfa5ea16eed7faebac1b1bed4098a2eb23afafa2ce | 0.6811 |
| vstripes | hstripes | 10 | 15 | 311aa9cef09e541ea7ee4f941338147e9ca86001b400950f04371743a901d3f3 | 0.6750 |
| vstripes | hstripes | 10 | 23 | 4743b825b1e80f2a8580f5f010aae3a26b19e11e64d8ba4da95e575a060162e6 | 0.6654 |
| vstripes | hstripes | 10 | 22 | 1a1b1b36104cda0082711a0a4594c7f766d02ee20cb959a8d92ecdc6bfb1bbdc | 0.6459 |
| blob | hstripes | 8 | 25 | e3737254bb3a8bce5fe2c0a132802c752aae36058164fde6c2451f5d30e7e960 | 0.4217 |
| blob | hstripes | 8 | 27 | 2b0292d936322add6f739c62dc184ebb5b16ad7a79780ea89a9eec9dbe2d56a6 | 0.4162 |
| blob | hstripes | 8 | 26 | 8c189a553b7052eb0c69ad5e655eb776ac86058481919a427a8e37560aac5c7c | 0.4105 |
| blob | hstripes | 8 | 28 | d655214257593e45321b63942391256a1bc4cb295b2183db9d8c2350efc8497e | 0.4075 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Image classifier (pretrained ResNet-50 or DINOv2)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.image_classifier 2.0.0 · spec 74c8715532fbfdac
# Dataset: img1_shapes (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# torch for R (LibTorch); the backbone and classifier are codesplashr's cs_img_backbone_* / cs_imgcls_* twins.
# %% Data and split plan
TARGET <- "pattern"
FEATURES <- c()
TASK <- "multiclass"
CLASSES <- c("blob", "hstripes", "vstripes")
POSITIVE <- NULL
METRIC <- "log_loss"
SEED <- 42
PARAMS <- list(
backbone = "resnet50",
training = "head",
train_blocks = 1,
lora_rank = 8,
lora_alpha = 16,
image_size = 28,
epochs = 1,
learning_rate = 0.0005,
batch_size = 8,
weight_decay = 0.0001,
early_stopping = 0,
validation_fraction = 0.1,
flip = FALSE,
crop = FALSE,
jitter = FALSE,
semi_supervised = "none",
fixmatch_threshold = 0.95,
fixmatch_weight = 1,
fixmatch_ratio = 2,
fixmatch_flip = FALSE,
loss = "cross_entropy",
focal_gamma = 2,
focal_alpha = NULL,
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
label_smoothing = 0,
mixup_alpha = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img1_shapes.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-48082/learn.image_classifier/multiclass_underfit_confusion_gallery/folds.parquet") # host-written folds: identical in Python and R
design <- cs_ml_design(
df, FEATURES,
kinds = list(
),
levels = list(
),
impute = "median",
scale = "standard",
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-48082/learn.image_classifier/multiclass_underfit_confusion_gallery/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
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
label_smoothing = 0,
mixup_alpha = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-48082/learn.image_classifier/multiclass_underfit_confusion_gallery/out-r")
.deep_folds <- length(if (0 > 0) utils::head(plan$folds, 0) else plan$folds)
.deep_training_set <- training_set
# Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build the
# training set as _ml_learn does.
training_set <- function(X, rows, fold_id, repeat_) {
cs_deep_trainer_set_fold(as.integer(fold_id), .deep_folds, if (fold_id > 0) "cv" else "final")
.deep_training_set(X, rows, fold_id, repeat_)
}
# A pretrained ResNet-50 with a new output layer on torch for R (float64, one thread under Parity).
# Training "head": the backbone stays frozen and only the output layer learns, on each image's embedding.
# Images come from the host's media tensors (cs_media_*): RGB in [0, 1], 28 x 28 pixels after the
# shorter side is resized and the center cropped. The frozen part runs once per image; initial weights, batches,
# augmentation and early-stopping rows come from the shared random stream, so Python's torch trains the same network.
IMAGE <- "path"
df <- cs_imgcls_attach_columns(df, "tests/parity/fixtures/img1_shapes.parquet", IMAGE)
# %% 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\":\"shorter_center_crop\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[28,28]}}", simplifyVector = FALSE), "target/academy-parity/run-48082/learn.image_classifier/multiclass_underfit_confusion_gallery/out-r", df,
"tests/parity/fixtures/img1_shapes.parquet")
media_ids <- cs_media_ids(media, df)
# Rows without a readable image (no path, or a file that can't be decoded) leave the split plan, as every media
# method leaves them out: the host's folds and test set keep their other rows (the same rows in Python),
# CS_W_ROWS_DROPPED counts the rows left out, and with no training image left the run stops (twin: imgcls.readable_plan).
.readable <- cs_imgcls_readable_plan(plan, media, media_ids, IMAGE, y_index, TARGET)
plan <- .readable$plan
READABLE <- .readable$readable
warnings <- c(warnings, .readable$notes)
weights <- cs_ml_class_weights(y_index, TASK, "none", plan$train) # from the rows left
.keyed <- cs_imgcls_add_key_column(df, IMAGE, design) # each row's position, carried through the design
df <- .keyed$df
design <- .keyed$design
NET <- cs_imgcls_network(PARAMS$backbone, cs_imgcls_media_loader(media, media_ids, IMAGE, readable = READABLE))
# `prep` is this fit's design (training) or the saved one (score, explain, embed).
.img_rows <- function(X) cs_imgcls_design_rows(X, prep, IMAGE, nrow(df))
fit_model <- function(X, y, w) {
r <- .img_rows(X)
if (TASK == "binary") {
target <- as.numeric(y); o <- 1L
} else {
target <- cs_deep_one_hot(y, length(CLASSES)); o <- length(CLASSES)
}
cs_imgcls_fit(
NET, r$pos, r$Z, target, w, TASK, o,
training = PARAMS$training,
train_blocks = as.integer(PARAMS$train_blocks),
lora_rank = as.integer(PARAMS$lora_rank),
lora_alpha = as.numeric(PARAMS$lora_alpha),
epochs = as.integer(PARAMS$epochs),
lr = as.numeric(PARAMS$learning_rate),
batch_size = if (is.null(PARAMS$batch_size)) NULL else as.integer(PARAMS$batch_size),
weight_decay = as.numeric(PARAMS$weight_decay),
early_stopping = as.integer(PARAMS$early_stopping) > 0,
validation_fraction = as.numeric(PARAMS$validation_fraction),
patience = max(1L, as.integer(PARAMS$early_stopping)),
flip = isTRUE(PARAMS$flip),
crop = isTRUE(PARAMS$crop),
jitter = isTRUE(PARAMS$jitter),
seed = SEED
)
}
predict_model <- function(model, X) {
r <- .img_rows(X)
cs_imgcls_predict(NET, model, r$pos, r$Z, TASK)
}
feature_importance <- function(model, names) NULL
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path) # the trained blocks and output layer (R arrays); the frozen weights stay in the store
hist <- file.path(directory, "history.parquet")
nanoparquet::write_parquet(cs_deep_history_frame(model$history), hist)
list(list(key = "model", path = path, format = "rds"), list(key = "history", path = hist, format = "parquet"))
}
load_model <- function(directory) {
model <- readRDS(file.path(directory, "model.rds"))
# Explanations that read the network (Grad-CAM in the Explain tab) find the images through these.
model$.gradcam <- function(X, cls = NULL, size = 32L) {
r <- .img_rows(X)
cs_imgcls_gradcam(NET, model, r$pos, r$Z, cls = cls, size = size)
}
model$.thumbnails <- function(X, size = 32L) cs_imgcls_thumbnails(NET, .img_rows(X)$pos, size)
model
}
# %% 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_imgcls_extend(cs_ml_result(
run,
title = "Image classifier (pretrained ResNet-50 or DINOv2)",
engine = cs_engine_info("torch", "codesplashr", "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
), model, run, NET, seq_len(nrow(df)) - 1L, function(rows) .img_rows(cs_ml_design_apply(prep, rows_of(rows)))$Z, CLASSES, ids = media_ids))
Image classifier (pretrained ResNet-50 or DINOv2): cross-validated log loss 1.004 ± 0.026 over 3 folds; log loss on the locked test set 0.829 (n = 6).
- CV log loss
- 1.004
- SD across folds
- 0.0265
- Test log loss
- 0.8295
Cross-validation
| Fold | Repeat | n | log loss | accuracy | balanced accuracy | F1 |
|---|---|---|---|---|---|---|
| 1 | 1 | 10 | 1.035 | 0.3000 | 0.3333 | 0.1538 |
| 2 | 1 | 10 | 0.9851 | 0.4000 | 0.3333 | 0.1905 |
| 3 | 1 | 10 | 0.9937 | 0.5000 | 0.5556 | 0.4485 |
Training curves
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| ResNet-50 | 1 | 1.180 | — |
Most frequent mistakes (out of fold)
| Actual | Predicted | Mistakes | Row | Image | P(predicted) |
|---|---|---|---|---|---|
| vstripes | hstripes | 10 | 13 | a5b4d35cf856a06f1a8260dfa5ea16eed7faebac1b1bed4098a2eb23afafa2ce | 0.6811 |
| vstripes | hstripes | 10 | 15 | 311aa9cef09e541ea7ee4f941338147e9ca86001b400950f04371743a901d3f3 | 0.6750 |
| vstripes | hstripes | 10 | 23 | 4743b825b1e80f2a8580f5f010aae3a26b19e11e64d8ba4da95e575a060162e6 | 0.6654 |
| vstripes | hstripes | 10 | 22 | 1a1b1b36104cda0082711a0a4594c7f766d02ee20cb959a8d92ecdc6bfb1bbdc | 0.6459 |
| blob | hstripes | 8 | 25 | e3737254bb3a8bce5fe2c0a132802c752aae36058164fde6c2451f5d30e7e960 | 0.4217 |
| blob | hstripes | 8 | 27 | 2b0292d936322add6f739c62dc184ebb5b16ad7a79780ea89a9eec9dbe2d56a6 | 0.4162 |
| blob | hstripes | 8 | 26 | 8c189a553b7052eb0c69ad5e655eb776ac86058481919a427a8e37560aac5c7c | 0.4105 |
| blob | hstripes | 8 | 28 | d655214257593e45321b63942391256a1bc4cb295b2183db9d8c2350efc8497e | 0.4075 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Image classifier (pretrained ResNet-50 or DINOv2)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.image_classifier 2.0.0 · spec 74c8715532fbfdac
# Dataset: img1_shapes (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.deep import core as deep
from codesplash.images import classifier as imgcls # twin of codesplashr cs_imgcls_* (same weights, draws and AdamW)
# %% Data and split plan
TARGET = "pattern"
FEATURES = []
TASK = "multiclass"
CLASSES = ["blob", "hstripes", "vstripes"]
POSITIVE = None
METRIC = "log_loss"
SEED = 42
PARAMS = {
"backbone": "resnet50",
"training": "head",
"train_blocks": 1,
"lora_rank": 8,
"lora_alpha": 16,
"image_size": 28,
"epochs": 1,
"learning_rate": 0.0005,
"batch_size": 8,
"weight_decay": 0.0001,
"early_stopping": 0,
"validation_fraction": 0.1,
"flip": False,
"crop": False,
"jitter": False,
"semi_supervised": "none",
"fixmatch_threshold": 0.95,
"fixmatch_weight": 1,
"fixmatch_ratio": 2,
"fixmatch_flip": False,
"loss": "cross_entropy",
"focal_gamma": 2,
"focal_alpha": None,
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"label_smoothing": 0,
"mixup_alpha": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
}
df = pd.read_parquet("tests/parity/fixtures/img1_shapes.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-48082/learn.image_classifier/multiclass_underfit_confusion_gallery/folds.parquet") # host-written folds: identical in Python and R
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
},
levels={
},
impute="median",
scale="standard",
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-48082/learn.image_classifier/multiclass_underfit_confusion_gallery/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
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"label_smoothing": 0,
"mixup_alpha": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-48082/learn.image_classifier/multiclass_underfit_confusion_gallery/out-python",
)
_DEEP_FOLDS = len(plan.folds[: 0] if 0 else plan.folds)
_deep_training_set = training_set
def training_set(X, rows, fold_id, repeat):
"""Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build
the training set as _ml_learn does."""
deep_trainer.set_fold(int(fold_id), _DEEP_FOLDS, "cv" if fold_id else "final")
return _deep_training_set(X, rows, fold_id, repeat)
# A pretrained ResNet-50 with a new output layer on PyTorch (float64, one thread under Parity).
# Training "head": the backbone stays frozen and only the output layer learns, on each image's embedding.
# Images come from the host's media tensors (codesplash.media): RGB in [0, 1], 28 × 28 pixels after the
# shorter side is resized and the center cropped. The frozen part runs once per image; initial weights, batches,
# augmentation and early-stopping rows come from the shared random stream, so R's torch trains the same network.
IMAGE = "path"
df = imgcls.attach_columns(df, "tests/parity/fixtures/img1_shapes.parquet", IMAGE)
# %% 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\":\"shorter_center_crop\",\"mode\":\"rgb\",\"normalize\":\"none\",\"size\":[28,28]}}"), "target/academy-parity/run-48082/learn.image_classifier/multiclass_underfit_confusion_gallery/out-python", df, "tests/parity/fixtures/img1_shapes.parquet")
media_ids = cs_media.ids_of(media, df)
# Rows without a readable image (no path, or a file that can't be decoded) leave the split plan, as every media
# method leaves them out: the host's folds and test set keep their other rows (the same rows in R), CS_W_ROWS_DROPPED
# counts the rows left out, and with no training image left the run stops (twin: cs_imgcls_readable_plan).
plan, READABLE, _left_out = imgcls.readable_plan(plan, media, media_ids, IMAGE, y_index, TARGET)
warnings.extend(_left_out)
weights = csml.class_weights(y_index, TASK, "none", plan.train) # from the rows left
df = imgcls.add_key_column(df, IMAGE, design) # each row's position, carried through the design
NET = imgcls.Network(PARAMS["backbone"], imgcls.media_loader(media, media_ids, IMAGE, readable=READABLE))
def _rows(X):
# `prep` is this fit's design (training) or the saved one (score, explain, embed).
return imgcls.design_rows(X, prep, IMAGE, len(df))
def fit_model(X, y, w):
pos, Z = _rows(X)
if TASK == "binary":
target, o = np.asarray(y, dtype=np.float64), 1
else:
target, o = deep.one_hot(y, len(CLASSES)), len(CLASSES)
return imgcls.fit(
NET, pos, Z, target, w, TASK, o,
training=PARAMS["training"],
train_blocks=int(PARAMS["train_blocks"]),
lora_rank=int(PARAMS["lora_rank"]),
lora_alpha=float(PARAMS["lora_alpha"]),
epochs=int(PARAMS["epochs"]),
lr=float(PARAMS["learning_rate"]),
batch_size=None if PARAMS["batch_size"] is None else int(PARAMS["batch_size"]),
weight_decay=float(PARAMS["weight_decay"]),
early_stopping=int(PARAMS["early_stopping"]) > 0,
validation_fraction=float(PARAMS["validation_fraction"]),
patience=max(1, int(PARAMS["early_stopping"])),
flip=bool(PARAMS["flip"]),
crop=bool(PARAMS["crop"]),
jitter=bool(PARAMS["jitter"]),
seed=SEED,
)
def predict_model(model, X):
pos, Z = _rows(X)
return imgcls.predict(NET, model, pos, Z, TASK)
def feature_importance(model, names):
return None
def save_model(model, directory):
import joblib
path = os.path.join(directory, "model.joblib")
joblib.dump(model, path) # the trained blocks and output layer (numpy); the frozen weights stay in the store
hist = os.path.join(directory, "history.parquet")
deep.history_frame(model["history"]).to_parquet(hist, index=False)
return [{"key": "model", "path": path, "format": "joblib"}, {"key": "history", "path": hist, "format": "parquet"}]
def load_model(directory):
import joblib
model = joblib.load(os.path.join(directory, "model.joblib"))
# Explanations that read the network (Grad-CAM in the Explain tab) find the images through these.
model["_gradcam"] = lambda X, cls=None, size=32: imgcls.gradcam(NET, model, *_rows(X), cls=cls, size=size)
model["_thumbnails"] = lambda X, size=32: imgcls.thumbnails(NET, _rows(X)[0], size)
return model
# %% 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(
imgcls.extend(run.result(
title="Image classifier (pretrained ResNet-50 or DINOv2)",
engine=cs.engine_info("torch", "safetensors", "codesplash", "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,
), model, run, NET, np.arange(len(df)), lambda rows: _rows(prep.transform(df.iloc[rows]))[1], CLASSES, ids=media_ids)
)
Shortened for the Academy: 4 chart(s) dropped to stay under 100 KB; 4 chart(s) dropped to stay under 100 KB.
Grad-CAM lays a heat map over held-out images: the last block's maps weighted by how much they raise the class score. A model that looks at a border, a watermark or the background instead of the object has learned a shortcut, even when its score is high.
Check your understanding
CheckpointCheck yourself
Why can head-only training work with a few dozen images per class?
Show the answer
Answer: a
Only the new output layer learns, on features the pretrained network learned from millions of photos. It has few weights, so few images are enough to fit it.
Check yourself
What does LoRA train in the top blocks?
Show the answer
Answer: b
The update starts at zero and has rank r, so the adapted network starts exactly where the pretrained one was and trains a small fraction of the weights. Training only biases is BitFit.
Check yourself
A folder holds 20 shots each of 50 products. Which split gives an honest estimate for new products?
Show the answer
Answer: b
Shots of one product are near-duplicates: a random split tests on copies of training images. Grouping by product tests every fold on products the model never saw.
Check yourself
A dog-versus-wolf classifier scores well, but its Grad-CAM maps light up the snowy background. What do you conclude?
Show the answer
Answer: a
Grad-CAM shows the regions that raise the class score. A high score earned from the background is a shortcut that fails on new pictures.
Train one
In the appAdd an image folder in Data, then start an experiment with the folder's label as the target. In Setup, choose the path column under Images for Image classifier and group the folds by source; in Learners, select Image classifier. A full fine-tune of the top block with augmentation and one ordinary column reaches a log loss of 0.302 here. The Explain tab draws Grad-CAM for any rows you pick. Rows whose image is missing or can't be read are left out of training and of explanations; when the saved model scores new images, those rows keep empty scores and the run warns how many there are.
Concepts in this lesson