How Big, How Busy
The first two terms of the model: a level for each camera and a level for each day.
Where we start
The model reads a table with one row per camera and minute. Its first column is the response: the log count where the model may see it, and empty (NaN) where it may not.
import json
import numpy as np
import pandas as pd
from pyinla import pyinla
import crowd
d = pd.read_pickle("work/table.pkl") # from Part 1
x = pd.DataFrame(index=d.index) # the table the model reads
x["y"] = np.where(d.obs, np.log(d.people), np.nan) # log count; NaN where it may not be seen
print(f"log count: mean {x.y.mean():.2f}, sd {x.y.std():.2f}")log count: mean 3.79, sd 1.31The standard deviation of the log count, 1.31, is the variation the model has to explain. Each part of this tutorial adds one term, and we watch how much of this number is left.
A level for each camera
1. What we want. The largest differences in the table are between cameras. So the first model gives every camera its own level:
μ is the level of an average camera, ac says how far camera c is above or below it, and ε is everything else.
2. Thirteen numbers, one distribution. We could estimate the thirteen ac separately, as thirteen averages. The model does something slightly different: it treats them as draws from one distribution,
and estimates σa, how much cameras differ, from the data. A camera with thousands of rows gets, in effect, its own average. A camera with few rows is pulled towards the others. This is the iid model, the simplest random effect, and every later term is a variation on it.
3. In pyINLA. A term needs an index column, here the camera number, and one line that names its model. Every term also needs a prior for its standard deviation. All terms of this tutorial use the same kind, written once in crowd.py:
def pc(u):
"""Prior for the standard deviation of a term: P(sd > u) = 0.01. A penalised-complexity prior."""
return {"prec": {"prior": "pc.prec", "param": [u, 0.01]}}pc(5) says that a σa above 5 is unlikely, with probability 0.01. That is a weak statement, and the data do the rest.
from crowd import pc # the prior for a term's sd, shown above
x["cam"] = crowd.codes(d.unit) # camera A is 1, ..., camera M is 13
cam = {"id": "cam", "model": "iid", "hyper": pc(5)}
res = pyinla(model={"response": "y", "fixed": ["1"], "random": [cam]},
family="gaussian", data=x, control={"predictor": {"compute": True}})
mu = res.summary_fixed["mean"].iloc[0]
a = res.summary_random["cam"]
print(f"mu = {mu:.2f}, so an average camera counts exp(mu) = {np.exp(mu):.0f} people\n")
print(pd.DataFrame({"camera": sorted(d.unit.unique()), "a": a["mean"].round(2),
"typical count": np.exp(mu + a["mean"]).round(0).astype(int)})
.to_string(index=False))mu = 3.75, so an average camera counts exp(mu) = 43 people
camera a typical count
cam_A 1.50 190
cam_B -0.85 18
cam_C -0.60 23
cam_D -0.47 27
cam_E 1.70 232
cam_F 1.02 118
cam_G -1.81 7
cam_H -1.12 14
cam_I 0.08 46
cam_J 0.40 64
cam_K 0.62 79
cam_L 0.59 77
cam_M -1.06 15Reading the result.
- μ = 3.75: an average camera counts e3.75 = 43 people.
- Camera A has a = 1.50: it counts e1.50 = 4.5 times as many, about 190.
- Camera G has a = -1.81: it counts e-1.81 = 0.16 times as many, about 7.
left_camera = (x.y - res.summary_linear_predictor["mean"].to_numpy()).std()
print(f"sd of what is left: {left_camera:.2f}")sd of what is left: 0.61Camera size alone takes the standard deviation from 1.31 to 0.61.
A level for each day
1. What we want. Some days are busier than others, for every camera at once. That is a second level, one per day:
2. In pyINLA. One more index column and one more line. The model is now a list of two terms.
x["day"] = crowd.codes(d.day) # 4 September is 1, ..., 19 September is 6
day = {"id": "day", "model": "iid", "hyper": pc(0.5)}
res = pyinla(model={"response": "y", "fixed": ["1"], "random": [cam, day]},
family="gaussian", data=x, control={"predictor": {"compute": True}})
b = res.summary_random["day"]
days = pd.to_datetime(sorted(d.day.unique()))
print(pd.DataFrame({"day": days.strftime("%a %d %b"),
"times the average day": np.exp(b["mean"]).round(2),
"from": np.exp(b["0.025quant"]).round(2),
"to": np.exp(b["0.975quant"]).round(2)}).to_string(index=False)) day times the average day from to
Fri 04 Sep 1.13 0.97 1.32
Sat 05 Sep 0.84 0.72 0.98
Fri 11 Sep 1.10 0.95 1.29
Sat 12 Sep 0.84 0.72 0.98
Fri 18 Sep 1.26 1.08 1.47
Sat 19 Sep 0.90 0.77 1.05
Reading the result. Every Friday is above the average day and every Saturday below it. The intervals are wide, because there are only six days.
A caution. These day levels cannot be trusted yet. The fragments of 4 and 5 September cover only a few hours, and the model has no notion of the time of day. A day filmed only during a busy hour looks like a busy day. Part 5 gives the day levels of the full model.
fitted = res.summary_linear_predictor["mean"].to_numpy()
left_day = (x.y - fitted).std()
print(f"sd of what is left: {left_day:.2f}")sd of what is left: 0.59The day level adds little: 0.61 becomes 0.59. Most of what is left lies inside the day.
What it cannot do

A level is one number for the whole day. Within this day the counts of camera A range from 56 to 469, a factor of 8, and they move in step with the prayers. The next term has to be a curve over the day.
x.to_pickle("work/x_part2.pkl") # the model table so far
json.dump([cam, day], open("work/terms_part2.json", "w")) # the model so far
# for the figures and the last part
pd.DataFrame({"fitted": fitted}, index=x.index).to_pickle("work/part2.pkl")
a.to_pickle("work/part2_cam.pkl"); b.to_pickle("work/part2_day.pkl")
json.dump({"mu": mu, "sd": float(x.y.std()),
"left": {"a level per camera": float(left_camera),
"and a level per day": float(left_day)}}, open("work/part2.json", "w"))The code of this part, with the output it printed: 02_levels.ipynb. It reads crowd.py and the files the earlier parts saved in work/.