Urban Analytics & Transportation · Part 6 of 7

Filling the Holes

A hole is an empty cell of the response. The fit already holds its predictive distribution; a forecast only needs the later rows hidden.

To predict a cell, leave it empty

Since Part 2 the response has been empty, NaN, on every row the model may not see. pyINLA does not drop such rows. It still computes the posterior of the sum of the terms on them, from everything the other rows say about those terms. So the fit of Part 5 has already filled every hole. What is left is to turn its answer into a statement about a count.

1. From the terms to the count. Call the sum of the terms on a row η. The fit gives its posterior median and standard deviation. A new count on that row is η plus noise, on the log scale:

$$\log y_{\text{new}} \sim N\!\left(\eta,\; \mathrm{sd}(\eta)^2 + \frac{1}{\tau\, s_c}\right)$$

with τ the noise precision and sc the relative size of the camera, both from Part 5. The first part of the variance is what the model does not know about the crowd; the second is the noise of counting. Taking exponentials gives the predictive distribution of the count: its median is the prediction, and its 2.5% and 97.5% points give a 95% interval.

import json

import numpy as np
import pandas as pd
from pyinla import pyinla
from scipy.stats import norm

import crowd

d = pd.read_pickle("work/table.pkl")                  # the rows, from Part 1
x = pd.read_pickle("work/x_part5.pkl")                # the model table
terms = json.load(open("work/terms_part5.json"))      # the whole model
scale = np.load("work/scale.npy")                     # relative size of the camera, row by row
saved = json.load(open("work/part5.json"))            # from the fit of Part 5:
theta, tau = saved["theta"], saved["tau"]             # hyperparameters; tau: noise precision
def predictive(predictor):
    """Predictive distribution of the count on every row: the terms plus noise, log-normal."""
    m = predictor["0.5quant"].to_numpy()
    sd = np.sqrt(predictor["sd"].to_numpy() ** 2 + 1 / (tau * scale))
    return pd.DataFrame({"pred": np.exp(m), "lo": np.exp(m - 1.96 * sd),
                         "hi": np.exp(m + 1.96 * sd), "log_median": m, "log_sd": sd},
                        index=x.index)


p = predictive(pd.read_pickle("work/part5_predictor.pkl"))    # every row, from the fit of Part 5
v = crowd.holes(d).join(p)                                    # the holes we made; the truth is y
print(len(p), "rows with a predictive distribution;", len(v), "of them are holes with known truth")
21022 rows with a predictive distribution; 3605 of them are holes with known truth

A camera hidden all day

On Saturday 12 September we hid camera D for the whole day. The model has never seen a count of this camera on this day.

hhmm = lambda m: f"{int(m) // 60:02d}:{int(m) % 60:02d}"
whole = lambda col: col.round(0).astype(int)
h = v[(v.unit == "cam_D") & (v.kind == "hidden")].iloc[::40]  # every 40th hidden minute of camera D
print(pd.DataFrame({"time": h.minute_of_day.map(hhmm), "median": whole(h.pred),
                    "from": whole(h.lo), "to": whole(h.hi), "count": whole(h.y)})
      .to_string(index=False))
 time  median  from  to  count
11:00       9     5  16     12
11:41       9     6  15     13
12:51      33    21  53     39
14:31      25    15  39     17
16:11      13     8  21     11
17:21      31    19  49     25
19:01      35    22  55     34
20:11      17    11  27     13
Camera D on Saturday 12 September: predictive median and 95% interval, with the hidden counts
Camera D on Saturday 12 September, hidden from the model. Line: predictive median. Band: 95% interval. Dots: the counts that were held back.

Reading the result. The prediction follows the day of this camera, including its surges after each prayer, and most counts fall inside the band. The band is wide: for a camera that is not seen at all, the model admits that it knows the shape of the day better than the exact count.

2. Where does the prediction come from? It can come from two places: the camera's own typical day, learned on other days, and what the other cameras show on this day. To separate them, compare the error of the typical day alone with the error of the full prediction:

on_rows = pd.read_pickle("work/part5_terms.pkl")      # every term on every row, from Part 5
typical = np.exp(on_rows[["intercept", "cam", "day", "cam_weekend",
                          "clock", "cam_curve", "cam_jumuah"]].sum(axis=1))
hid = v[v.kind == "hidden"]
error = lambda guess: (guess[hid.index] - hid.y).abs().groupby([hid.day, hid.unit]).mean().round(2)
print(pd.DataFrame({"typical day alone": error(typical),
                    "with the other cameras that day": error(v.pred)}))
                  typical day alone  with the other cameras that day
day        unit                                                     
2026-09-11 cam_B               5.19                             4.85
           cam_G               2.64                             2.56
2026-09-12 cam_D               5.62                             5.52

The other cameras of that day change little: the mean error of camera D goes from 5.62 to 5.52 people. This is what Part 5 found in the data. The small cameras do not move with the others during a day, so there is little to borrow. A hidden camera is rebuilt from its own level and curve. For a plaza camera it would be different, because the plaza cameras share most of what happens to them.

Forecast: hide what comes after

3. A forecast must not look ahead. The fit of Part 5 saw the whole table, including the counts that follow each blank window. For a hidden camera or a gap that is the task. For a forecast it is not: at the cutoff nothing later is known. So for each cutoff we empty every later row of that day and solve the model again.

4. Keep the hyperparameters. Solving again does not mean fitting again. The standard deviations and correlations of Part 5 describe how crowds behave in general; they do not depend on one cutoff. They are passed back as "mode": {"theta": ..., "fixed": True}, and pyINLA only recomputes the terms. That takes seconds for each cutoff, where the fit took minutes.

def solve(table):
    """The same model with the hyperparameters kept: only the terms are solved again."""
    return pyinla(model={"response": "y", "fixed": ["1"], "random": terms}, family="gaussian",
                  data=table, scale=scale, num_threads=crowd.THREADS,
                  control={"predictor": {"compute": True}, "inla": {"int.strategy": "eb"},
                           "mode": {"theta": theta, "fixed": True}})


future = v.kind.isin(["forecast", "hidden-future"])
for (recording, now), g in v[future].groupby(["recording", "now"]):
    later = ((d.recording == recording) & (d.minute_of_day > now)).to_numpy()
    table = x.copy()
    table.loc[later, "y"] = np.nan                    # hide everything after the cutoff on that day
    v.loc[g.index, p.columns] = predictive(solve(table).summary_linear_predictor).loc[g.index]
print(v[future].groupby(["recording", "now"]).ngroups, "cutoffs solved")
20 cutoffs solved
Camera A on the evening of Saturday 12 September: counts seen by the model, four forecasts with intervals, and what happened
Camera A on the evening of Saturday 12 September. Teal line: counts the model has seen. Amber: four 15-minute forecasts with their 95% intervals. Teal dots: what happened.

Reading the result. Each forecast starts at the last count and then follows the typical day: down around the sunset adhan, up when the night prayer ends. The interval opens quickly. Part 5 said why: what the model knows about today fades with a half-life of 10 to 20 minutes.

A distribution, not a number

Take the forecast made at 20:15, shortly before the crowd returns from the night prayer:

f = v[(v.unit == "cam_A") & (v.day == "2026-09-12") & (v.now == 1215)].copy()   # made at 20:15
f["ahead"] = (f.minute_of_day - f.now).astype(int)
f = f[f.ahead.isin([1, 5, 10, 14])]
print(pd.DataFrame({"minutes ahead": f.ahead, "median": whole(f.pred), "from": whole(f.lo),
                    "to": whole(f.hi), "count": whole(f.y)}).to_string(index=False))
 minutes ahead  median  from  to  count
             1     117    94 145    120
             5     119    82 173    107
            10     136    84 218    149
            14     162    96 272    211

A distribution answers questions that a single number cannot. For example: how likely is it that camera A counts more than 150 people?

def exceed(p, k):
    """Probability that the count is above k, from the predictive distribution of each row."""
    return norm.sf((np.log(k) - p["log_median"]) / p["log_sd"])


print(pd.DataFrame({"minutes ahead": f.ahead, "P(count > 150)": exceed(f, 150).round(2)})
      .to_string(index=False))
 minutes ahead  P(count > 150)
             1            0.01
             5            0.11
            10            0.34
            14            0.61

Reading the result. One minute ahead the count is almost certainly below 150; fourteen minutes ahead it is more likely above than below. The model expects the surge because it has seen one at these minutes on other days. The interval runs from 20% below the median to 24% above it one minute ahead, and from 41% below to 68% above fourteen minutes ahead.

v.to_pickle("work/part6_holes.pkl")                   # the holes, their truth and their predictions
p.to_pickle("work/part6_predictive.pkl")              # for the figures

The code of this part, with the output it printed: 06_filling_holes.ipynb. It reads crowd.py and the files the earlier parts saved in work/.

Next: Part 7: Checking the Predictions →

Part 7 checks the predictions against the counts that were held back, and shows where the model fails.