Skip to content

A frozen text encoder with a linear head

Predict from free text with a pretrained sentence encoder that runs on your Mac. The encoder stays frozen; only a penalized linear model is trained, and a saved model embeds new text the same way.

Advanced ~11 min7 steps

What runs in CodeSplash

You will be able to

  • Explain what a frozen encoder with a linear head learns, and what it can't
  • Read the penalty and the embedding components of the model
  • Score new text with a registered model without a separate embedding step

Read first

01

Reading the text, not just counting words

Read

The product reviews in this example are about a coffee maker, headphones or running shoes, and many never name the product. A review like "Brews fast but the carafe drips" never says "coffee maker", so a word-count model would have to learn that "carafe" means coffee. A sentence encoder already places texts about the same thing close together.

The Text encoder learner uses a frozen encoderFrozen text encoderA pretrained model that turns each text into a fixed vector and is not trained further; a small model learns on top of the vectors.. Each review becomes an all-MiniLM-L6-v2 sentence embeddingSentence embeddingA fixed-length vector for a whole text from a model trained so that texts with similar meaning get nearby vectors., the encoder itself isn't trained, and a penalized linear model learns on top. This setup is also called 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..

02

How well does it read?

Predict

Predict first

From the review text and the star rating, the model predicts which of three products a review is about. What cross-validated accuracy do you expect?

About a third (guessing)Around 70%Above 95%
Reveal

The answer: Around 70%

Cross-validated accuracy is 72.9%, with a log loss of 0.616 and an AUC of 0.93. That's well above guessing from 48 training reviews. Reviews about delivery or price, which could be about any product, stay hard.

03

Run it

In the app
Text encoder (MiniLM + linear head)Recorded · Python and R agreeRecorded 2026-11-25 · 47 values compared
R

Text encoder (MiniLM + linear head): cross-validated log loss 0.616 ± 0.166 over 3 folds; log loss on the locked test set 0.416 (n = 12).

CV log loss
0.6155
SD across folds
0.1657
Test log loss
0.4157

Cross-validation

FoldRepeatnlog lossaccuracybalanced accuracyF1
11160.59340.68750.70000.6940
21160.79120.62500.65560.5822
31160.46200.87500.87780.8727

Feature importance

FeatureImportance
review text__pc14.065
review text__pc23.242
review text__pc33.162
review text__pc51.536
review text__pc161.026
review text__pc100.9960
review text__pc120.8694
review text__pc60.7876
review text__pc80.7590
review text__pc150.6920
review text__pc70.5699
review text__pc110.5461
stars0.4219
review text__pc40.3848
review text__pc140.2855
review text__pc130.2710
review text__pc90.1677
The exact R script · R R version 4.5.1 (2025-06-13)
# Text encoder (MiniLM + linear head)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.text_encoder 1.4.0 · spec 514833d0ccd1a30c
# Dataset: txt2_reviews (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 <- "product"
FEATURES <- c("stars")
TASK <- "multiclass"
CLASSES <- c("coffee maker", "headphones", "running shoes")
POSITIVE <- NULL
METRIC <- "log_loss"
SEED <- 42
PARAMS <- list(
  encoder = "minilm",
  penalty = 0.001,
  max_iter = 100,
  mode = "frozen",
  train_layers = 2,
  epochs = 3,
  learning_rate = 0.0001,
  batch_size = 16,
  lora_rank = 8,
  lora_alpha = 16,
  layer_lr_decay = 1,
  gradual_unfreezing = FALSE,
  slanted_triangular = FALSE,
  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
)

# Text this learner embeds itself (frozen all-MiniLM-L6-v2), added as columns once the rows are read.
ENCODE_TEXT <- c("review text")

df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/txt2_reviews.parquet", col_select = unique(c(TARGET, FEATURES, ENCODE_TEXT))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.text_encoder/multiclass_reviews_product/folds.parquet")  # host-written folds: identical in Python and R
# Frozen all-MiniLM-L6-v2 sentence vectors of the text (cs_tenc_add_embedding_columns ↔ codesplash.text.encoder),
# added as `<text>__emb_<i>` columns in every mode, so a saved model embeds new text exactly as in training;
# the design compresses them per fold (0 components keeps all).
encoded_text <- cs_tenc_add_embedding_columns(df, ENCODE_TEXT)
df <- encoded_text$df
EMBED <- encoded_text$embed
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    stars = "numeric"
  ),
  levels = list(
  ),
  impute = "median",
  scale = "standard",
  indicators = FALSE,
  embed = EMBED,
  embed_pcs = 16L
)
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.text_encoder/multiclass_reviews_product/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-8142/learn.text_encoder/multiclass_reviews_product/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 frozen sentence encoder with a linear head. The driver adds the text's all-MiniLM-L6-v2 vectors as
# columns (the same in every mode), the design compresses them per fold (or keeps all with 0 components)
# beside any other features, and an L2-penalized linear model learns on top: ridge for numbers, logistic
# for two classes, multinomial (first class as reference) for more. Intercepts are not penalized.
LAMBDA <- PARAMS$penalty

fit_model <- function(X, y, w) {
  maxit <- as.integer(PARAMS$max_iter)
  if (TASK == "regression") {
    f <- cs_tenc_ridge(X, y, w, LAMBDA)
    return(list(intercept = f$intercept, coef = f$coef, converged = TRUE))
  }
  if (TASK == "binary") return(cs_tenc_logistic_l2(X, y, w, LAMBDA, maxit = maxit))
  cs_tenc_multinomial_l2(X, y, length(CLASSES), w, LAMBDA, maxit = maxit)
}

predict_model <- function(model, X) {
  # Classes whose probability is within 1e-12 of the best (or a probability within 1e-12 of 0.5) are set
  # equal to it, so a tie in exact arithmetic picks the first class in both engines, not rounding noise.
  if (TASK == "multiclass") {
    eta <- sweep(X %*% t(model$coef), 2, model$intercept, "+")
    eta <- eta - apply(eta, 1, max)
    P <- exp(eta)
    P <- P / rowSums(P)
    m <- apply(P, 1, max)
    return(ifelse(P >= m - 1e-12, m, P))
  }
  eta <- model$intercept + as.numeric(X %*% model$coef)
  if (TASK == "regression") return(eta)
  p <- 1 / (1 + exp(-eta))
  ifelse(abs(p - 0.5) <= 1e-12, 0.5, p)
}

feature_importance <- function(model, names) {
  if (!isTRUE(model$converged)) {
    warnings[[length(warnings) + 1L]] <<- "The head did not converge within the iteration limit: raise Maximum iterations or the penalty."
  }
  cs_ml_coef_importance(names, model$coef)
}

save_model <- function(model, directory) {
  path <- file.path(directory, "model.rds")
  saveRDS(model, path)
  list(list(key = "model", path = path, format = "rds"))
}

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))))
  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 = "Text encoder (MiniLM + linear head)",
  engine = cs_engine_info("codesplashr", "stringi", "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
))
Python

Text encoder (MiniLM + linear head): cross-validated log loss 0.616 ± 0.166 over 3 folds; log loss on the locked test set 0.416 (n = 12).

CV log loss
0.6155
SD across folds
0.1657
Test log loss
0.4157

Cross-validation

FoldRepeatnlog lossaccuracybalanced accuracyF1
11160.59340.68750.70000.6940
21160.79120.62500.65560.5822
31160.46200.87500.87780.8727

Feature importance

FeatureImportance
review text__pc14.065
review text__pc23.242
review text__pc33.162
review text__pc51.536
review text__pc161.026
review text__pc100.9960
review text__pc120.8694
review text__pc60.7876
review text__pc80.7590
review text__pc150.6920
review text__pc70.5699
review text__pc110.5461
stars0.4219
review text__pc40.3848
review text__pc140.2855
review text__pc130.2710
review text__pc90.1677
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Text encoder (MiniLM + linear head)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.text_encoder 1.4.0 · spec 514833d0ccd1a30c
# Dataset: txt2_reviews (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 import linear as cslin
from codesplash.text import encoder as cstenc  # frozen MiniLM columns + L2 heads (twin: codesplashr cs_tenc_*)

# %% Data and split plan
TARGET = "product"
FEATURES = ["stars"]
TASK = "multiclass"
CLASSES = ["coffee maker", "headphones", "running shoes"]
POSITIVE = None
METRIC = "log_loss"
SEED = 42
PARAMS = {
    "encoder": "minilm",
    "penalty": 0.001,
    "max_iter": 100,
    "mode": "frozen",
    "train_layers": 2,
    "epochs": 3,
    "learning_rate": 0.0001,
    "batch_size": 16,
    "lora_rank": 8,
    "lora_alpha": 16,
    "layer_lr_decay": 1,
    "gradual_unfreezing": False,
    "slanted_triangular": False,
    "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,
}

# Text this learner embeds itself (frozen all-MiniLM-L6-v2), added as columns once the rows are read.
ENCODE_TEXT = ["review text"]

df = pd.read_parquet("tests/parity/fixtures/txt2_reviews.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES + ENCODE_TEXT)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.text_encoder/multiclass_reviews_product/folds.parquet")  # host-written folds: identical in Python and R
# Frozen all-MiniLM-L6-v2 sentence vectors of the text (codesplash.text.encoder ↔ codesplashr
# cs_tenc_add_embedding_columns), added as `<text>__emb_<i>` columns in every mode, so a saved model
# embeds new text exactly as in training; the design compresses them per fold (0 components keeps all).
from codesplash.text import encoder as cstenc

df, EMBED = cstenc.add_embedding_columns(df, ENCODE_TEXT)
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "stars": "numeric",
    },
    levels={
    },
    impute="median",
    scale="standard",
    indicators=False,
    embed=EMBED,
    embed_pcs=16,
)
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.text_encoder/multiclass_reviews_product/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-8142/learn.text_encoder/multiclass_reviews_product/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 frozen sentence encoder with a linear head. The driver adds the text's all-MiniLM-L6-v2 vectors as
# columns (the same in every mode), the design compresses them per fold (or keeps all with 0 components)
# beside any other features, and an L2-penalized linear model learns on top: ridge for numbers, logistic
# for two classes, multinomial (first class as reference) for more. Intercepts are not penalized.
LAMBDA = PARAMS["penalty"]


def fit_model(X, y, w):
    maxit = int(PARAMS["max_iter"])
    if TASK == "regression":
        b0, b = cstenc.ridge(X, y, w, LAMBDA)
        return {"intercept": b0, "coef": b, "converged": True}
    if TASK == "binary":
        b0, b, ok = cstenc.logistic_l2(X, y, w, LAMBDA, maxit=maxit)
        return {"intercept": b0, "coef": b, "converged": ok}
    b0, B, ok = cstenc.multinomial_l2(X, y, len(CLASSES), w, LAMBDA, maxit=maxit)
    return {"intercept": b0, "coef": B, "converged": ok}


def predict_model(model, X):
    # Classes whose probability is within 1e-12 of the best (or a probability within 1e-12 of 0.5) are set
    # equal to it, so a tie in exact arithmetic picks the first class in both engines, not rounding noise.
    if TASK == "multiclass":
        P = cslin.softmax_rows(model["intercept"][None, :] + X @ model["coef"].T)
        m = P.max(axis=1, keepdims=True)
        return np.where(P >= m - 1e-12, m, P)
    eta = model["intercept"] + X @ model["coef"]
    if TASK == "regression":
        return eta
    p = 1.0 / (1.0 + np.exp(-eta))
    return np.where(np.abs(p - 0.5) <= 1e-12, 0.5, p)


def feature_importance(model, names):
    if not model["converged"]:
        warnings.append("The head did not converge within the iteration limit: raise Maximum iterations or the penalty.")
    return cslin.coef_importance(names, model["coef"])


def save_model(model, directory):
    import joblib

    path = os.path.join(directory, "model.joblib")
    joblib.dump(model, path)
    return [{"key": "model", "path": path, "format": "joblib"}]


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])))
    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="Text encoder (MiniLM + linear head)",
        engine=cs.engine_info("numpy", "pandas", "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,
    )
)

In Predict, pick the review column under Text for Text encoder in Setup, then add the Text encoder learner beside the others.

04

Embedding components

Read

By default, the 384 dimensions are compressed to 16 principal components, learned on each fold's training rows only, so validation rows never shape them. Set the components to 0 to keep every dimension. The binary model "good review or not" keeps all of them and reaches a cross-validated AUC of 0.83.

05

The penalty

Read

The penalty λ shrinks the head's coefficients toward zero; intercepts are free. With λ = 0.1 and only 4 components, the product model is shrunk so hard that accuracy falls to 43.8% and log loss rises to 1.04. Tune λ on a log scale, as for any ridge model.

06

Check your understanding

Checkpoint

Check yourself

Your support tickets use in-house product codes that mean nothing outside the company. Why might a frozen encoder with a linear head struggle?

Show the answer

Answer: a

Only the head learns from your rows. When the meaning lives in vocabulary the encoder never saw, add those columns as ordinary features or use a model that learns the words.

Check yourself

Why are the embedding components learned inside each fold rather than once on all rows?

Show the answer

Answer: a

The encoder is fixed, but PCA learns from data. Fitting it on all rows would let validation rows leak into the features, the same leak as fitting a scaler on all rows.

Check yourself

You raise the penalty λ from 0.001 to 0.1. What happens to the predicted probabilities?

Show the answer

Answer: a

A stronger penalty shrinks the coefficients, so predictions lean on the intercepts: the class shares. Accuracy can hold while the probabilities lose confidence.

07

Recap

Recap
  • A frozen encoder with a linear head trains only the head: it needs fewer rows, but it can't learn words the encoder doesn't know.
  • Components are learned per fold (0 keeps all 384); the penalty shrinks the head.
  • A registered model embeds new text itself, exactly as in training.

Concepts in this lesson