Skip to content

Uncertainty, structured prediction, and causal learning · Uncertainty, structured prediction, and causal learning · UNC002 · Architecture

Neural conditional random field (BiLSTM–CRF family)

Combine learned contextual token representations with globally normalized structured decoding. The neural encoder replaces hand-designed CRF input features; the CRF head preserves label-transition interactions.

Needs a data type CodeSplash doesn't load yet Complete calculation CodeSplash's run and the reference's record

In CodeSplash

Running this needs images, audio, video, graphs or another data type CodeSplash doesn't load yet.

Availability
Needs a data type CodeSplash doesn't load yet
Code example
Complete calculation
Who ran it
CodeSplash's run and the reference's record
CodeSplash's run
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

Combine learned contextual token representations with globally normalized structured decoding. The neural encoder replaces hand-designed CRF input features; the CRF head preserves label-transition interactions. This entry covers the encoder-plus-CRF mechanism rather than counting every encoder checkpoint separately.

Question / hypotheses

Can a contextual encoder and structured output layer jointly improve sequence labels and span boundaries over independent token classifiers? Compare that claim on held-out entities, documents, or subjects.

Architecture / computational structure

A representative implementation embeds words and characters, runs a bidirectional LSTM, maps contextual states to K emission scores, and appends a trainable K-by-K transition matrix. A Transformer can replace the encoder. Gradients of the CRF log partition propagate through the emissions into the encoder.

Assumptions

Gold tokenization and label alignment must match the model. The chain output assumptions remain, but neural optimization is nonconvex. Pretrained encoders can contain domain or benchmark leakage; bidirectional context is incompatible with strict streaming unless a causal variant is deliberately used.

Formula / computational definition

Let H=fθ(x)H=f_\theta(x) and E=HW+bE=HW+b. Minimize L=log⁡Z(E,A)−S(E,A,y)\mathcal L=\log Z(E,A)-S(E,A,y). The emission derivative is ∂L/∂Etk=p(yt=k∣x)−1[yt=k]\partial\mathcal L/\partial E_{tk}=p(y_t=k\mid x)-\mathbf1[y_t=k], linking structured posterior marginals to neural backpropagation.

Parameters and notation

Learned: encoder parameters θ, emission projection W/b, transitions, and optional boundary vectors. Hyperparameters: encoder width/depth, dropout, sequence truncation, learning rates by parameter group, weight decay, gradient clipping, and transition restrictions. A frozen pretrained encoder still leaves a trainable structured head.

Fitting, fine-tuning, and adaptation

Initialize from a suitable encoder, fit the emission/CRF head with the encoder frozen, then optionally unfreeze upper and lower layers at smaller learning rates. Adapt transitions when annotation conventions change. Re-tokenize and realign labels carefully; use a validation domain that represents the intended transfer.

How to use and calibrate

First establish a token-softmax baseline and a fixed-feature CRF baseline. Monitor span F1, entity-type recall, sequence likelihood and calibration; masking correctness matters more than a slightly lower training loss. Plot errors against token length and entity rarity.

Example application

Identify product names and attribute spans in technical descriptions with domain-specific vocabulary. An error audit should separate missed mentions, incorrect boundaries and wrong entity types.

Interpretation / pitfalls

Watch out

Hard transition constraints can silently remove a valid path. Contextual memorization can inflate random-token splits. A low CRF loss is not proof of calibrated span probability; token and span uncertainty require different summaries.

Python and R code examples

Scope: Exact small CRF emission-gradient component after a fixed neural projection. Finite differences verify the marginal-minus-label gradient; no BiLSTM is trained.

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.

Python

Complete calculation — Exact small CRF emission-gradient component after a fixed neural projection. Finite differences verify the marginal-minus-label gradient; no BiLSTM is trained.

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))
H = np.array([[.4,-.1],[.2,.7],[-.5,.3]])
W = np.array([[.8,-.4],[-.2,.5]])
E = H @ W; A = np.array([[.2,-.1],[-.1,.3]])
paths = np.array(list(product(range(2),repeat=3))); gold = np.array([0,1,1])
def loss(e):
    scores = np.array([e[np.arange(3),p].sum()+A[p[:-1],p[1:]].sum() for p in paths])
    return logsumexp(scores)-e[np.arange(3),gold].sum()-A[gold[:-1],gold[1:]].sum(), scores
value,scores = loss(E); prob = np.exp(scores-logsumexp(scores))
grad = sum(prob[i]*(p[1]==1) for i,p in enumerate(paths))-1
plus,minus = E.copy(),E.copy(); plus[1,1]+=1e-6; minus[1,1]-=1e-6
fd = (loss(plus)[0]-loss(minus)[0])/(2e-6)
assert np.isclose(grad,fd,atol=1e-7)
print({'loss':float(value),'emission_gradient':float(grad)})
R

Complete calculation — Exact small CRF emission-gradient component after a fixed neural projection. Finite differences verify the marginal-minus-label gradient; no BiLSTM is trained.

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))
}
H <- matrix(c(.4,-.1,.2,.7,-.5,.3),3,2,byrow=TRUE)
W <- matrix(c(.8,-.4,-.2,.5),2,2,byrow=TRUE)
E <- H%*%W; A <- matrix(c(.2,-.1,-.1,.3),2,2,byrow=TRUE)
paths <- as.matrix(expand.grid(rep(list(1:2),3))); gold <- c(1,2,2)
loss <- function(e) {
 score <- function(p) sum(e[cbind(1:3,p)])+sum(A[cbind(p[1:2],p[2:3])])
 ss <- apply(paths,1,score)
 list(value=lse(ss)-score(gold),scores=ss)
}
v <- loss(E); pr <- exp(v$scores-lse(v$scores))
grad <- sum(pr*(paths[,2]==2))-1
plus <- minus <- E; plus[2,2] <- plus[2,2]+1e-6; minus[2,2] <- minus[2,2]-1e-6
fd <- (loss(plus)$value-loss(minus)$value)/(2e-6)
stopifnot(abs(grad-fd)<1e-7)
print(c(loss=v$value,emission_gradient=grad))

Sources

From the CodeSplash reference, entry UNC002.