Skip to content

Spatial CV API

SpatialBlockSplitter

h2ml.features.spatial_cv.SpatialBlockSplitter

K-fold splitter that groups spatially adjacent samples into blocks and holds out entire blocks as test sets.

Blocks are formed by quantile-binning coordinates on each axis (robust to uneven spatial distributions) and assigned to folds round-robin. Each fold's test set is one or more contiguous blocks.

Parameters:

Name Type Description Default
coords ndarray

(n_samples, 2) array of spatial coordinates (lat/lon, x/y, or any 2-D position).

required
n_splits int

Number of CV folds.

5
n_blocks_per_fold int

Number of blocks per test fold. Total blocks = n_splits × n_blocks_per_fold. More blocks give finer spatial granularity at the cost of smaller individual test sets.

5
random_state int

Seed for the block→fold shuffle (reproducible folds).

42
metric SpatialMetric

"euclidean" (projected coords) or "haversine" (lat/lon in decimal degrees).

'euclidean'

Examples:

>>> coords = np.column_stack([lats, lons])
>>> splitter = SpatialBlockSplitter(coords, n_splits=5, n_blocks_per_fold=5)
>>> for train_idx, test_idx in splitter.split(X):
...     model.fit(X[train_idx], y[train_idx])
...     score = model.score(X[test_idx], y[test_idx])

clone_with_n_splits(n_splits, random_state=None)

Return a new splitter with n_splits folds, reusing the same coords and metric.

get_n_splits(X=None, y=None, groups=None)

Number of folds (sklearn splitter interface; X/y/groups ignored).

plot(lon_col=1, lat_col=0, save_path=None)

Two-panel scatter of block and fold assignments.

Thin wrapper over h2ml.plots.plot_spatial_blocks(self); see that function for details.

split(X, y=None, groups=None)

Yield (train_idx, test_idx) for each of n_splits folds.

Parameters:

Name Type Description Default
X ndarray

Array-like whose row count must match the calibration coords.

required
y Optional[ndarray]

Ignored (sklearn signature compatibility).

None
groups Optional[ndarray]

Ignored (sklearn signature compatibility).

None

Yields:

Type Description
tuple[ndarray, ndarray]

(train_idx, test_idx) integer index arrays per fold.

Raises:

Type Description
ValueError

If len(X) does not match the number of stored coords.

SPCVSplitter

h2ml.features.spatial_cv.SPCVSplitter

Two-stage spatial cross-validation splitter (SP-CV). Reference: Wang et al. 2023. Spatial+: A new cross-validation method to evaluate geospatial machine learning models.

Stage 1 — AHC blocks: Agglomerative Hierarchical Clustering (AHC) on spatial coordinates forms blocks that respect the autocorrelation structure of the data. The AHC distance threshold controls block granularity; if not provided it defaults to the 10th percentile of pairwise distances.

Stage 2 — Cluster Ensemble fold assignment: Each block is represented by its mean coordinates, covariates, and target value. Three independent KMeans runs (on location, covariates, and target) are combined via Hybrid Bipartite Graph Formulation (HBGF): a co-occurrence affinity matrix is built from the stacked membership matrices and SpectralClustering produces the final k folds.

Blocks that co-cluster across the three views get high affinity and end up in the same fold, so each test fold is a distinct region of geographic, covariate, and target space. The resulting folds are deliberately not representative of the full data: CV scores estimate extrapolation to unseen conditions and are typically more pessimistic than block or random CV.

Parameters:

Name Type Description Default
coords ndarray

(n_samples, 2) spatial coordinates (lat/lon or projected).

required
X ndarray

(n_samples, n_features) covariate matrix.

required
y ndarray

(n_samples,) target array.

required
n_splits int

Number of CV folds (k).

5
threshold Optional[float]

AHC distance threshold. Defaults to the 10th percentile of pairwise coordinate distances when None.

None
linkage LinkageCriterion

Linkage criterion for AHC ('ward', 'average', 'complete'). 'ward' minimises within-cluster variance and works well for compact geographic blocks.

'ward'
random_state int

Seed for KMeans and SpectralClustering reproducibility.

42
metric SpatialMetric

"euclidean" (projected coords) or "haversine" (lat/lon in decimal degrees). See the Note on linkage interaction.

'euclidean'
pca_components float

Variance fraction retained by PCA applied to block covariates in stage 2 (after AHC, before the cluster ensemble). Default 0.95.

0.95
exact_max_samples int

Sample count below which exact scipy AHC is used; above it an approximate sklearn AHC (k-NN graph) is used. Default 5000.

5000
knn_neighbors int

k for the k-NN connectivity graph in approximate AHC. Default 15.

15
use_target bool

Include the target view in stage 2. False assigns folds from location and covariates alone, so they do not depend on y. Default True.

True
Note

'ward' linkage operates on Euclidean distances. When metric='haversine', ward is silently downgraded to 'average' (in both the exact and approximate AHC paths) because ward is undefined for non-Euclidean distances. For projected coords (km, m) use metric='euclidean' and ward linkage is valid.

Examples:

>>> splitter = SPCVSplitter(coords, X, y, n_splits=5)
>>> for train_idx, test_idx in splitter.split(X):
...     model.fit(X[train_idx], y[train_idx])
...     score = model.score(X[test_idx], y[test_idx])

clone_with_n_splits(n_splits, random_state=None)

Return a new splitter with n_splits folds, reusing the AHC block structure.

Stage 1 (AHC clustering) is skipped — block_id_ is copied directly. Stage 2 (fold assignment) is rerun with the new n_splits and random_state, so each HPO repeat gets different fold boundaries without repeating AHC.

get_n_splits(X=None, y=None, groups=None)

Number of folds (sklearn splitter interface; X/y/groups ignored).

plot(lon_col=1, lat_col=0, save_path=None)

Two-panel scatter of block and fold assignments.

Thin wrapper over h2ml.plots.plot_spatial_blocks(self); see that function for details.

split(X, y=None, groups=None)

Yield (train_idx, test_idx) for each of n_splits folds.

Parameters:

Name Type Description Default
X ndarray

Array-like whose row count must match the calibration coords.

required
y Optional[ndarray]

Ignored (sklearn signature compatibility).

None
groups Optional[ndarray]

Ignored (sklearn signature compatibility).

None

Yields:

Type Description
tuple[ndarray, ndarray]

(train_idx, test_idx) integer index arrays per fold.

Raises:

Type Description
ValueError

If len(X) does not match the number of stored coords.

Variogram

h2ml.utils.variogram.autocorrelation_range(coords, values, n_lags=15, max_dist=None, max_points=3000, random_state=42, metric='euclidean')

Estimate the spatial autocorrelation range from an empirical variogram.

Parameters:

Name Type Description Default
coords ndarray

(n_samples, 2) coordinate array. With metric="euclidean" the range comes out in these units; with "haversine" they are (lat, lon) degrees and the range is in km.

required
values ndarray

(n_samples,) variable to analyse. Use model residuals (y_pred − y_true) to measure unexplained spatial structure.

required
n_lags int

Number of distance bins for the empirical variogram (default 15).

15
max_dist Optional[float]

Maximum lag distance to consider. Defaults to half the maximum pairwise distance (standard geostatistics convention — the variogram is unreliable beyond this point).

None
max_points int

Cap on the number of points used. The pairwise distance matrix is O(n²) in memory, so for larger inputs a random subsample of this size is drawn (the range estimate is stable under subsampling). Default 3 000 (~72 MB matrix).

3000
random_state int

Seed for the subsample draw and the permutation check.

42
metric Literal['euclidean', 'haversine']

"euclidean" or "haversine", as in spatial_cv_metric.

'euclidean'

Returns:

Type Description
VariogramResult

VariogramResult with fitted parameters and practical_range, which is capped at

VariogramResult

max_dist. Check status before using the range.

Raises:

Type Description
ValueError

If metric is unknown.

RuntimeError

If curve fitting fails to converge.

h2ml.utils.variogram.VariogramResult dataclass

Fitted variogram parameters and derived autocorrelation range.

Attributes:

Name Type Description
nugget float

Semivariance at lag h=0 — measurement noise / micro-scale variation not resolved by the sampling.

sill float

Semivariance added by spatial structure; the total sill (the plateau the variogram reaches) is nugget + sill.

scale float

Exponential e-folding distance (model parameter a) — the lag at which ~63% of the structured variance is reached.

practical_range float

3 × scale — the lag where correlation has decayed to ≈ 5%; the effective autocorrelation range.

lag_distances ndarray

Bin centres (lag distances) used for fitting.

semivariances ndarray

Robust (Cressie–Hawkins) semivariance γ per bin.

n_pairs ndarray

Number of point pairs contributing to each bin.

status str

How far to trust practical_range. "ok" — the variogram levels off within the lags. "at_bound" — it doesn't, so the true range is at least practical_range. "no_structure" — no resolved spatial structure was found, so ignore the range; on small or very zero-heavy samples, weak structure can land here too. "unknown" — fitted before status existed.

h2ml.utils.variogram.plot_variogram(coords, values, n_lags=15, max_dist=None, units=None, save_path=None, metric='euclidean')

Plot the empirical variogram, fitted exponential model, and practical range.

Parameters:

Name Type Description Default
coords ndarray

(n_samples, 2) coordinate array.

required
values ndarray

(n_samples,) variable (use model residuals).

required
n_lags int

Distance bins (default 15).

15
max_dist Optional[float]

Max lag. Defaults to half the max pairwise distance.

None
units Optional[str]

Distance unit label for the x-axis. Defaults to "km" for haversine, otherwise "°".

None
save_path Optional[str | Path]

Path to save the figure. If None, shows interactively.

None
metric Literal['euclidean', 'haversine']

"euclidean" or "haversine", as in spatial_cv_metric.

'euclidean'

Returns:

Type Description
VariogramResult

VariogramResult (same as autocorrelation_range).