Change-point detection
Detect changes in a time series distribution online or retrospectively, using Page's CUSUM, Bayesian online change-point detection, penalized segmentation, binary segmentation, dynamic programming and PELT.
After this lesson you can
- Implement CUSUM for a mean shift and calibrate its threshold for a target ARL_0 by simulation.
- Formulate segmentation as penalized optimization and solve it exactly with dynamic programming and PELT.
- Compare binary segmentation, PELT and BOCPD in accuracy, cost and sensitivity to penalty.
- Implement BOCPD with a normal-gamma predictive distribution and read the run-length matrix.
- Evaluate detectors using change-point metrics, including precision and recall with tolerance, Hausdorff distance and delay.
Before you start
- 26Weak (second-order) stationarityWhite noise and its variantsMartingaleOrder selection with information criteriaMarkov-switching model
- 05Sequential probability ratio testConjugate priorsPosterior predictive distribution
- 14Multivariate conjugate priors (Normal-gamma, Normal-Wishart)
- 08Dynamic programming
Did the process change or were we just unlucky?
A sustained increase in latency after releasing a version, a change in market volatility or a shift in network traffic can have very different consequences. The common statistical question is whether the law generating a series has changed. Online, decisions must use data available up to that moment; offline, we can examine the whole series and locate breaks retrospectively.
The change-point problem seeks dates separating segments with different laws. The mean, variance or dependence can change, and a gradual transition need not have a unique true date. The interactive generates normal observations with a known jump: move the change and observe what happens when more evidence is required.
CUSUM: accumulated evidence and reset
Suppose independent observations have density before the change and afterwards. For a candidate change , the log likelihood ratio accumulated through is . Maximizing over all possible starts and adding the option not to start gives one-sided CUSUM:
The recurrence is equivalent to an SPRT that discards accumulated evidence when it becomes negative and starts again. For versus , with and known variance, . A downward change requires another detector or a two-sided test; one designed for a particular magnitude can detect other magnitudes less well.
The trade-off between false alarms and delay is expressed through , the mean time until the first alarm when the distribution never changes, and a measure of delay under change. Lorden’s criterion takes the worst change time and worst admissible prior observation history. Under suitable assumptions of independence and known pre- and post-change densities, CUSUM has an exact optimality property for that criterion; see Moustakides’ proof. This conclusion does not turn a threshold selected under an incorrect model into a guarantee for autocorrelated data.
A finite horizon causes censoring: if no alarm appears through , we know , not . The mean of estimates a restricted expectation, less than or equal to ARL₀. To measure delay in simulation, report pre-change alarms, cases not detected by the horizon and delay conditional on valid cases separately.
Segmenting the whole series
With cut indices , penalized segmentation minimizes
For example, with independent normal observations and known variance , cost is twice the negative log-likelihood, up to a common constant. The penalty must be on the same scale as the cost. With one mean per segment and known variance, corresponds to penalizing each new mean in BIC, ignoring additional treatment of discrete positions. If variances are also estimated or positions penalized, specify the criterion and number of parameters. A solution path for several values of , such as CROPS, shows sensitivity; selecting a solution because it confirms a hypothesis does not provide validation.
Binary segmentation finds the best split of the full segment and repeats on the two subsegments if the cost warrants it. It is fast but greedy: an initial split can prevent the global optimum. Wild binary segmentation also examines selected intervals in the series to discover changes that cancel in large intervals; its result depends on the intervals examined.
Exact dynamic programming uses and
Segment costs are obtained in constant time with cumulative sums, but there are candidates in the worst case. PELT retains the optimum and discards candidates under a verifiable condition: if for every , and hold, then cannot be the last optimal cut before . This is safe pruning, not a universal promise of linear time: cost remains quadratic in the worst case. With a minimum segment length, elimination must wait until is an admissible candidate for the future.
A distribution over run length
Adams and MacKay’s Bayesian online change-point detection maintains a distribution over , the number of observations since the last change under their convention. Each hypothesis grows by one observation or ends with hazard , and is weighted by the run’s predictive distribution. The probability matrix shows growth diagonals and mass in short runs when a change hypothesis gains support.
In the original convention, the observation is first evaluated with each run’s predictive distribution and then it is decided whether that run ends. With constant hazard , normalization makes exactly: that cell alone is not a variable surprise signal. Examine the distribution’s mode or mass of short positive runs. Another convention may put the change before the observation and use the prior predictive for the new segment, but it must be declared because its indices and probabilities differ.
With unknown mean and precision, the normal-gamma prior yields a Student predictive distribution with degrees of freedom and scale . After observing , , , and . Student scale is not generally its standard deviation. Cost without truncation grows quadratically with series length; truncating and renormalizing controls memory and time, but approximates the posterior.
Lab: calibrate and compare
We simulate data with a fixed seed. For each null trajectory, the detector calculates its first crossing. Calibration targets a restricted expectation and shows how many trajectories reach the horizon without an alarm. Changing the seed, horizon or jump magnitude changes the result: this is not a universal table.
import numpy as np
from scipy.special import gammaln
rng = np.random.default_rng(421)
trayectorias = rng.normal(size=(400, 1200))
def primer_cruce(y, h, delta=1.):
w = 0.
for i, x in enumerate(y, 1):
w = max(0., w + delta*x - delta**2/2)
if w >= h:
return i
return len(y)+1
def restringida(h):
w = np.zeros(len(trayectorias))
tiempos = np.full(len(trayectorias),trayectorias.shape[1]+1)
for t in range(trayectorias.shape[1]):
w = np.maximum(0.,w+trayectorias[:,t]-.5)
nuevos = (w>=h) & (tiempos>trayectorias.shape[1])
tiempos[nuevos] = t+1
return np.minimum(tiempos, trayectorias.shape[1]).mean(), np.mean(tiempos > trayectorias.shape[1])
objetivo = 100.
lo, hi = .1, 5.
for _ in range(10):
mid = (lo+hi)/2
if restringida(mid)[0] < objetivo:
lo = mid
else:
hi = mid
h = (lo+hi)/2
print("umbral, media restringida y fracción censurada:", h, restringida(h))
prueba = rng.normal(size=(250,300))
tau=80
prueba[:,tau-1:] += 1.
tiempos=np.array([primer_cruce(fila,h) for fila in prueba])
previas=tiempos<tau
detectadas=(tiempos>=tau)&(tiempos<=prueba.shape[1])
print("prueba independiente: alarmas previas, detectadas, censuradas:",
previas.sum(),detectadas.sum(),np.sum(tiempos>prueba.shape[1]))
print("retardo medio condicionado a detectar sin alarma previa:",
np.mean(tiempos[detectadas]-tau+1))The sum-of-squares cost is additive for constant segments and satisfies the pruning condition with . This example permits segments of length one. Variance estimated per segment requires a minimum length and a constraint preventing variance collapse; pruning must respect candidate admissibility.
def prefijos(y):
centrada=y-y[0]
return np.r_[0.,np.cumsum(centrada)], np.r_[0.,np.cumsum(centrada*centrada)]
def coste(pref, a, b):
s,q = pref
return max(0., q[b]-q[a]-(s[b]-s[a])**2/(b-a))
def segmentar(y, beta, poda=False):
n = len(y); pref = prefijos(np.asarray(y))
F = np.full(n+1,np.inf); F[0] = -beta
anterior = np.zeros(n+1,dtype=int)
candidatos = [0]
for s in range(1,n+1):
cs = np.array([F[t]+coste(pref,t,s)+beta for t in candidatos])
j = int(np.argmin(cs)); F[s] = cs[j]; anterior[s] = candidatos[j]
if poda:
candidatos = [t for t in candidatos if F[t]+coste(pref,t,s) <= F[s]+1e-10]
candidatos.append(s)
cortes = []; s = n
while anterior[s] > 0:
s = anterior[s]; cortes.append(s)
return sorted(cortes), F[n]
def binaria(y, beta):
pref = prefijos(np.asarray(y)); cortes = []
def partir(a,b):
if b-a < 2: return
valores = [(coste(pref,a,k)+coste(pref,k,b),k) for k in range(a+1,b)]
mejor,k = min(valores)
if coste(pref,a,b)-mejor > beta:
cortes.append(k); partir(a,k); partir(k,b)
partir(0,len(y))
return sorted(cortes)
y = np.r_[rng.normal(0,1,60),rng.normal(2,1,60),rng.normal(-1,1,60)]
beta = 2*np.log(len(y))
dp = segmentar(y,beta); pe = segmentar(y,beta,True); bs = binaria(y,beta)
print("DP, PELT y binaria:", dp, pe, bs)
print("coinciden los costes óptimos:", np.isclose(dp[1],pe[1]))The following filter uses the convention of resetting after evaluating each observation. The matrix is cut to the indicated lengths and renormalized after discarding the tail: if the discarded tail is substantial, the approximation can alter the result.
def bocpd(y, hazard=.02, maxrun=150, prior=(0.,1.,1.,1.)):
mu0,k0,a0,b0 = prior
mu=np.array([mu0]); k=np.array([k0]); a=np.array([a0]); b=np.array([b0])
p=np.array([1.]); matriz=np.zeros((len(y)+1,maxrun+1)); matriz[0,0]=1.
descartada=0.
for t,x in enumerate(y,1):
nu=2*a; escala=np.sqrt(b*(k+1)/(a*k))
z=(x-mu)/escala
logpred = gammaln((nu+1)/2)-gammaln(nu/2)-.5*np.log(nu*np.pi)-np.log(escala)-(nu+1)/2*np.log1p(z*z/nu)
pesos = p*np.exp(logpred-np.max(logpred))
total = pesos.sum()
nueva=np.r_[hazard*total,(1-hazard)*pesos]/total
if len(nueva)>maxrun+1:
descartada=max(descartada,nueva[-1]); nueva=nueva[:maxrun+1]; nueva/=nueva.sum()
kn=k+1
bn=b+k*(x-mu)**2/(2*kn)
mun=(k*mu+x)/kn
mu=np.r_[mu0,mun][:len(nueva)]
b=np.r_[b0,bn][:len(nueva)]
a=np.r_[a0,a+.5][:len(nueva)]
k=np.r_[k0,kn][:len(nueva)]
p=nueva
matriz[t,:len(p)]=p
return matriz, descartada
R,cola=bocpd(y)
print("probabilidad de racha cero, masa máxima descartada:",
R[1:,0].min(),R[1:,0].max(),cola)
print("modos alrededor de los cambios:", np.argmax(R,axis=1)[[55,60,65,115,120,125]])To compare with another implementation, we install the pure Python version of ruptures. This cell needs a network connection the first time; the final returned index is the end of the series, not a change. We match cost, penalty, minimum length and candidate grid before comparing.
import micropip
await micropip.install('ruptures==1.0.6')
import ruptures as rpt
externo=rpt.Pelt(model="l2",min_size=1,jump=1).fit(y).predict(pen=beta)
print("ruptures sin final:",externo[:-1],"propio:",pe[0])What good detection means
Precision divides matched detections by all detections; recall divides matched changes by all true changes. Match at most one detection to each change within a time tolerance fixed in advance. For nonempty sets, Hausdorff distance is the maximum of the two directed distances between dates. If one is empty, we declare infinite distance here; if both are empty, zero. No metric replaces online alarm delay.
def metricas(reales, detectados, margen):
a,b=sorted(reales),sorted(detectados)
i=j=aciertos=0
while i<len(a) and j<len(b):
if abs(a[i]-b[j])<=margen:
aciertos+=1; i+=1; j+=1
elif b[j]<a[i]-margen:
j+=1
else:
i+=1
precision=aciertos/len(b) if b else (1. if not a else 0.)
recall=aciertos/len(a) if a else (1. if not b else 0.)
if not a or not b:
hausdorff=0. if not a and not b else np.inf
else:
hausdorff=max(max(min(abs(x-z) for z in b) for x in a),
max(min(abs(x-z) for z in a) for x in b))
return precision,recall,hausdorff
for nombre, cortes in [("DP",dp[0]),("PELT",pe[0]),("binaria",bs)]:
print(nombre, metricas([60,120],cortes,5))
modo=np.argmax(R,axis=1)
alarmas_bocpd=[t for t in range(2,len(modo)) if modo[t]<modo[t-1]]
print("cambios de modo BOCPD y métricas:", alarmas_bocpd, metricas([60,120],alarmas_bocpd,5))
import time
for nombre, metodo in [("DP",lambda:segmentar(y,beta)),
("PELT",lambda:segmentar(y,beta,True)),
("binaria",lambda:binaria(y,beta)),
("BOCPD",lambda:bocpd(y))]:
inicio=time.perf_counter(); metodo(); duracion=time.perf_counter()-inicio
print(nombre,"tiempo de esta ejecución, segundos:",duracion)
print("costes candidatos del ejercicio:", [(k,coste(prefijos(np.array([1.,2.,4.,5.])),0,k)+coste(prefijos(np.array([1.,2.,4.,5.])),k,4)) for k in (1,2,3)])
print("coste sin dividir:", coste(prefijos(np.array([1.,2.,4.,5.])),0,4))The previous comparison knows the truth because the series is simulated. Now we use real performance measurements from the SAP HANA collection, series 0002. The published annotation indicates a regression at cut 54; the data record a build change between measurements 54 and 55. The source does not identify the unit or claim these are production latency measurements: they are performance tests across versions, not evidence of a service deployment. We retain the values to run the example without downloading data.
real = np.array([48.942, 49.7, 49.382, 49.04, 49.2, 48.302, 48.96, 48.296, 47.66, 48.98, 49.1, 48.44, 48.78, 49.28, 49.822, 49.578, 47.7, 48.482, 48.9, 48.942, 49, 49.178, 48.88, 48.064, 48.882, 49.42, 49.04, 48.52, 48.64, 48.918, 48.78, 48.14, 48.558, 49.66, 49.72, 49.498, 48.882, 49.682, 49.418, 47.618, 48.86, 48.84, 50.72, 49.658, 48.54, 48.6, 49.44, 48.7, 47.598, 48, 49.36, 46.918, 48, 46.582, 50.962, 53.582, 52.582, 53.276, 52.558, 53.1, 52.32, 52.7, 53.22, 52.74, 53.22, 53.34, 53.462, 52.52, 53.58, 54.26, 52.82, 53.06, 53.182, 53.82, 51.6, 53.278, 53.8, 53.482, 53.2, 52.8, 52.32, 52.46, 53.958, 53.34, 51.962, 52.76, 52.36, 52.902, 52.74, 52.936, 53.34, 53.14, 50.46, 53.34, 52.3, 53.642, 53.224, 51.94, 54.102, 53.782, 53.462, 51.564, 53.138, 53.158, 53.72, 52.618, 52.16, 51.36, 51.6, 53.184, 51.62, 52.48, 52, 53.222])
corte_referencia = 54
pen_real = 2*np.log(len(real))
propio_real = segmentar(real,pen_real,True)
externo_real = rpt.Pelt(model="l2",min_size=1,jump=1).fit(real).predict(pen=pen_real)[:-1]
print("mediciones y medias antes/después del corte anotado:",
len(real),real[:corte_referencia].mean(),real[corte_referencia:].mean())
print("cortes propio y ruptures:",propio_real[0],externo_real)
print("precisión, exhaustividad y Hausdorff con margen 5:",
metricas([corte_referencia],propio_real[0],5))A deployment date is an observable intervention, not proof that the distribution changed then: load changes or incidents may coincide. To evaluate a detector, retain independent timestamps, distinguish deployment time from measured change and do not use evaluation labels to choose the threshold. An annotated benchmark allows method comparison, but its tolerance and annotation criteria matter. Here penalty tuning is illustrative and the real series checks one case, not overall detector quality.
To obtain actually measured latencies with a known version change, the next local experiment starts an HTTP service on the loopback interface. It serves requests with an initial implementation and then replaces the function with a second that performs more cryptographic work before responding. Each point is the actual time of a request, not a sample from a simulated distribution. The deployment marker is the boundary between the blocks. This is a controlled deployment on the same machine, not a production trace; the operating system, machine load and local connection can change the result.
The cell is self-contained and runs in local Python. It standardizes latency with the mean and deviation of the first version, applies sum-of-squares PELT and compares the detected cut with the known boundary. The threshold is illustrative and must not be interpreted as a false-alarm guarantee. The server closes even if a request fails.
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from threading import Thread
from urllib.request import urlopen
import hashlib, time, math
import numpy as np
def version_uno():
return hashlib.pbkdf2_hmac("sha256",b"solicitud",b"oryon",500)
def version_dos():
return hashlib.pbkdf2_hmac("sha256",b"solicitud",b"oryon",80000)
implementacion = version_uno
class Servicio(BaseHTTPRequestHandler):
def do_GET(self):
payload = implementacion()
self.send_response(200)
self.send_header("Content-Length",str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def log_message(self, format, *args):
pass
server = ThreadingHTTPServer(("127.0.0.1",0),Servicio)
hilo = Thread(target=server.serve_forever,daemon=True)
hilo.start()
url = "http://127.0.0.1:" + str(server.server_port) + "/"
latencias = []
def medir():
inicio = time.perf_counter()
with urlopen(url,timeout=10) as respuesta:
respuesta.read()
return 1000*(time.perf_counter()-inicio)
try:
medir() # Calentamiento excluido.
for _ in range(40):
latencias.append(medir())
despliegue = len(latencias)
implementacion = version_dos
for _ in range(40):
latencias.append(medir())
finally:
server.shutdown()
server.server_close()
hilo.join()
observada=np.asarray(latencias)
escala=max(observada[:despliegue].std(ddof=1),1e-6)
z=(observada-observada[:despliegue].mean())/escala
pref=np.r_[0.,np.cumsum(z)]; cuadrados=np.r_[0.,np.cumsum(z*z)]
def coste_local(a,b):
return max(0.,cuadrados[b]-cuadrados[a]-(pref[b]-pref[a])**2/(b-a))
pen=2*math.log(len(z))
F=np.full(len(z)+1,np.inf); F[0]=-pen
anterior=np.zeros(len(z)+1,dtype=int); candidatos=[0]
for s in range(1,len(z)+1):
valores=[F[t]+coste_local(t,s)+pen for t in candidatos]
j=int(np.argmin(valores)); F[s]=valores[j]; anterior[s]=candidatos[j]
candidatos=[t for t in candidatos if F[t]+coste_local(t,s)<=F[s]+1e-9]
candidatos.append(s)
cortes=[]; s=len(z)
while anterior[s]>0:
s=anterior[s]; cortes.append(int(s))
cortes.sort()
distancia=min((abs(t-despliegue) for t in cortes),default=None)
print("peticiones por versión, frontera:",despliegue,len(z)-despliegue,despliegue)
print("medianas reales en milisegundos:",np.median(observada[:despliegue]),np.median(observada[despliegue:]))
print("cortes PELT, distancia mínima a la frontera:",cortes,distancia)npm run lab and open the connection link.Exercises
Step 1 of 2. How do you express the maximum accumulated from any start, including the option to reset?
Step 1 of 2. What lower bound applies to the cost of using t as the last cut before T?
import numpy as np
def pelt(y, beta):
passSequential detection and retrospective segmentation answer different questions. Guarantees depend on the model, loss criterion and available information; calibration and evaluation must preserve those conditions.