Spatial kernel density: bandwidth and interpretation
Learning purpose: Explore how bandwidth controls the spatial scale of a density estimate. The example uses synthetic metric coordinates to isolate the modelling choices; it does not represent real Johor POIs.
Format: guided learner notebook. Part 1 supplies the conceptual background; try the exercises before consulting the linked solution.
Data: entirely synthetic, generated with a fixed seed. Software: NumPy, Matplotlib and relevant SciPy/scikit-learn functions. No private course datasets or Google Drive required.
After you attempt the exercises: Open the complete solution notebook on GitHub.
1. Generate and inspect the observations¶
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KernelDensity
rng = np.random.default_rng(47)
points = np.vstack([rng.normal((250, 300), 65, (100, 2)),
rng.normal((730, 690), 100, (160, 2))])
points = np.clip(points, 0, 1000)
coords = np.linspace(0, 1000, 55)
xx, yy = np.meshgrid(coords, coords)
grid = np.column_stack((xx.ravel(), yy.ravel()))
print("Observations:", len(points))2. Analyse and evaluate¶
KDE smooths observed events into an estimated intensity surface. The evaluation grid is not the set of observations.
TODO 1 — bandwidth. Fit a Gaussian KDE with bandwidth=60, evaluate it at grid, and display the resulting surface.
# TODO: KernelDensity(bandwidth=60).fit(points).score_samples(grid)
TODO 2 — sensitivity. Repeat with bandwidth 160. Compare the number and apparent breadth of concentrated regions. Why is the smoothest surface not automatically the best?
# TODO: evaluate the KDE at bandwidth=160 and compare with bandwidth=60.
3. Interpretation¶
These surfaces are probability density estimates (integrating to approximately 1 over the full plane), not event counts per square kilometre. Their scales and interpretation must be stated explicitly; bandwidth can merge locally distinct concentrations.
Write your own interpretation: How might parameter selection or observation design change the result?
Check your understanding¶
Try the exercises and write down your interpretation before comparing your work with the complete answers.