Skip to content

Linear-chain CRFs: scoring whole label sequences

A conditional random field scores an entire label sequence, so neighboring labels can constrain each other. The score, the partition function, forward–backward marginals versus the Viterbi path, and how to evaluate spans honestly.

Advanced ~14 min9 steps

What runs in CodeSplash

You will be able to

  • Write the CRF sequence score and its normalized probability
  • Compute the partition function with the forward recursion and explain why it is needed
  • Tell the best path (Viterbi) from the most likely label at each position
  • Split by sequence, evaluate spans, and say how a CRF differs from an HMM

Read first

01

Labels that depend on each other

Read

Tag each word of "New York City" as a place: labeling words one at a time, a classifier might call "York" a person. In sequence labeling, labels depend on their neighbors: an inside-of-entity tag must follow a begin or another inside tag; a machine in "running" rarely jumps straight to "off" without "stopping".

A linear-chain CRFLinear-chain conditional random fieldScores a whole label sequence from each token's features and each pair of neighboring labels, then normalizes over all sequences. predicts the whole sequence at once, scoring each candidate label sequence by how well each label fits its position and how well each label follows the previous one.

Tag a sentence word by word, then let a CRF score the label pairs too.

DExplorable · Sequence labels: a CRF against one token at a time

Tagging each word on its own can produce label sequences that make no sense. What does scoring the whole sequence buy?

With the transition strength above zero, can the CRF's best path contain an I right after an O?

How sure?
2.0

How strongly the CRF scores label pairs: an I after O costs this much. At 0 the CRF is a token-by-token classifier.

1.00

Noise in each word's label scores: higher means a weaker word-level classifier.

OBI53416Thegold O671320newgold O33625boardgold O741016ofgold O203743Acmegold B8784Corpgold I9451metgold O78202ingold O107515Newgold B6490Yorkgold I8839ongold O38602Mondaygold O

Numbers are the CRF's marginal probability (%) of each tag; the blue line is the Viterbi path. Dashed rings are what a token-by-token classifier picks, red when it puts an I with no B before it. Outlined nodes are the gold tags.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

02

The sequence score

Read

For input xx and labels y1:Ty_{1:T}, the score adds emissions (how well label yty_t fits position tt, from any features of the whole input) and transitions (how well yty_t follows yt−1y_{t-1}):

S(x,y)=∑t=1TEt,yt+∑t=2TAyt−1,yt,p(y∣x)=exp⁡S(x,y)Z(x).S(x,y)=\sum_{t=1}^{T}E_{t,y_t}+\sum_{t=2}^{T}A_{y_{t-1},y_t},\qquad p(y\mid x)=\frac{\exp S(x,y)}{Z(x)}.

Z(x)Z(x) sums exp⁡S\exp S over every possible label sequence. Training minimizes log⁡Z(x)−S(x,y)\log Z(x)-S(x,y), with a penalty on the weights. Normalizing each position's softmax separately would be a different, weaker model.

03

Summing over every sequence

Read

With KK labels there are KTK^T sequences, far too many to list. The forward recursion adds them up position by position:

αt(j)=Et,j+logsumexp⁡i[αt−1(i)+Aij],log⁡Z=logsumexp⁡j αT(j).\alpha_t(j)=E_{t,j}+\operatorname{logsumexp}_i\big[\alpha_{t-1}(i)+A_{ij}\big],\qquad \log Z=\operatorname{logsumexp}_j\,\alpha_T(j).

In the reference's small example, log⁡Z\log Z is 3.63 and the true sequence's negative log likelihood 1.03. A backward pass gives each position's marginal p(yt=k∣x)p(y_t=k\mid x); replacing logsumexp with max (Viterbi) gives the single best path.

04

Best path or best labels?

Predict

Predict first

At each position you pick the label with the highest marginal probability. Is that sequence the same as the Viterbi best path?

Always the sameThey can differ
Reveal

They can differ. Position-by-position winners can form a sequence that the transitions make unlikely, even impossible, such as an inside tag right after an outside tag. Viterbi picks the best whole sequence. Use marginals for per-token confidence, and the path for the labels you report.

05

A CRF in CodeSplash

Read
Conditional random field (sequence labeling)Recorded · Python and R agreeRecorded 2026-11-25 · 53 values compared · largest relative difference 1.1e-2
R

Conditional random field (sequence labeling): cross-validated log loss 0.178 ± 0.016 over 3 folds; log loss on the locked test set 0.194 (n = 198).

CV log loss
0.1781
SD across folds
0.0160
Test log loss
0.1937

Plots

Span F1 by type (held-out folds)Which categories lead on a total, mean or median?
View data
Span typeF1
LOC0.9118
PER0.7342
Transition weights (final model)What do the values of a square or rectangular result matrix look like at a glance?
View data
ToFromWeight
B-LOCB-LOC−1.136
B-PERB-LOC−0.2328
I-LOCB-LOC1.639
I-PERB-LOC−0.6319
OB-LOC−0.3805
B-LOCB-PER−0.1236
B-PERB-PER−0.9753
I-LOCB-PER−0.6278
I-PERB-PER1.842
OB-PER−0.1111
B-LOCI-LOC−0.4430
B-PERI-LOC−0.4117
I-LOCI-LOC1.257
I-PERI-LOC−0.3168
OI-LOC−0.1950
B-LOCI-PER−0.3858
B-PERI-PER−0.3347
I-LOCI-PER−0.3768
I-PERI-PER0.6121
OI-PER0.5064
B-LOCO0.7755
B-PERO0.9619
I-LOCO−1.188
I-PERO−1.210
OO1.487

Cross-validation

FoldRepeatnlog lossaccuracybalanced accuracyF1
112650.19650.95470.93800.9299
212610.17080.94640.85730.8903
312640.16700.93940.88380.8849

Spans (held-out folds, Viterbi path)

Span typePrecisionRecallF1True spansPredicted spans
LOC0.92540.89860.91186967
PER0.77330.69880.73428375
All spans0.84510.78950.8163152142

Transition weights (row: from, column: to)

FromB-LOCB-PERI-LOCI-PERO
B-LOC−1.136−0.23281.639−0.6319−0.3805
B-PER−0.1236−0.9753−0.62781.842−0.1111
I-LOC−0.4430−0.41171.257−0.3168−0.1950
I-PER−0.3858−0.3347−0.37680.61210.5064
O0.77550.9619−1.188−1.2101.487

Largest state weights per label (final model)

LabelFeatureWeight
B-LOCgaz1.968
B-LOCshape=x−0.5703
B-LOClen0.4420
B-LOCtitle−0.1850
B-LOCshape=d−0.1490
B-PERgaz−1.137
B-PERtitle0.8546
B-PERshape=Xx0.7125
B-PERshape=x−0.6000
B-PERcap0.5894
I-LOCgaz1.151
I-LOClen−0.3225
I-LOCtitle−0.2820
I-LOCshape=d−0.1093
I-LOCshape=Xx−0.1078
I-PERgaz−0.9031
I-PERshape=x−0.6372
I-PERcap0.4958
I-PERlen0.4759
I-PERshape=Xx0.4627
Oshape=x1.708
Ocap−1.205
Ogaz−1.079
Oshape=Xx−0.9203
Oshape=d0.8609
The exact R script · R R version 4.5.1 (2025-06-13)
# Conditional random field (sequence labeling)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.crf 1.0.0 · spec d81a3fde1e0224e4
# Dataset: seq_ner (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
# The linear-chain CRF is codesplashr's cs_crf_* twin of codesplash.ml.crf (written out; CRFsuite is the oracle).

# %% Data and split plan
TARGET <- "tag"
FEATURES <- c("cap", "len", "shape", "title", "gaz")
TASK <- "multiclass"
CLASSES <- c("B-LOC", "B-PER", "I-LOC", "I-PER", "O")
POSITIVE <- NULL
METRIC <- "log_loss"
SEED <- 42
PARAMS <- list(
  c2 = 1,
  c1 = 0,
  max_iterations = 1000,
  tolerance = 1e-10,
  spans = "auto",
  outside = "O"
)

df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/seq_ner.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-8142/learn.crf/ner_bio_defaults/folds.parquet")  # host-written folds: identical in Python and R
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    cap = "numeric",
    len = "numeric",
    shape = "categorical",
    title = "numeric",
    gaz = "numeric"
  ),
  levels = list(
    shape = c("X", "Xx", "d", "x")
  ),
  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-8142/learn.crf/ner_bio_defaults/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
# A linear-chain conditional random field: rows that share a sequence id form a sequence (the Groups role, so a
# sequence never straddles folds), ordered by the position column (or the input order). State weights read the
# fold's design, transition weights link neighboring labels; L-BFGS minimizes the penalized negative
# log-likelihood from zero, the same iterations in Python and R. Probabilities are the per-token marginals; span
# metrics come from the Viterbi path.
SEQ_ID <- "sentence"  # the Sequence id role
POSITION <- "position"  # optional: order of the tokens inside a sequence
FIT_FINAL <- TRUE
LABELS <- if (TASK == "binary") c(setdiff(CLASSES, POSITIVE), POSITIVE) else as.character(CLASSES)  # label of each code
N_INPUT <- nrow(df)

# Each input row's sequence id and position (NULL when a column isn't in this input, e.g. scoring data).
read_sequence_columns <- function() {
  if (is.null(SEQ_ID)) return(list(ids = NULL, pos = NULL))
  frame <- tryCatch(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/seq_ner.parquet", col_select = c(SEQ_ID, POSITION))),
                    error = function(e) NULL)
  if (is.null(frame)) return(list(ids = NULL, pos = NULL))
  ids <- frame[[SEQ_ID]]
  if (is.factor(ids)) ids <- as.character(ids)
  pos <- if (is.null(POSITION)) NULL else suppressWarnings(as.numeric(frame[[POSITION]]))
  list(ids = ids, pos = pos)
}

.seq_cols <- read_sequence_columns()
SEQ_VALUES <- .seq_cols$ids
POS_VALUES <- .seq_cols$pos

# Each design matrix the driver makes knows its input rows (attribute cs_rows, 0-based, from the frame's row names).
.cs_crf_design_apply <- cs_ml_design_apply
cs_ml_design_apply <- function(prep, frame) {
  X <- .cs_crf_design_apply(prep, frame)
  attr(X, "cs_rows") <- as.integer(rownames(frame)) - 1L
  X
}
DECODED <- new.env(parent = emptyenv())  # decoded row sets (cs_crf_remember: sorted rows + Viterbi codes), for the span metrics

# The input rows of a design matrix: carried by training matrices; otherwise every input row (scoring).
rows_of_X <- function(X) {
  n <- nrow(X)
  r <- attr(X, "cs_rows")
  if (!is.null(r) && length(r) == n) return(as.integer(r))
  if (n == N_INPUT) return(seq_len(n) - 1L)
  NULL
}

sequences_of <- function(X) {
  rows <- rows_of_X(X)
  if (is.null(rows) || is.null(SEQ_VALUES)) {
    cs_error("CS_E_INVALID_VALUES", column = if (is.null(SEQ_ID)) "Sequence id" else SEQ_ID,
             requirement = "in the data with every token of each sequence (a CRF labels whole sequences)", count = nrow(X))
  }
  ids <- SEQ_VALUES[rows + 1L]
  pos <- if (is.null(POS_VALUES)) NULL else POS_VALUES[rows + 1L]
  cs_crf_check_sequences(ids, pos, SEQ_ID, POSITION)
  list(rows = rows, ids = ids, pos = pos)
}

fit_model <- function(X, y, w) {
  if (length(LABELS) > 100L) cs_error("CS_E_TOO_MANY_LEVELS", column = TARGET, k = length(LABELS), max = 100L)  # K^2 transition weights
  if (length(unique(as.numeric(y))) < 2L) cs_error("CS_E_TOO_FEW_GROUPS", column = TARGET, min = 2L, k = length(unique(as.numeric(y))))
  if (!is.null(w)) cs_error("CS_E_INVALID_OPTION", option = "Class weights", allowed = "none for a CRF (its likelihood is per sequence)", value = "on")
  if (is.null(attr(X, "cs_rows"))) cs_error("CS_E_INVALID_OPTION", option = "Resampling", allowed = "none for a CRF (rows belong to sequences)", value = "on")
  s <- sequences_of(X)
  cs_crf_fit(unname(as.matrix(X)), as.integer(y), s$ids, s$pos, length(LABELS),
             c2 = as.numeric(PARAMS$c2), c1 = as.numeric(PARAMS$c1), max_iter = as.integer(PARAMS$max_iterations),
             tol = as.numeric(PARAMS$tolerance))
}

predict_model <- function(model, X) {
  s <- sequences_of(X)
  M <- unname(as.matrix(X))
  P <- cs_crf_marginals(model, M, s$ids, s$pos)
  path <- cs_crf_viterbi(model, M, s$ids, s$pos)
  o <- order(s$rows)
  cs_crf_remember(DECODED, s$rows[o], path[o])
  if (TASK == "binary") P[, 2] else P
}

feature_importance <- function(model, names) NULL

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_crf_extend_result(cs_ml_result(
  run,
  title = "Conditional random field (sequence labeling)",
  engine = cs_engine_info("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
), if (FIT_FINAL) model else NULL, DECODED, cs_ml_frame(run), y, SEQ_VALUES, POS_VALUES, LABELS, PARAMS$spans, PARAMS$outside, names_))
Python

Conditional random field (sequence labeling): cross-validated log loss 0.178 ± 0.016 over 3 folds; log loss on the locked test set 0.194 (n = 198).

CV log loss
0.1781
SD across folds
0.0160
Test log loss
0.1937

To keep this page light, the plots are shown once, under the R tab.

Cross-validation

FoldRepeatnlog lossaccuracybalanced accuracyF1
112650.19650.95470.93800.9299
212610.17080.94640.85730.8903
312640.16700.93940.88380.8849

Spans (held-out folds, Viterbi path)

Span typePrecisionRecallF1True spansPredicted spans
LOC0.92540.89860.91186967
PER0.77330.69880.73428375
All spans0.84510.78950.8163152142

Transition weights (row: from, column: to)

FromB-LOCB-PERI-LOCI-PERO
B-LOC−1.136−0.23281.639−0.6319−0.3805
B-PER−0.1236−0.9753−0.62781.842−0.1111
I-LOC−0.4430−0.41171.257−0.3168−0.1950
I-PER−0.3858−0.3347−0.37680.61210.5064
O0.77550.9619−1.188−1.2101.487

Largest state weights per label (final model)

LabelFeatureWeight
B-LOCgaz1.968
B-LOCshape=x−0.5703
B-LOClen0.4420
B-LOCtitle−0.1850
B-LOCshape=d−0.1490
B-PERgaz−1.137
B-PERtitle0.8546
B-PERshape=Xx0.7125
B-PERshape=x−0.6000
B-PERcap0.5894
I-LOCgaz1.151
I-LOClen−0.3225
I-LOCtitle−0.2820
I-LOCshape=d−0.1093
I-LOCshape=Xx−0.1078
I-PERgaz−0.9031
I-PERshape=x−0.6372
I-PERcap0.4958
I-PERlen0.4759
I-PERshape=Xx0.4627
Oshape=x1.708
Ocap−1.205
Ogaz−1.079
Oshape=Xx−0.9203
Oshape=d0.8609
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Conditional random field (sequence labeling)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.crf 1.0.0 · spec d81a3fde1e0224e4
# Dataset: seq_ner (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 crf as cscrf  # written-out twin of codesplashr cs_crf_* (CRFsuite is the oracle)

# %% Data and split plan
TARGET = "tag"
FEATURES = ["cap", "len", "shape", "title", "gaz"]
TASK = "multiclass"
CLASSES = ["B-LOC", "B-PER", "I-LOC", "I-PER", "O"]
POSITIVE = None
METRIC = "log_loss"
SEED = 42
PARAMS = {
    "c2": 1,
    "c1": 0,
    "max_iterations": 1000,
    "tolerance": 1e-10,
    "spans": "auto",
    "outside": "O",
}

df = pd.read_parquet("tests/parity/fixtures/seq_ner.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-8142/learn.crf/ner_bio_defaults/folds.parquet")  # host-written folds: identical in Python and R
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "cap": "numeric",
        "len": "numeric",
        "shape": "categorical",
        "title": "numeric",
        "gaz": "numeric",
    },
    levels={
        "shape": ["X", "Xx", "d", "x"],
    },
    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-8142/learn.crf/ner_bio_defaults/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
# A linear-chain conditional random field: rows that share a sequence id form a sequence (the Groups role, so a
# sequence never straddles folds), ordered by the position column (or the input order). State weights read the
# fold's design, transition weights link neighboring labels; L-BFGS minimizes the penalized negative
# log-likelihood from zero, the same iterations in Python and R. Probabilities are the per-token marginals; span
# metrics come from the Viterbi path.
SEQ_ID = "sentence"  # the Sequence id role
POSITION = "position"  # optional: order of the tokens inside a sequence
FIT_FINAL = True
LABELS = ([c for c in CLASSES if c != POSITIVE] + [POSITIVE]) if TASK == "binary" else list(CLASSES)  # label of each code
N_INPUT = len(df)


def read_sequence_columns():
    """Each input row's sequence id and position (None when a column isn't in this input, e.g. scoring data)."""
    if SEQ_ID is None:
        return None, None
    try:
        frame = pd.read_parquet("tests/parity/fixtures/seq_ner.parquet", columns=[c for c in (SEQ_ID, POSITION) if c])
    except Exception:  # noqa: BLE001 — the columns are not in this input
        return None, None
    ids = frame[SEQ_ID].astype("object").where(frame[SEQ_ID].notna(), None).to_numpy(dtype=object)
    pos = pd.to_numeric(frame[POSITION], errors="coerce").to_numpy(dtype=np.float64) if POSITION else None
    return ids, pos


SEQ_VALUES, POS_VALUES = read_sequence_columns()


class SeqDesign:
    """The driver's design; each design matrix it makes knows its input rows (codesplash.ml.crf.TokenRows)."""

    def __init__(self, inner):
        self._inner = inner

    def fit(self, frame):
        return SeqPrep(self._inner.fit(frame))

    def __getattr__(self, name):
        return getattr(self._inner, name)


class SeqPrep:
    def __init__(self, inner):
        self._inner = inner

    def transform(self, frame):
        return cscrf.TokenRows(self._inner.transform(frame), frame.index.to_numpy())

    def __getattr__(self, name):
        return getattr(self._inner, name)


design = SeqDesign(design)
DECODED = {}  # sorted rows → {row: Viterbi code}, for the span metrics


def rows_of(X):
    """The input rows of a design matrix: carried by training matrices; otherwise every input row (scoring)."""
    n = int(np.asarray(X).shape[0])
    r = getattr(X, "rows", None)
    if r is not None and len(r) == n:
        return np.asarray(r, dtype=np.int64)
    if n == N_INPUT:
        return np.arange(n, dtype=np.int64)
    return None


def sequences_of(X):
    rows = rows_of(X)
    if rows is None or SEQ_VALUES is None:
        cs.cs_error("CS_E_INVALID_VALUES", column=SEQ_ID or "Sequence id", requirement="in the data with every token of each sequence (a CRF labels whole sequences)", count=int(np.asarray(X).shape[0]))
    ids = SEQ_VALUES[rows]
    pos = None if POS_VALUES is None else POS_VALUES[rows]
    cscrf.check_sequences(ids, pos, SEQ_ID, POSITION)
    return rows, ids, pos


def fit_model(X, y, w):
    if len(LABELS) > cscrf.MAX_LABELS:
        cs.cs_error("CS_E_TOO_MANY_LEVELS", column=TARGET, k=len(LABELS), max=cscrf.MAX_LABELS)
    if len(np.unique(np.asarray(y))) < 2:
        cs.cs_error("CS_E_TOO_FEW_GROUPS", column=TARGET, min=2, k=int(len(np.unique(np.asarray(y)))))
    if w is not None:
        cs.cs_error("CS_E_INVALID_OPTION", option="Class weights", allowed="none for a CRF (its likelihood is per sequence)", value="on")
    if getattr(X, "rows", None) is None:
        cs.cs_error("CS_E_INVALID_OPTION", option="Resampling", allowed="none for a CRF (rows belong to sequences)", value="on")
    _, ids, pos = sequences_of(X)
    return cscrf.fit(
        np.asarray(X), np.asarray(y).astype(np.int64), ids, pos, len(LABELS),
        c2=float(PARAMS["c2"]), c1=float(PARAMS["c1"]), max_iter=int(PARAMS["max_iterations"]), tol=float(PARAMS["tolerance"]),
    )


def predict_model(model, X):
    rows, ids, pos = sequences_of(X)
    P = cscrf.marginals(model, np.asarray(X), ids, pos)
    path = cscrf.viterbi(model, np.asarray(X), ids, pos)
    DECODED[tuple(sorted(int(r) for r in rows))] = {int(r): int(c) for r, c in zip(rows, path)}
    return P[:, 1] if TASK == "binary" else P


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)
    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(
    cscrf.extend_result(run.result(
        title="Conditional random field (sequence labeling)",
        engine=cs.engine_info("numpy", "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 if FIT_FINAL else None, DECODED, run.frame(), y, SEQ_VALUES, POS_VALUES, LABELS, PARAMS["spans"], PARAMS["outside"], names)
)

On short tagged sentences the held-out token accuracy was 93.9%, but span F1, where a whole entity must be right, was 0.761. Token accuracy flatters: the many "outside" tokens are easy. Report spans, and per label, because rare labels hide in the average.

06

Evaluation and the HMM

Read

Split by sequence (or by speaker, document, machine), never by token: tokens of one sentence share context, and mixing them across train and test leaks. Make sure the score and ZZ use the same mask, so padding is never a label.

Strong transitions can cover for weak emissions, producing tidy but wrong runs; check the confusion of labels and calibration of marginals. And keep a CRF apart from an HMM: the HMM is generative, modeling how the inputs arise from hidden states, while the CRF models labels given the full input and can use overlapping features freely.

07

Where it stands in CodeSplash

Read
EntryIn CodeSplash
Linear-chain CRF (UNC001)Runs in CodeSplash: Conditional random field (sequence labeling), new this wave, on token or time-step tables with a sequence id
08

Check your understanding

Checkpoint

Check yourself

Why does a CRF need the partition function Z(x)?

Show the answer

Answer: b

p(y∣x)=exp⁡S(x,y)/Z(x)p(y\mid x)=\exp S(x,y)/Z(x). The forward recursion computes log⁡Z\log Z without listing the KTK^T sequences.

Check yourself

What do the transition weights AijA_{ij} capture?

Show the answer

Answer: a

Emissions score fit to the input; transitions score fit to the neighbor. Together they make the whole-sequence score.

Check yourself

How should you split data to evaluate a CRF?

Show the answer

Answer: b

Tokens of one sequence share context. Splitting them across train and test leaks information and inflates scores.

Check yourself

A CRF reaches high token accuracy but modest span F1. What should you report?

Show the answer

Answer: b

Entities are spans; getting most tokens right can still miss many entity boundaries.

09

Do it on your own data

In the app

In Predict, choose Conditional random field (sequence labeling), set Sequence id (and Position if rows aren't in order), and compare span F1 on held-out sequences with a token-by-token classifier on the same split.

Concepts in this lesson