Module contents
Lesson 21 of 31Core 110 min

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

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.

InteractiveA threshold for monitoring a stream

Before τ, Xₜ is normal N(0,1); from τ it is N(1,1), with independent observations. The log ratio of the two densities is Xₜ−0.5. CUSUM resets to zero: Sₜ=max(0,Sₜ₋₁+Xₜ−0.5), with S₀=0. The first alarm occurs when Sₜ≥h.

On the example path, move the change marker with mouse, touch or arrow keys. The same normal shocks are retained as it moves; the detector is not restarted after an alarm.

Time t; change from τ=70
  • Data and CUSUM
  • Threshold and first alarm
  • True change τ

Trade-off curve calculated with 220 simulated paths, horizon 5000 and the same shocks for all thresholds. The horizontal axis estimates E[min(T,5000)] under no change. This restricted expectation is at most ARL₀, but its sample estimate fluctuates and does not identify full ARL₀ under censoring.

The vertical axis averages min(T−τ+1, 4931) over paths without an alarm before τ. Earlier alarms are excluded and the number of eligible runs still without an alarm at the horizon is reported. This conditional delay is not Lorden’s worst case; it can fluctuate substantially with few eligible paths.

Horizontal: restricted null time; vertical: restricted conditional delay. Highlighted point: h=2.5.

The threshold is selected on a grid of 9 values; moving it does not redraw paths. The same innovations compare thresholds and scenarios with and without change. Results are Monte Carlo estimates, not exact values.

2.5
70
First alarm in exampleAlarm at t=71, delay 2
Restricted mean time under null67.7
Null paths without alarm at horizon0 / 220
Restricted mean delay4.8
Alarms before change144 / 220
Eligible paths undetected at horizon0 / 76
Seed2621
Compare alarms and delay with simulated trajectories; censoring is shown explicitly.

CUSUM: accumulated evidence and reset

Suppose independent observations have density f0f_0 before the change and f1f_1 afterwards. For a candidate change kk, the log likelihood ratio accumulated through tt is ∑i=ktlog⁡[f1(Yi)/f0(Yi)]\sum_{i=k}^{t}\log[f_1(Y_i)/f_0(Y_i)]. Maximizing over all possible starts and adding the option not to start gives one-sided CUSUM:

W0=0,Wt=max⁡{0,Wt−1+ℓt},ℓt=log⁡f1(Yt)f0(Yt),Th=inf⁡{t:Wt≥h}.W_0=0,\qquad W_t=\max\{0,W_{t-1}+\ell_t\},\quad \ell_t=\log\frac{f_1(Y_t)}{f_0(Y_t)},\quad T_h=\inf\{t:W_t\ge h\}.

The recurrence is equivalent to an SPRT that discards accumulated evidence when it becomes negative and starts again. For N(μ0,σ2)N(\mu_0,\sigma^2) versus N(μ0+δ,σ2)N(\mu_0+\delta,\sigma^2), with δ>0\delta>0 and known variance, ℓt=δ(Yt−μ0)/σ2−δ2/(2σ2)\ell_t=\delta(Y_t-\mu_0)/\sigma^2-\delta^2/(2\sigma^2). 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 ARL⁡0=E∞[Th]\operatorname{ARL}_0=E_\infty[T_h], 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 HH, we know Th>HT_h>H, not Th=HT_h=H. The mean of min⁡(Th,H)\min(T_h,H) 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 0=τ0<⋯<τm+1=n0=\tau_0<\cdots<\tau_{m+1}=n, penalized segmentation minimizes

∑j=0mC(yτj+1:τj+1)+βm.\sum_{j=0}^{m} C(y_{\tau_j+1:\tau_{j+1}})+\beta m.

For example, with independent normal observations and known variance σ2\sigma^2, cost C(a:b)=∑i=a+1b(yi−yˉa+1:b)2/σ2C(a:b)=\sum_{i=a+1}^{b}(y_i-\bar y_{a+1:b})^2/\sigma^2 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, β=log⁡n\beta=\log n 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 β\beta, 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 F(0)=−βF(0)=-\beta and

F(s)=min⁡0≤t<s{F(t)+C(t:s)+β}.F(s)=\min_{0\le t<s}\{F(t)+C(t:s)+\beta\}.

Segment costs are obtained in constant time with cumulative sums, but there are O(n2)O(n^2) candidates in the worst case. PELT retains the optimum and discards candidates under a verifiable condition: if for every t<s<Tt<s<T, C(t:T)≥C(t:s)+C(s:T)+KC(t:T)\ge C(t:s)+C(s:T)+K and F(t)+C(t:s)+K>F(s)F(t)+C(t:s)+K>F(s) hold, then tt cannot be the last optimal cut before TT. 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 ss is an admissible candidate for the future.

InteractiveThe price of adding breaks

Gaussian sample of 96 observations: it was generated with true changes after observations 24, 48 and 72.

  • Observations
  • Fitted mean
  • Selected cut

Minimum unpenalized cost for each number of changes. The highlighted point minimizes BIC.

  • Optimal cost
  • BIC
  • Current selection

In each segment, C=n log(2πv)+SSE/v, with v=max(SSE/n, 0.16). Mean and variance are fitted and at least 8 observations are required. PELT minimizes ΣC+βK; the lower curve is calculated using exact dynamic programming for each K.

Here BIC means ΣC+(2(K+1)+K) log N: two parameters per segment and one discrete parameter per change. It is an approximate selection criterion, not a guarantee of recovering true changes. With this definition it is equivalent to β=3 log N, apart from a constant.

14
1
Selected changes3
Cut positions25, 48, 72
Cost + β × changes232.8
BIC: changes3
BIC penalty per change13.69
Explore the relationship between penalty, cost and number of changes for a simulated series.

A distribution over run length

Adams and MacKay’s Bayesian online change-point detection maintains a distribution over rtr_t, the number of observations since the last change under their convention. Each hypothesis grows by one observation or ends with hazard H(r)H(r), 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 HH, normalization makes P(rt=0∣y1:t)=HP(r_t=0\mid y_{1:t})=H 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 (μ,κ,α,β)(\mu,\kappa,\alpha,\beta) yields a Student predictive distribution with 2α2\alpha degrees of freedom and scale β(κ+1)/(ακ)\sqrt{\beta(\kappa+1)/(\alpha\kappa)}. After observing xx, κ′=κ+1\kappa'=\kappa+1, μ′=(κμ+x)/κ′\mu'=(\kappa\mu+x)/\kappa', α′=α+1/2\alpha'=\alpha+1/2 and β′=β+κ(x−μ)2/(2κ′)\beta'=\beta+\kappa(x-\mu)^2/(2\kappa'). 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.

InteractivePossible runs

The observation has known changes before indices 30 and 60. The dark vertical line marks the selected date; dashed lines mark those changes only because the generator is known.

Each column shows the posterior run-length distribution after observing that date: r = 0 is at the bottom. Blue intensity increases with the square root of probability; blank regions are impossible or have very small probability.

03060900306089
Observation index · vertical axis: run length
observation 89 / 89

The next curve shows cumulative probability of positive run lengths from 1 to 5; it may rise after a change, but can also give false alarms or react late. At the beginning it is high because long runs do not yet exist, without implying a break.

In this BOCPD convention the observation is predicted using the previous run, then a new run is decided. With constant hazard H, posterior probability of r = 0 is exactly H at every date: it is not a data-dependent change signal. If a change occurs before xₜ, a short positive run can reflect it after xₜ is observed.

Generator: 90 independent normal observations with σ = 0.6 and means 0, 2 and −1 in the three segments. The fitted model uses unknown mean and precision per segment with normal-gamma prior μ₀ = 0, κ = 1.0, α = 2 and β = 1. The predictive distribution is Student with 2α degrees of freedom and scale √[β(κ+1)/(ακ)]. All possible run lengths are retained; exact computation grows quadratically with length.

Hazard H = 1/40 implies a prior geometric mean duration of 40 observations, not an estimated duration. The prior and independence within each segment are assumptions; there is no guarantee that every change is detected. Reference: Adams and MacKay, Bayesian Online Changepoint Detection.

40
1.0
Observed index89
Hazard H2.50 %
P(run length 0)2.50 %
P(run length 1 to 5)3.03 %
Most likely run length30
Seed2621
Adjust the hazard and prior; observe how the distribution changes, not just its mode.

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.

[ ]CUSUM and simulation calibrationBrowser
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 K=0K=0. 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.

[ ]Dynamic programming, pruning and binary segmentationBrowser
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.

[ ]BOCPD with normal-gamma predictive distributionBrowser
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.

[ ]Comparison with rupturesBrowser
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.

[ ]Metrics with toleranceBrowser
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.

[ ]An annotated real seriesBrowser
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.

[ ]Measure latency across two local deploymentsLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofResetting the SPRT
Prove: Show the equivalence between CUSUM and the maximum accumulated evidence from a candidate start.
0
Let Lₜ be the cumulative sum of log increments through t, with L₀=0.

Step 1 of 2. How do you express the maximum accumulated from any start, including the option to reset?

ProofWhy pruning preserves the optimum
Prove: Suppose C(t:T) ≥ C(t:s)+C(s:T)+K for every admissible future T. Show that if F(t)+C(t:s)+K > F(s), candidate t can be discarded for those futures.
0
F(s) is the best penalized cost through s; the same penalty is added to each new segment.

Step 1 of 2. What lower bound applies to the cost of using t as the last cut before T?

NumericThe gain from splitting
For data 1, 2, 4, 5 and known variance 1, calculate how much the sum of squares decreases when splitting after the second observation.
QuizDependence and false alarms
A highly persistent AR(1), with no mean changes, produces many alarms in a detector calibrated for independent noise. What explains this and what do you do?
CodePELT with mean-segmentation cost
Implement pelt(y,beta) for sum of squares with nonempty segments and positive beta. Return the sorted list of internal cuts and penalized cost, without counting the end as a cut. Prune only when the condition with K=0 permits it.
import numpy as np

def pelt(y, beta):
  pass
Shift+Enter to run
Key idea

Sequential detection and retrospective segmentation answer different questions. Guarantees depend on the model, loss criterion and available information; calibration and evaluation must preserve those conditions.