where \(\hat{m}(\mathbf{s}, t)\) is the trend prediction and \(\hat{e}(\mathbf{s}, t)\) is the kriged residual. Tutorial 15 uses a recurrent GNN (GRU gates built from graph convolutions). This notebook uses spatio-temporal graph Transformers: a spatial attention layer lets every node attend to its \(k\)-NN neighbors at each month, and a temporal attention layer lets every node attend across its own time steps. Residuals are then kriged independently per month — the same RK recipe as TGCN/DCRNN and ConvLSTM.
This is the attention-based counterpart of Tutorial 15 (ST-GNN) and the deep-learning counterpart of Tutorial 13 (Spatio-Temporal Kriging). The validation protocol matches tests/test_kriging_STGTN.py (same seed, same 25 held-out stations, same classical ST-kriging grid).
Step
What we do
Data
Load daily CA PM2.5 for 2025 (163 stations); aggregate to monthly means; project to California Albers (EPSG:3310, meters)
Graph
Build a directed \(k\)-NN graph of stations (k_neighbors=8); inject sinusoidal time encodings
Split
Hold out 25 complete stations entirely (seed=0), matching pygstat.krigeST and the STGTN unit tests
Fit
Fit STTN and GMAN (hidden_dim=32, n_heads=4, 2 layers) on the remaining stations, with per-month residual ordinary kriging
Validation
Predict every held-out station-month; report RMSE, MAE, \(R^2\) vs a naive-mean baseline
Grid
Predict at the 5 km California grid used by classical ST kriging; correlate month-by-month with CA_pm25_grid_predictions.csv
Mapping
Draw monthly PM2.5 surfaces, kriging standard error, and a side-by-side comparison with the classical reference
CPU / GPU
Time STTN.fit+predict on CPU vs GPU using sgsim CA-like PM2.5 (\(n=8{,}400\))
By the end you will have two validated graph-Transformer interpolators, a monthly PM2.5 surface for California in 2025, and a CPU vs GPU timing of STTN training+inference on an SGS-simulated panel.
ST-GTN trend models in this notebook
pygstat wraps two published graph Transformer blocks. Each follows the same RK recipe. Graphs are \(k\)-nearest-neighbor graphs of the coordinates (scipy.spatial.cKDTree); spatial attention uses scatter-softmax (index_add_); temporal attention is stock nn.MultiheadAttention — no torch_geometric dependency.
Class
Architecture
How space and time are combined
STTN
Spatial-Temporal Transformer Network (Xu et al., 2020)
Spatial Transformer block, then temporal Transformer block (sequential)
GMAN
Graph Multi-Attention Network (Zheng et al., 2020)
Spatial and temporal attention in parallel, fused by a learned gate
STGTNRegressionKriging
Shared engine
block_type='sttn' or 'gman'; STTN/GMAN are thin aliases
Attention has no inherent sense of order, unlike the GRU cells in Tutorial 15, so a sinusoidal positional encoding of the month index (Vaswani et al., 2017) is added to every node’s input. Both models are inductive at prediction time: new locations attach only to training nodes.
2. Mathematical Formulation
The target \(Z(\mathbf{s}, t)\) at location \(\mathbf{s}\) and time \(t\) is
where \(\mu(\mathbf{s}, t)\) is a deterministic spatio-temporal trend (the graph Transformer) and \(\varepsilon(\mathbf{s}, t)\) is a zero-mean, spatially autocorrelated residual, kriged independently at each time step.
2.1 Spatial graph and inputs
Given \(n\) stations with coordinates \(\mathbf{s}_i = (x_i, y_i)\), a directed \(k\)-nearest-neighbor graph \(\mathcal{G}=(V,E)\) connects each node to its \(k\) nearest other stations. At prediction time, each new location is attached with \(k\) edges into the training graph only — no new-to-new edges.
Every node’s input at time \(t\) is the two-channel vector \([m_{i,t}\, z_{i,t},\; m_{i,t}]\) (IGNNK-style masking; Wu et al., 2021), linearly embedded to dimension \(d\) and added to a sinusoidal positional encoding \(\mathrm{PE}(t)\in\mathbb{R}^d\):
Spatial attention is a graph Transformer layer (Dwivedi & Bresson, 2020): for each destination node, scaled dot-product attention is restricted to its incoming \(k\)-NN edges and softmax-normalized per head via scatter-softmax,
This is the multi-head, learned Query/Key generalization of the single learned-scalar attention in Tutorial 7.5’s GATConv.
Temporal attention is an unmodified Transformer self-attention over the \(T\) months of a single node (nn.MultiheadAttention with batch_first=True).
2.3 STTN block (Xu et al., 2020)
One STTN layer applies a spatial Transformer block (graph attention independently at each time step) then a temporal Transformer block (self-attention across time, independently per node). Each is a standard pre-residual, post-norm sub-layer with its own feed-forward network:
\[
H \leftarrow \mathrm{LN}\big(H + \mathrm{FF}\big(\mathrm{LN}\big(H + \mathrm{Attn}(H)\big)\big)\big).
\]
2.4 GMAN block (Zheng et al., 2020)
GMAN computes spatial and temporal attention in parallel from the same input, then fuses them with a learned gate
\[
g = \sigma\big(W[h_{\mathrm{spatial}}; h_{\mathrm{temporal}}]\big), \qquad
h = g \odot h_{\mathrm{spatial}} + (1-g)\odot h_{\mathrm{temporal}}.
\]
That gate, rather than sequential alternation, is GMAN’s difference from STTN.
A shared linear head maps the top-layer hidden state at each \((i,t)\) to a scalar trend \(\hat{m}(\mathbf{s}_i, t)\).
2.5 IGNNK-style masking and residual kriging
Training hides a validation subset of stations entirely, plus a random fraction mask_ratio of the remaining observed (station, month) cells, and reconstructs them from the rest of the space-time graph. After fitting, out-of-fold reconstructions yield residuals \(e_i(t)=Z(\mathbf{s}_i,t)-\hat{m}(\mathbf{s}_i,t)\). A spherical variogram is fit independently at each month, and ordinary kriging of those residuals is added back:
STTN(..., device=...) (and the other PyTorch ST models) send the network to:
Value
Behaviour
'auto' (default)
CUDA when this PyTorch build has kernels for the attached GPU. Falls back to CPU otherwise.
'cuda'
Force GPU.
'cpu'
Always CPU.
This notebook probes CUDA once and stores the result in DEVICE. Fits below pass device=DEVICE. §14 times device='cpu' against device='cuda' on an SGS-simulated CA-like PM2.5 panel with \(n > 5{,}000\) space-time observations. Residual ordinary kriging is skipped in that section (krige_residuals=False) so the times isolate the neural net, not the CPU-only kriging solve.
Install extras with pip install pygstat[pytorch].
Code
%matplotlib inlineimport sysimport warningsfrom pathlib import Path# pygstat optionally imports TensorFlow for DeepRegressionKrigingTF.# Loading that stack in the same process as PyTorch can crash; keep TF out.sys.modules.setdefault("tensorflow", None)import geopandas as gpdimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport torchfrom IPython.display import displayfrom sklearn.metrics import mean_absolute_error, mean_squared_error, r2_scorefrom pygstat import GMAN, STGTNRegressionKriging, STTN, load_ca_pm25_panel, sgsimfrom pygstat.kriging_STGTN import ( GatedFusionBlock, GraphMultiHeadAttention, SpatialTemporalBlock, _knn_edges, _sinusoidal_positional_encoding,)warnings.filterwarnings("ignore", category=UserWarning)pd.set_option("display.float_format", lambda v: f"{v:0.3f}")DATA_DIR = Path("..") /"data"MONTH_NAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec",]print("torch version :", torch.__version__)print("CUDA available:", torch.cuda.is_available())DEVICE ="cpu"if torch.cuda.is_available(): major, minor = torch.cuda.get_device_capability(0)print("GPU :", torch.cuda.get_device_name(0), f"(sm_{major}{minor})")# This wheel ships kernels for sm_75+; older cards fall back to CPU.if (major, minor) >= (7, 5): DEVICE ="cuda"else:print("GPU compute capability is below sm_75; using CPU")print("Using device :", DEVICE)
torch version : 2.14.0+cu126
CUDA available: True
GPU : NVIDIA GeForce RTX 2080 Ti (sm_75)
Using device : cuda
4. Load and Explore the California PM2.5 Panel
data/CA_pm25_2025.csv holds daily PM2.5 (µg/m³) at 163 California air-quality stations through 2025. load_ca_pm25_panel aggregates daily readings to monthly station means and projects coordinates from lat/long (EPSG:4326) to California Albers Equal Area (EPSG:3310, meters).
The companion file data/CA_pm25_grid_predictions.csv is the classical space-time Ordinary Kriging surface for the same panel (scripts/predict_ca_pm25_grid.py via pygstat.krigeST) — the reference this tutorial compares against, and the same file used by tests/test_kriging_STGTN.py.
Code
raw = pd.read_csv(DATA_DIR /"CA_pm25_2025.csv")print(f"Daily file : {raw.shape[0]:,} rows, {raw['Site ID'].nunique()} stations")print(f"Date range : {raw['Date'].min()} -> {raw['Date'].max()}")print("Columns :", list(raw.columns))raw.head()
mean_pm = np.nanmean(values, axis=1)fig, axes = plt.subplots(1, 2, figsize=(12, 5.5))sc = axes[0].scatter( latlon["lon"], latlon["lat"], c=mean_pm, cmap="RdYlGn_r", s=28, edgecolor="k", linewidth=0.3,)plt.colorbar(sc, ax=axes[0], label="mean PM2.5 (ug/m3)", shrink=0.75)axes[0].set_xlabel("Longitude")axes[0].set_ylabel("Latitude")axes[0].set_title("Annual-mean PM2.5 at 163 CA stations")axes[0].set_aspect("equal", adjustable="box")axes[1].hist(values[~np.isnan(values)], bins=30, color="steelblue", edgecolor="white")axes[1].set_xlabel("Monthly mean PM2.5 (ug/m3)")axes[1].set_ylabel("Count")axes[1].set_title("Distribution of station-month PM2.5")plt.tight_layout()plt.show()
Code
rng_plot = np.random.default_rng(1)demo_idx = rng_plot.choice(complete, size=6, replace=False)fig, ax = plt.subplots(figsize=(10, 4.2))for i in demo_idx: ax.plot(range(12), values[i], marker="o", linewidth=1.4, label=f"site {int(site_ids[i])}")ax.set_xticks(range(12), MONTH_NAMES)ax.set_xlabel("Month (2025)")ax.set_ylabel("PM2.5 (ug/m3)")ax.set_title("Monthly PM2.5 at six complete stations")ax.legend(loc="upper right", fontsize=8, ncol=2)ax.grid(True, alpha=0.3)plt.tight_layout()plt.show()
Annual-mean PM2.5 is highest in the Central Valley and the South Coast and lowest along the north coast and Sierra. The six example series show a shared seasonal pattern plus station-to-station differences — spatial attention over the \(k\)-NN graph and temporal attention over the 12 months are the two mechanisms that capture them.
5. Spatial \(k\)-NN Graph and Positional Encoding
Before fitting, look at the two ingredients the Transformer actually sees: the station graph, and the sinusoidal encoding that gives attention a sense of month order. _knn_edges builds each station’s 8 nearest other stations (no self-loops). At prediction time the same constructor attaches query points to training nodes only.
GraphMHA out : (8, 8), finite=True
STTN block out : (5, 8, 8), finite=True
GMAN block out : (5, 8, 8), finite=True
STGTN aliases : STTN subclass=True, GMAN subclass=True
6. Hold-Out Station Split
To test genuine spatial-temporal extrapolation (not just interpolating a missing month at a known site), we hold out 25 stations with complete 12-month coverage entirely. Every month at those sites is predicted from the remaining 138 stations. The 7 stations with partial-year coverage stay in the training set: STTN.fit / GMAN.fit already allow NaN. This split (seed=0, n_test=25) is the same protocol as pygstat.krigeST and tests/test_kriging_STGTN.py.
Both families are fit on the training stations only. Hyperparameters match tests/test_kriging_STGTN.py: k_neighbors=8, hidden_dim=32, n_heads=4, n_layers=2, max_epochs=300, patience=30. A random 15% of training stations are held out internally for early stopping (val_fraction=0.15). Residual ordinary kriging uses a spherical variogram, independently per month.
seed= controls the (station, time) masking pattern, not PyTorch’s global weight-init RNG, so exact numbers vary a little run to run — the same caveat as TGCN/DCRNN and ConvLSTM.
Code
COMMON =dict( k_neighbors=8, hidden_dim=32, n_heads=4, n_layers=2, max_epochs=300, patience=30, device=DEVICE, seed=0,)specs = {"sttn": STTN,"gman": GMAN,}fitted = {}for name, cls in specs.items():print()print(f"===== {name.upper()} =====") rk = cls(**COMMON) rk.fit(coords_train, values_train, verbose=True) fitted[name] = rkprint()print(rk)print(f"Epochs run : {len(rk.train_losses_)}")print(f"Best val loss : {min(rk.val_losses_):.6f}")print(f"Months with OK : {sorted(rk.krige_by_step_)}")
===== STTN =====
Epoch 1/300 - Train Loss: 1.101865, Val Loss: 1.186697
Epoch 2/300 - Train Loss: 1.300301, Val Loss: 0.933000
Epoch 3/300 - Train Loss: 1.073553, Val Loss: 0.809167
Epoch 4/300 - Train Loss: 0.676885, Val Loss: 0.783993
Epoch 5/300 - Train Loss: 1.013728, Val Loss: 0.740006
Epoch 6/300 - Train Loss: 0.927526, Val Loss: 0.739523
Epoch 7/300 - Train Loss: 0.689372, Val Loss: 0.752404
Epoch 8/300 - Train Loss: 0.692868, Val Loss: 0.711626
Epoch 9/300 - Train Loss: 0.582490, Val Loss: 0.632327
Epoch 10/300 - Train Loss: 0.642253, Val Loss: 0.603160
Epoch 11/300 - Train Loss: 0.489341, Val Loss: 0.597084
Epoch 12/300 - Train Loss: 0.571402, Val Loss: 0.560291
Epoch 13/300 - Train Loss: 0.607926, Val Loss: 0.554913
Epoch 14/300 - Train Loss: 0.523961, Val Loss: 0.561482
Epoch 15/300 - Train Loss: 0.443650, Val Loss: 0.535481
Epoch 16/300 - Train Loss: 0.568813, Val Loss: 0.535811
Epoch 17/300 - Train Loss: 0.524116, Val Loss: 0.548164
Epoch 18/300 - Train Loss: 0.452447, Val Loss: 0.555616
Epoch 19/300 - Train Loss: 0.415799, Val Loss: 0.542892
Epoch 20/300 - Train Loss: 0.531465, Val Loss: 0.519882
Epoch 21/300 - Train Loss: 0.484272, Val Loss: 0.513734
Epoch 22/300 - Train Loss: 0.472984, Val Loss: 0.516421
Epoch 23/300 - Train Loss: 0.487994, Val Loss: 0.517004
Epoch 24/300 - Train Loss: 0.463928, Val Loss: 0.526767
Epoch 25/300 - Train Loss: 0.427595, Val Loss: 0.538639
Epoch 26/300 - Train Loss: 0.367873, Val Loss: 0.550082
Epoch 27/300 - Train Loss: 0.527223, Val Loss: 0.555738
Epoch 28/300 - Train Loss: 0.374476, Val Loss: 0.562424
Epoch 29/300 - Train Loss: 0.440297, Val Loss: 0.557788
Epoch 30/300 - Train Loss: 0.466041, Val Loss: 0.560177
Epoch 31/300 - Train Loss: 0.390248, Val Loss: 0.562243
Epoch 32/300 - Train Loss: 0.332120, Val Loss: 0.561250
Epoch 33/300 - Train Loss: 0.467119, Val Loss: 0.565609
Epoch 34/300 - Train Loss: 0.326006, Val Loss: 0.574399
Epoch 35/300 - Train Loss: 0.416502, Val Loss: 0.575534
Epoch 36/300 - Train Loss: 0.562165, Val Loss: 0.569229
Epoch 37/300 - Train Loss: 0.403459, Val Loss: 0.570053
Epoch 38/300 - Train Loss: 0.324434, Val Loss: 0.577830
Epoch 39/300 - Train Loss: 0.349149, Val Loss: 0.599470
Epoch 40/300 - Train Loss: 0.390258, Val Loss: 0.608749
Epoch 41/300 - Train Loss: 0.364449, Val Loss: 0.613538
Epoch 42/300 - Train Loss: 0.351656, Val Loss: 0.620166
Epoch 43/300 - Train Loss: 0.337663, Val Loss: 0.623525
Epoch 44/300 - Train Loss: 0.346080, Val Loss: 0.632339
Epoch 45/300 - Train Loss: 0.341850, Val Loss: 0.641283
Epoch 46/300 - Train Loss: 0.313693, Val Loss: 0.652829
Epoch 47/300 - Train Loss: 0.398023, Val Loss: 0.662257
Epoch 48/300 - Train Loss: 0.350359, Val Loss: 0.675805
Epoch 49/300 - Train Loss: 0.489819, Val Loss: 0.680177
Epoch 50/300 - Train Loss: 0.269188, Val Loss: 0.678499
STTN(block_type='sttn', k_neighbors=8, fitted)
Epochs run : 51
Best val loss : 0.513734
Months with OK : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
===== GMAN =====
Epoch 1/300 - Train Loss: 1.205948, Val Loss: 0.971026
Epoch 2/300 - Train Loss: 1.225158, Val Loss: 0.917720
Epoch 3/300 - Train Loss: 1.202172, Val Loss: 0.873237
Epoch 4/300 - Train Loss: 0.720381, Val Loss: 0.839295
Epoch 5/300 - Train Loss: 1.062964, Val Loss: 0.809261
Epoch 6/300 - Train Loss: 0.969402, Val Loss: 0.775475
Epoch 7/300 - Train Loss: 0.759374, Val Loss: 0.748127
Epoch 8/300 - Train Loss: 0.831215, Val Loss: 0.720266
Epoch 9/300 - Train Loss: 0.679360, Val Loss: 0.701376
Epoch 10/300 - Train Loss: 0.795466, Val Loss: 0.689821
Epoch 11/300 - Train Loss: 0.595607, Val Loss: 0.673921
Epoch 12/300 - Train Loss: 0.663740, Val Loss: 0.639427
Epoch 13/300 - Train Loss: 0.717314, Val Loss: 0.605953
Epoch 14/300 - Train Loss: 0.594298, Val Loss: 0.597864
Epoch 15/300 - Train Loss: 0.447061, Val Loss: 0.639164
Epoch 16/300 - Train Loss: 0.606410, Val Loss: 0.642130
Epoch 17/300 - Train Loss: 0.532641, Val Loss: 0.641919
Epoch 18/300 - Train Loss: 0.453095, Val Loss: 0.665965
Epoch 19/300 - Train Loss: 0.389770, Val Loss: 0.682814
Epoch 20/300 - Train Loss: 0.515132, Val Loss: 0.630645
Epoch 21/300 - Train Loss: 0.505305, Val Loss: 0.602091
Epoch 22/300 - Train Loss: 0.506228, Val Loss: 0.565229
Epoch 23/300 - Train Loss: 0.528992, Val Loss: 0.559314
Epoch 24/300 - Train Loss: 0.500342, Val Loss: 0.576531
Epoch 25/300 - Train Loss: 0.441946, Val Loss: 0.566546
Epoch 26/300 - Train Loss: 0.399194, Val Loss: 0.543641
Epoch 27/300 - Train Loss: 0.535426, Val Loss: 0.527717
Epoch 28/300 - Train Loss: 0.385882, Val Loss: 0.527521
Epoch 29/300 - Train Loss: 0.447121, Val Loss: 0.491665
Epoch 30/300 - Train Loss: 0.448577, Val Loss: 0.470911
Epoch 31/300 - Train Loss: 0.424705, Val Loss: 0.470912
Epoch 32/300 - Train Loss: 0.351968, Val Loss: 0.479457
Epoch 33/300 - Train Loss: 0.502358, Val Loss: 0.494210
Epoch 34/300 - Train Loss: 0.326996, Val Loss: 0.507515
Epoch 35/300 - Train Loss: 0.405399, Val Loss: 0.502209
Epoch 36/300 - Train Loss: 0.585193, Val Loss: 0.484517
Epoch 37/300 - Train Loss: 0.394870, Val Loss: 0.480951
Epoch 38/300 - Train Loss: 0.310938, Val Loss: 0.483419
Epoch 39/300 - Train Loss: 0.373807, Val Loss: 0.497310
Epoch 40/300 - Train Loss: 0.415927, Val Loss: 0.507108
Epoch 41/300 - Train Loss: 0.378660, Val Loss: 0.514894
Epoch 42/300 - Train Loss: 0.371866, Val Loss: 0.527126
Epoch 43/300 - Train Loss: 0.334460, Val Loss: 0.528336
Epoch 44/300 - Train Loss: 0.376302, Val Loss: 0.520487
Epoch 45/300 - Train Loss: 0.359615, Val Loss: 0.506539
Epoch 46/300 - Train Loss: 0.342913, Val Loss: 0.505047
Epoch 47/300 - Train Loss: 0.410241, Val Loss: 0.507805
Epoch 48/300 - Train Loss: 0.355960, Val Loss: 0.527680
Epoch 49/300 - Train Loss: 0.533183, Val Loss: 0.546892
Epoch 50/300 - Train Loss: 0.289643, Val Loss: 0.559383
Epoch 51/300 - Train Loss: 0.445876, Val Loss: 0.552775
Epoch 52/300 - Train Loss: 0.271943, Val Loss: 0.573602
Epoch 53/300 - Train Loss: 0.371506, Val Loss: 0.574835
Epoch 54/300 - Train Loss: 0.422737, Val Loss: 0.558215
Epoch 55/300 - Train Loss: 0.277249, Val Loss: 0.552185
Epoch 56/300 - Train Loss: 0.375546, Val Loss: 0.544308
Epoch 57/300 - Train Loss: 0.341586, Val Loss: 0.544814
Epoch 58/300 - Train Loss: 0.311657, Val Loss: 0.548261
Epoch 59/300 - Train Loss: 0.303115, Val Loss: 0.560060
GMAN(block_type='gman', k_neighbors=8, fitted)
Epochs run : 60
Best val loss : 0.470911
Months with OK : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
8. Training Curves
Validation loss is the early-stopping signal: a held-out fraction of training stations is fully excluded from the graph input at every epoch, so the curve measures reconstruction at locations the Transformer never saw as observed values.
Code
n =len(fitted)fig, axes = plt.subplots(1, n, figsize=(5.5* n, 4.2), sharey=True)if n ==1: axes = [axes]for ax, (name, rk) inzip(axes, fitted.items()): ax.plot(rk.train_losses_, label="Training (masked cells)") ax.plot(rk.val_losses_, label="Validation (held-out stations)") ax.set_xlabel("Epoch") ax.set_ylabel("MSE loss (scaled PM2.5)") ax.set_title(name.upper()) ax.legend() ax.grid(True, alpha=0.3)plt.tight_layout()plt.show()
9. Validate on Held-Out Stations
Predict every station-month of the 25 held-out stations from each trained ST-GTN + residual kriging, and compare against a naive baseline: the overall training-mean PM2.5. Classical space-time Ordinary Kriging on this exact split scores RMSE ≈ 2.24 µg/m³ (\(R^2\) ≈ 0.58). Development runs of this test had STTN at RMSE ≈ 2.10 (\(R^2\) ≈ 0.63) and GMAN at ≈ 2.44 (\(R^2\) ≈ 0.51), both competitive with TGCN/DCRNN. Exact numbers move a little because weight initialization is not pinned.
If RMSE is well below the naive-mean baseline, spatial and temporal attention (plus residual kriging) are doing real work: nearby stations and nearby months are informing the prediction. Residual RMSE that varies by month usually tracks the seasonal amplitude of PM2.5 (winter is harder).
10. Residual Variograms
A spherical variogram is fit independently at each month on each model’s out-of-fold residuals. A better neighborhood-aware trend typically leaves less structured residual spatial variation (smaller sill / shorter range). January (peak winter PM2.5) and July are shown for the best family.
For a production map we refit both families on the full 163-station panel (rather than the train/test split), then predict at every cell of data/CA_pm25_grid_predictions.csv — the same 5 km California grid used by classical space-time Ordinary Kriging in Tutorial 13. Query cells attach inductively to the training graph. predict(..., return_std=True) returns the residual-kriging standard error (not a Transformer posterior).
fitted_full = {}pred_full = {}std_full = {}for name, cls in specs.items():print()print(f"===== {name.upper()} (full panel) =====") rk = cls(**COMMON) rk.fit(coords, values, verbose=True) pred, std = rk.predict(grid_xy, return_std=True) fitted_full[name] = rk pred_full[name] = pred std_full[name] = stdprint()print(f"Grid prediction shape : {pred.shape}")print(f"Finite predictions : {np.isfinite(pred).all()}")print(f"PM2.5 pred mean / max : {pred.mean():.2f} / {pred.max():.2f} ug/m3")print(f"SE mean / max : {std.mean():.2f} / {std.max():.2f} ug/m3")
===== STTN (full panel) =====
Epoch 1/300 - Train Loss: 1.227318, Val Loss: 1.421747
Epoch 2/300 - Train Loss: 1.255145, Val Loss: 1.168963
Epoch 3/300 - Train Loss: 1.097342, Val Loss: 0.987940
Epoch 4/300 - Train Loss: 0.807838, Val Loss: 0.983956
Epoch 5/300 - Train Loss: 0.987736, Val Loss: 0.966709
Epoch 6/300 - Train Loss: 1.043803, Val Loss: 0.896878
Epoch 7/300 - Train Loss: 0.670759, Val Loss: 0.866908
Epoch 8/300 - Train Loss: 0.716691, Val Loss: 0.886187
Epoch 9/300 - Train Loss: 0.575513, Val Loss: 0.885776
Epoch 10/300 - Train Loss: 0.803353, Val Loss: 0.841308
Epoch 11/300 - Train Loss: 0.690659, Val Loss: 0.780185
Epoch 12/300 - Train Loss: 0.581581, Val Loss: 0.751528
Epoch 13/300 - Train Loss: 0.610025, Val Loss: 0.761640
Epoch 14/300 - Train Loss: 0.577513, Val Loss: 0.756257
Epoch 15/300 - Train Loss: 0.615385, Val Loss: 0.730150
Epoch 16/300 - Train Loss: 0.435460, Val Loss: 0.752118
Epoch 17/300 - Train Loss: 0.502068, Val Loss: 0.790195
Epoch 18/300 - Train Loss: 0.507764, Val Loss: 0.761242
Epoch 19/300 - Train Loss: 0.496404, Val Loss: 0.750158
Epoch 20/300 - Train Loss: 0.379834, Val Loss: 0.790694
Epoch 21/300 - Train Loss: 0.571857, Val Loss: 0.805761
Epoch 22/300 - Train Loss: 0.495986, Val Loss: 0.767783
Epoch 23/300 - Train Loss: 0.506101, Val Loss: 0.745528
Epoch 24/300 - Train Loss: 0.371692, Val Loss: 0.746811
Epoch 25/300 - Train Loss: 0.440034, Val Loss: 0.741901
Epoch 26/300 - Train Loss: 0.372362, Val Loss: 0.738596
Epoch 27/300 - Train Loss: 0.393383, Val Loss: 0.742289
Epoch 28/300 - Train Loss: 0.414956, Val Loss: 0.753483
Epoch 29/300 - Train Loss: 0.416711, Val Loss: 0.764415
Epoch 30/300 - Train Loss: 0.358784, Val Loss: 0.770750
Epoch 31/300 - Train Loss: 0.411215, Val Loss: 0.767992
Epoch 32/300 - Train Loss: 0.417031, Val Loss: 0.762806
Epoch 33/300 - Train Loss: 0.448803, Val Loss: 0.762040
Epoch 34/300 - Train Loss: 0.357952, Val Loss: 0.767769
Epoch 35/300 - Train Loss: 0.529389, Val Loss: 0.772674
Epoch 36/300 - Train Loss: 0.544498, Val Loss: 0.774943
Epoch 37/300 - Train Loss: 0.391468, Val Loss: 0.772106
Epoch 38/300 - Train Loss: 0.471359, Val Loss: 0.770639
Epoch 39/300 - Train Loss: 0.381136, Val Loss: 0.773592
Epoch 40/300 - Train Loss: 0.400788, Val Loss: 0.779603
Epoch 41/300 - Train Loss: 0.327196, Val Loss: 0.786038
Epoch 42/300 - Train Loss: 0.341461, Val Loss: 0.790699
Epoch 43/300 - Train Loss: 0.382614, Val Loss: 0.792439
Epoch 44/300 - Train Loss: 0.393302, Val Loss: 0.796724
Grid prediction shape : (16397, 12)
Finite predictions : True
PM2.5 pred mean / max : 6.40 / 27.97 ug/m3
SE mean / max : 2.72 / 5.53 ug/m3
===== GMAN (full panel) =====
Epoch 1/300 - Train Loss: 1.325789, Val Loss: 1.228897
Epoch 2/300 - Train Loss: 1.157184, Val Loss: 1.166782
Epoch 3/300 - Train Loss: 1.150858, Val Loss: 1.115772
Epoch 4/300 - Train Loss: 0.883177, Val Loss: 1.089554
Epoch 5/300 - Train Loss: 1.029951, Val Loss: 1.067092
Epoch 6/300 - Train Loss: 1.045644, Val Loss: 1.023698
Epoch 7/300 - Train Loss: 0.763022, Val Loss: 0.980074
Epoch 8/300 - Train Loss: 0.802015, Val Loss: 0.941758
Epoch 9/300 - Train Loss: 0.626572, Val Loss: 0.912092
Epoch 10/300 - Train Loss: 0.905403, Val Loss: 0.884944
Epoch 11/300 - Train Loss: 0.774657, Val Loss: 0.861797
Epoch 12/300 - Train Loss: 0.636167, Val Loss: 0.850757
Epoch 13/300 - Train Loss: 0.679255, Val Loss: 0.852556
Epoch 14/300 - Train Loss: 0.668165, Val Loss: 0.855034
Epoch 15/300 - Train Loss: 0.643659, Val Loss: 0.820522
Epoch 16/300 - Train Loss: 0.480030, Val Loss: 0.792682
Epoch 17/300 - Train Loss: 0.543272, Val Loss: 0.772119
Epoch 18/300 - Train Loss: 0.464443, Val Loss: 0.807686
Epoch 19/300 - Train Loss: 0.485683, Val Loss: 0.875126
Epoch 20/300 - Train Loss: 0.403208, Val Loss: 0.963576
Epoch 21/300 - Train Loss: 0.611517, Val Loss: 0.930232
Epoch 22/300 - Train Loss: 0.494462, Val Loss: 0.832222
Epoch 23/300 - Train Loss: 0.523062, Val Loss: 0.782956
Epoch 24/300 - Train Loss: 0.434671, Val Loss: 0.777759
Epoch 25/300 - Train Loss: 0.463439, Val Loss: 0.826061
Epoch 26/300 - Train Loss: 0.389289, Val Loss: 0.872465
Epoch 27/300 - Train Loss: 0.436992, Val Loss: 0.877510
Epoch 28/300 - Train Loss: 0.471446, Val Loss: 0.831741
Epoch 29/300 - Train Loss: 0.452033, Val Loss: 0.777084
Epoch 30/300 - Train Loss: 0.389797, Val Loss: 0.742083
Epoch 31/300 - Train Loss: 0.392560, Val Loss: 0.723903
Epoch 32/300 - Train Loss: 0.436622, Val Loss: 0.718329
Epoch 33/300 - Train Loss: 0.458714, Val Loss: 0.718107
Epoch 34/300 - Train Loss: 0.355258, Val Loss: 0.720917
Epoch 35/300 - Train Loss: 0.566450, Val Loss: 0.726638
Epoch 36/300 - Train Loss: 0.556254, Val Loss: 0.728710
Epoch 37/300 - Train Loss: 0.433354, Val Loss: 0.725236
Epoch 38/300 - Train Loss: 0.497450, Val Loss: 0.719193
Epoch 39/300 - Train Loss: 0.413124, Val Loss: 0.716175
Epoch 40/300 - Train Loss: 0.434289, Val Loss: 0.716709
Epoch 41/300 - Train Loss: 0.337223, Val Loss: 0.718149
Epoch 42/300 - Train Loss: 0.361438, Val Loss: 0.722631
Epoch 43/300 - Train Loss: 0.384894, Val Loss: 0.730813
Epoch 44/300 - Train Loss: 0.409438, Val Loss: 0.746826
Epoch 45/300 - Train Loss: 0.384348, Val Loss: 0.767672
Epoch 46/300 - Train Loss: 0.344280, Val Loss: 0.774044
Epoch 47/300 - Train Loss: 0.383207, Val Loss: 0.759960
Epoch 48/300 - Train Loss: 0.418149, Val Loss: 0.738441
Epoch 49/300 - Train Loss: 0.341868, Val Loss: 0.728723
Epoch 50/300 - Train Loss: 0.340291, Val Loss: 0.730227
Epoch 51/300 - Train Loss: 0.373035, Val Loss: 0.732660
Epoch 52/300 - Train Loss: 0.371307, Val Loss: 0.743283
Epoch 53/300 - Train Loss: 0.341986, Val Loss: 0.774988
Epoch 54/300 - Train Loss: 0.288495, Val Loss: 0.805163
Epoch 55/300 - Train Loss: 0.407727, Val Loss: 0.797816
Epoch 56/300 - Train Loss: 0.262584, Val Loss: 0.785407
Epoch 57/300 - Train Loss: 0.381638, Val Loss: 0.765377
Epoch 58/300 - Train Loss: 0.256785, Val Loss: 0.759378
Epoch 59/300 - Train Loss: 0.356219, Val Loss: 0.756986
Epoch 60/300 - Train Loss: 0.405660, Val Loss: 0.757181
Epoch 61/300 - Train Loss: 0.329377, Val Loss: 0.758033
Epoch 62/300 - Train Loss: 0.352138, Val Loss: 0.760075
Epoch 63/300 - Train Loss: 0.427706, Val Loss: 0.760337
Epoch 64/300 - Train Loss: 0.262401, Val Loss: 0.764415
Epoch 65/300 - Train Loss: 0.363894, Val Loss: 0.767928
Epoch 66/300 - Train Loss: 0.299965, Val Loss: 0.772516
Epoch 67/300 - Train Loss: 0.270326, Val Loss: 0.776738
Epoch 68/300 - Train Loss: 0.275437, Val Loss: 0.780597
Grid prediction shape : (16397, 12)
Finite predictions : True
PM2.5 pred mean / max : 6.13 / 28.94 ug/m3
SE mean / max : 2.71 / 5.50 ug/m3
12. Compare with Classical ST Kriging
The classical reference in CA_pm25_grid_predictions.csv is space-time Ordinary Kriging (STKriging, Tutorial 13). Per-month Pearson correlation between that surface and each ST-GTN RK surface is the same check as tests/test_kriging_STGTN.py. Graph Transformers typically land around mean \(r pprox 0.83\)–\(0.85\) (range 0.72–0.92 by month) — comparable to TGCN/DCRNN (~0.82–0.88) and tighter than ConvLSTM (~0.73), because the \(k\)-NN graph preserves exact station topology.
Code
corr_rows = []corr_lookup = {}for name, pred in pred_full.items(): corrs = []for month inrange(12): ref = grid.loc[grid["month"] == month, "pm25_pred"].to_numpy() corrs.append(float(np.corrcoef(ref, pred[:, month])[0, 1])) corr_lookup[name] = corrs mean_corr =float(np.mean(corrs)) corr_rows.append({"family": name, **{MONTH_NAMES[m]: corrs[m] for m inrange(12)}, "mean": mean_corr})print(f"{name.upper()} vs classical STKriging: per-month corr = "f"{[f'{c:.2f}'for c in corrs]}, mean={mean_corr:.3f}" )corr_tbl = pd.DataFrame(corr_rows).set_index("family")display(corr_tbl.round(3))fig, ax = plt.subplots(figsize=(9, 4.2))x = np.arange(12)width =0.35for i, (name, corrs) inenumerate(corr_lookup.items()): ax.bar(x + (i -0.5) * width, corrs, width, label=name.upper(), alpha=0.85) ax.axhline(np.mean(corrs), linestyle="--", color=f"C{i}", linewidth=1)ax.set_xticks(x, MONTH_NAMES)ax.set_ylabel("Pearson r")ax.set_ylim(0, 1)ax.set_title("ST-GTN RK vs classical ST kriging (grid)")ax.legend()plt.tight_layout()plt.show()
Monthly surfaces for the best held-out family, plus January/July side-by-side with classical ST kriging and the other family. The 5 km grid is clipped to California’s boundary (data/US_STATE.shp, reprojected to EPSG:3310). Ordinary kriging of residuals has no positivity constraint, so a handful of cells far from stations can go slightly negative; they are clipped to 0 for display, matching Tutorial 13.
fig, axes = plt.subplots(2, 3, figsize=(16, 12), sharex=True, sharey=True)families = ["pm25_stk"] + [f"pm25_{n}"for n in pred_full]titles = ["ST kriging"] + [n.upper() for n in pred_full]for row, (m, month_name) inenumerate([(0, "January"), (6, "July")]): sub = grid_pred[grid_pred["month"] == m]for col, (colname, title) inenumerate(zip(families, titles)): ax = axes[row, col] sc = ax.scatter( sub["x"], sub["y"], c=sub[colname], cmap="RdYlGn_r", vmin=vmin, vmax=vmax, s=4, marker="s", ) ca.boundary.plot(ax=ax, color="black", linewidth=0.6) ax.set_title(f"{title} -- {month_name}") ax.set_xticks([]) ax.set_yticks([]) ax.set_aspect("equal")fig.colorbar(sc, ax=axes, shrink=0.5, label="PM2.5 (ug/m3)")fig.suptitle("Classical ST kriging vs STTN / GMAN RK", fontsize=14, y=0.93)plt.show()
The monthly maps recover the well-known California pattern: winter peaks in the Central Valley, cleaner conditions along the coast, and a summer contrast driven by wildfire and photochemistry. The standard-error maps are high where stations are sparse (eastern deserts, far north) and low in the South Coast and Central Valley networks — a map of how well the residual kriging is constrained, not of Transformer epistemic uncertainty. Side-by-side with classical ST kriging, both Transformers track the same regional structure; STTN’s sequential spatial-then-temporal attention often stays a little closer to the geostatistical surface than GMAN’s gated parallel fusion.
14. CPU vs GPU STTN Timing
The ~1,600-row CA station panel is too small for a GPU comparison: the STTN graph is only ~140 training nodes, and host→device copies dominate. Here we simulate a CA-like monthly PM2.5 panel with Sequential Gaussian Simulation (pygstat.sgsim) so that \(n_{\mathrm{train}} > 5{,}000\) space-time observations, then time STTN.fit + predict on CPU (device='cpu') versus GPU (device='cuda'). GMAN uses the same engine; we time STTN, the primary model in this notebook.
Simulation recipe (conditioned on the real 163 stations):
Draw \(n_{\mathrm{sites}} = 700\) random locations in the California bounding box.
Simulate \(\log(\mathrm{PM2.5})\) with sgsim (exponential variogram, practical range 250 km, conditioned on station-mean PM2.5 from data/CA_pm25_2025.csv) and back-transform with \(\exp(\cdot)\).
Expand each site across 12 months using the observed statewide monthly relative seasonality, giving \(n_{\mathrm{train}} = 8{,}400\) (700 stations × 12 months).
Draw a separate prediction set of \((x, y)\) locations (no values needed — the trend only needs coordinates plus the training panel).
The GPU work is PyTorch training and the STTN forward pass, not residual ordinary kriging. Residual OK is a dense CPU solve and would dominate at this \(n\), so the timing section uses krige_residuals=False. At prediction time the query nodes attach to the training graph, so GPU work grows gently with \(n_{\mathrm{pred}}\). Epochs are capped at 5 so the comparison isolates device cost; the CA maps in §7 used max_epochs=300.
Each timing is the median of three fit + predict calls after a short GPU warmup so CUDA kernel compilation is not counted. match is same-weights inference: a GPU-trained network is copied to CPU and both devices must agree (np.allclose). Training itself is not bit-identical across devices. If CUDA cannot run here, the GPU column is skipped.
Simulating 700 CA-like PM2.5 sites with sgsim, then 12 months
conditioning : 163 station means from data/CA_pm25_2025.csv
vario : azimuth=0, nugget=0.009, range=250 km, exponential, log(PM2.5)
sgsim wall : 5.1 s (not included in STTN times)
simulated PM2.5 : [1.07, 25.30] µg/m³ (CA observed [-0.50, 39.05])
GPU usable : True
Repeats : 3 (median wall time of STTN fit + predict)
n_train : 8400 (sgsim CA-like PM2.5 panel, 700 sites × 12 months)
n_pred : [500, 1000, 2000, 4000, 8000] (random locations in the CA bbox)
settings : architecture: k_neighbors=8, hidden_dim=32, n_heads=4, 2 layers; max_epochs=5, krige_residuals=False
dataset n_train n_pred CPU (ms) GPU (ms) speedup match
CA PM2.5 (sgsim) 8400 500 1933.1 961.1 2.01× True
CA PM2.5 (sgsim) 8400 1000 1863.9 954.0 1.95× True
CA PM2.5 (sgsim) 8400 2000 1914.9 1027.4 1.86× True
CA PM2.5 (sgsim) 8400 4000 1809.7 1036.5 1.75× True
CA PM2.5 (sgsim) 8400 8000 1983.8 1054.6 1.88× True
match = True means the GPU-trained STTN, evaluated on CPU and on GPU with the same weights, agrees to rtol=1e-3. The GPU speedup comes from STTN training and the attention forward pass (including inductive \(k\)-NN attachment of query nodes), not from SGS and not from residual ordinary kriging (turned off here). Fit still dominates at 5 epochs, so the curve is relatively flat in \(n_{\mathrm{pred}}\); the GPU stays about 1.8–2.0× faster. Use device=DEVICE so the same cells run on a laptop CPU or a CUDA workstation without edits. For the published CA maps, leave krige_residuals=True (the default).
15. Summary and Conclusions
This notebook applied spatio-temporal graph Transformer regression kriging to California monthly PM2.5, the attention-based counterpart of the recurrent ST-GNNs in Tutorial 15 and of classical STKriging (Tutorial 13).
Data. Daily readings at 163 stations (CA_pm25_2025.csv) aggregated to a monthly panel in EPSG:3310. The prediction grid is the classical ST-kriging surface in CA_pm25_grid_predictions.csv.
Trend. A directed \(k\)-NN graph (k_neighbors=8) plus either sequential spatial-then-temporal Transformer blocks (STTN) or parallel spatial + temporal attention fused by a learned gate (GMAN). A sinusoidal positional encoding injects month order. New locations attach inductively to training nodes only.
Training. IGNNK-style random masking of (station, month) cells, plus a validation subset of stations always fully excluded.
Residuals. Out-of-fold Transformer reconstructions are kriged spatially, independently per month, and added back.
Validation. The same 25 complete held-out stations as Tutorial 13 / tests/test_kriging_STGTN.py. Both families should beat a naive-mean baseline; STTN has come out near classical ST kriging (RMSE ≈ 2.10 vs 2.24 µg/m³) in development runs.
Grid. Per-month correlation with the classical ST-kriging reference is typically \(r \approx 0.72\)–\(0.92\) (mean ~0.83–0.85).
CPU vs GPU
Timed STTN.fit + predict on CPU vs GPU using an SGS-simulated CA-like panel (\(n_{\mathrm{train}}=8{,}400\)), with residual kriging off so the times isolate the neural net.
CPU / GPU.STTN(..., device=DEVICE) trains a graph Transformer on PyTorch. GPU work is the network (and inductive \(k\)-NN attachment at predict time), not residual OK. The 163-station CA panel is too small to show that; §14 uses SGS so \(n > 5{,}000\), krige_residuals=False, and a short epoch budget.
When to use ST-GTN RK
You have a monitoring network through time and want a learned spatio-temporal trend plus kriged residuals.
You want attention over neighbors and months (which months matter for this station? which neighbors?) rather than a GRU that compresses history into a single hidden state.
You do not have dense covariates at every prediction cell (this module’s trend is the masked panel itself, not external regressors — unlike tutorials 7.1–7.5).
When not to use it
A purely spatial snapshot with no time dimension — use ordinary, universal, or regression kriging (tutorials 4–7), or the spatial GNNs in Tutorial 7.5.
Count / rate data over polygons — use Poisson kriging.
You prefer a recurrent inductive bias — Tutorial 15 (TGCN / DCRNN).
You prefer a CNN on a regular grid — Tutorial 14 (ConvLSTM).
Objects used here
Object
Role
pygstat.STTN
Sequential spatial-then-temporal Transformer + per-month residual OK
Training curves, per-month OK models, and the fitted \(k\)-NN graph
Install extras with pip install pygstat[pytorch]. Set device='cuda' to force a GPU, or leave device='auto' (used here via DEVICE) to fall back to CPU when CUDA is unavailable. Related tutorials: 13 Spatio-Temporal Kriging, 15 ST-GNN RK, 14 ConvLSTM RK, 6.5 GNN RK.
16. Resources
Papers and books
Reference
Notes
Xu, M., Dai, W., Liu, C., Gao, X., Lin, W., Qi, G.-J. & Xiong, H. (2020). Spatial-Temporal Transformer Networks for Traffic Flow Forecasting. arXiv:2001.02908
STTN block used here
Zheng, C., Fan, X., Wang, C. & Qi, J. (2020). GMAN: A Graph Multi-Attention Network for Traffic Prediction. AAAI. arXiv:1911.08415
GMAN gated fusion used here
Vaswani, A. et al. (2017). Attention is all you need. NeurIPS.
Multi-head attention and sinusoidal PE
Dwivedi, V.P. & Bresson, X. (2020). A generalization of Transformer networks to graphs. arXiv:2012.09699
Graph-masked attention
Wu, Y., Cui, X., Nie, X. & Wang, H. (2021). Inductive Graph Neural Networks for Spatiotemporal Kriging. AAAI.
Masked-reconstruction training (IGNNK)
Cressie, N. (1993). Statistics for Spatial Data (rev. ed.). Wiley.
Residual kriging
Hengl, T., Heuvelink, G.B.M. & Rossiter, D.G. (2007). About regression-kriging: from equations to case studies. Computers & Geosciences, 33(10).
RK recipe
Pebesma, E. (2012). spacetime: Spatio-Temporal Data in R. Journal of Statistical Software, 51(7).