Uncertainty, structured prediction, and causal learning · Uncertainty, structured prediction, and causal learning · UNC001 · Model
Linear-chain conditional random field (CRF)
Predict a mutually compatible label sequence conditional on the complete observed input. A CRF models dependencies among output labels while allowing overlapping input features.
In CodeSplash
A CodeSplash method runs this entry in Python and R. Set it up from the method's page.
- Conditional random field (sequence labeling) Verified in Python and R
Do it in CodeSplash Run it on your own data, in Python or R.
- Availability
- Runs in CodeSplash
- Code example
- Complete calculation
- Who ran it
- CodeSplash's run and the reference's record
- CodeSplash's run
- Verified in Python and R through learn.crf. The reference's example ran in Python and R here, and they agree.
- The reference's record
- Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.
Purpose
Predict a mutually compatible label sequence conditional on the complete observed input. A CRF models dependencies among output labels while allowing overlapping input features. Its supervised conditional likelihood is different from the generative observation model of an HMM.
Question / hypotheses
Which full label sequence has the largest conditional probability, and how uncertain are its token labels? There is no intrinsic hypothesis-test null; evaluate conditional prediction and structured errors.
Architecture / computational structure
Input-dependent emission scores and adjacent-label transition scores form a chain factor graph. The forward algorithm computes the partition function in O(T K²); forward–backward produces marginals, and Viterbi uses max instead of log-sum-exp for the most probable path. Start/end terms and forbidden transitions must follow one convention.
Assumptions
Training needs representative labeled sequences and an appropriate label inventory. The chain factorization limits output interactions to adjacent states, although input features can examine the whole sequence. Padding is not an observed label; independent train/test units are sequences or subjects, not randomly mixed tokens.
Formula / computational definition
For labels , let . Then and the negative log likelihood is . The forward recursion is .
Parameters and notation
Learned: feature weights, transition scores, and optional boundary scores. Hyperparameters: feature templates, regularization strength, label constraints, optimizer tolerance, and iteration budget. T is sequence length and K is label count; neither is a fitted coefficient. Select regularization by held-out sequence performance, not token-level leakage.
Fitting, fine-tuning, and adaptation
Classical fine-tuning means refitting or warm-starting feature and transition weights on new labeled sequences. Preserve the label mapping and preprocessing. Changing labels requires rebuilding compatible features and transitions; validate target sequences separately and monitor performance on the original domain.
How to use and calibrate
Fit regularized conditional likelihood; compare sequence likelihood, span-level F1, token confusion, and probability calibration. Verify that path scores and partition functions use identical masks. An independently normalized token softmax does not compute the CRF likelihood.
Example application
Tag gene segments or named-entity spans while enforcing transition consistency. Plot a token-by-label marginal heatmap and highlight the Viterbi path to distinguish locally ambiguous tokens from a confident global sequence.
Interpretation / pitfalls
Watch out
The best path is not the sequence of marginally most probable labels. Strong transitions can hide poor emissions; rare labels need class-specific evaluation. General loopy CRFs do not inherit the exact chain inference described here.
Python and R code examples
Scope: Complete partition-function and negative-log-likelihood calculation for a fixed three-token/two-label CRF; it does not estimate feature weights. Enumeration independently checks the dynamic program.
Dependencies / validation: use the shared NumPy/SciPy or base-R setup above. Python executed successfully with assertions; R reviewed but not executed.
Python and R
The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.
Complete calculation — Complete partition-function and negative-log-likelihood calculation for a fixed three-token/two-label CRF; it does not estimate feature weights. Enumeration independently checks the dynamic program.
Shared setup for this chapter
import numpy as np
from scipy.special import logsumexp, gammaln
from scipy.linalg import expm
from itertools import product
def rbf(a, b, ell=1.0):
a, b = np.atleast_2d(a), np.atleast_2d(b)
return np.exp(-np.sum((a[:, None, :] - b[None, :, :])**2, axis=2)/(2*ell**2))
E = np.array([[.8,-.2],[.1,.6],[-.4,.9]])
A = np.array([[.3,-.1],[-.2,.4]])
a = E[0].copy()
for t in range(1,len(E)):
a = E[t] + logsumexp(a[:,None]+A,axis=0)
logZ = logsumexp(a)
paths = np.array(list(product(range(2),repeat=3)))
scores = np.array([E[np.arange(3),p].sum()+A[p[:-1],p[1:]].sum() for p in paths])
y = np.array([0,1,1])
nll = logZ-E[np.arange(3),y].sum()-A[y[:-1],y[1:]].sum()
assert np.allclose(logZ,logsumexp(scores)) and nll >= 0
print({'logZ':float(logZ),'nll':float(nll)})
Complete calculation — Complete partition-function and negative-log-likelihood calculation for a fixed three-token/two-label CRF; it does not estimate feature weights. Enumeration independently checks the dynamic program.
Shared setup for this chapter
lse <- function(z) { m <- max(z); m + log(sum(exp(z-m))) }
rbf <- function(a,b,ell=1) {
a <- as.matrix(a); b <- as.matrix(b)
D <- outer(rowSums(a*a),rowSums(b*b),"+")-2*a%*%t(b)
exp(-pmax(D,0)/(2*ell^2))
}
E <- matrix(c(.8,-.2,.1,.6,-.4,.9),3,2,byrow=TRUE)
A <- matrix(c(.3,-.1,-.2,.4),2,2,byrow=TRUE)
a <- E[1,]
for(t in 2:3) a <- E[t,]+apply(sweep(A,1,a,"+"),2,lse)
logZ <- lse(a)
paths <- as.matrix(expand.grid(rep(list(1:2),3)))
score <- function(p) sum(E[cbind(1:3,p)])+sum(A[cbind(p[1:2],p[2:3])])
scores <- apply(paths,1,score)
nll <- logZ-score(c(1,2,2))
stopifnot(abs(logZ-lse(scores))<1e-12,nll>=0)
print(c(logZ=logZ,nll=nll))
Sources
- Original CRF publication recordcs.cmu.edu
- Sutton–McCallum CRF inference referencearxiv.org
From the CodeSplash reference, entry UNC001.