spatialmllab
Spatial machine learning for predictive mapping, from sample points to a map with intervals and an area of applicability.
spatialmllab is the analytical core of the QGIS plugin
02SpatialML, usable without QGIS. It takes NumPy arrays
(samples, covariates, coordinates in a projected CRS in metres) and runs one study: a spatial
cross-validation design whose nearest-neighbour distances are checked against the prediction
task, five models on the same folds with nested tuning, explanations on held-out data, and the
dissimilarity index and area of applicability (Meyer & Pebesma 2021) for the prediction. Every
engine is written in NumPy; SciPy and scikit-learn are used when installed. The test suite
reproduces the plugin's reference values (fold vectors, GWR coefficients, cross-validation
metrics, variogram, Wasserstein distances) on its demo landscape.
Installation
pip install spatialmllab # numpy only
pip install "spatialmllab[fast]" # + scipy (k-d tree, Ward linkage)
pip install "spatialmllab[sklearn]" # + scikit-learn tree engine
pip install "spatialmllab[geo]" # + shapely / geopandas adapters
Until the first PyPI release, install from GitLab:
pip install "spatialmllab @ git+https://gitlab.com/geophilo1/spatialmllab_sdk.git"
Requires Python 3.9 or newer. Coordinates must be in a projected CRS in metres.
Quickstart
import numpy as np
import spatialmllab as sml
# samples: covariates X (n, p), target y (n,), coordinates xy (n, 2)
demo = sml.demo_landscape() # synthetic landscape with a planted truth
table = demo.table # or sml.from_arrays(X, y, xy, names=..., categorical=...)
pred_xy = demo.prediction_xy() # where the map will be made
res = sml.run_study(
table,
cv="knndm", # random, blocks, hex, cluster, bloo, knndm
pred_xy=pred_xy,
models=("ols", "rf", "gbm", "gwr"),
model_params={"rf": {"n_trees": 200}},
)
for s in res.leaderboard:
print(s.model, s.scheme, round(s.rmse, 3), s.coverage, s.moran_i_residual)
res.best # model with the lowest spatial-CV RMSE
res.optimism_gap() # spatial RMSE - random RMSE per model
res.nnd["W"] # Wasserstein distance of each design to the task
res.importance[res.best].mean # permutation importance on held-out folds
# wall-to-wall map on a covariate grid (rows, cols, p), north-up
maps = res.predict_grid(demo.stack(), demo.x_min, demo.y_max, demo.cell)
maps["mean"], maps["lower"], maps["upper"], maps["di"], maps["aoa"], maps["mean_aoa"]
Single steps are plain functions: make_folds, g_functions, fit_variogram, make,
cross_validate, permutation_importance, tree_shap, pdp_ice, ale, train_di,
predict_rows, predict_grid. See examples/quickstart.py for a run on the demo landscape.
Features
| Area | Functions | Notes |
|---|---|---|
| Sample table | from_arrays -> SampleTable, detect_task |
drops missing rows; categorical levels as codes; regression or classification |
| Variogram | fit_variogram -> VariogramFit |
Matheron estimator; spherical / exponential fit by Cressie WLS; practical range |
| Validation designs | make_folds -> FoldSet, inner_design, fold_polygons |
random, square and hexagonal blocks, k-means clusters, buffered LOO, kNNDM |
| Distance diagnostics | g_functions, sample_nnd, prediction_nnd, cv_nnd, wasserstein, ecdf |
G_j, G_ij, G*_j and W per design |
| Models | make -> Model, OLS, GWR, MGWR, MODELS |
OLS, random forest (QRF intervals), gradient boosting (split-conformal), GWR, MGWR |
| Validation | cross_validate -> CVResult, tune, metrics, moran_i |
nested tuning; RMSE, MAE, R2, bias, CCC, coverage; accuracy, balanced accuracy, kappa, F1, log loss, Brier |
| Explanations | permutation_importance, tree_shap, tree_shap_base, linear_shap, pdp_ice, ale |
exact path-dependent TreeSHAP; PDP with ICE; ALE |
| Area of applicability | train_di -> AOAModel |
weighted dissimilarity index, CV-based threshold |
| Prediction | predict_rows, predict_grid, aoa_share |
mean and interval or class, probability and entropy; DI and AOA mask |
| One call | run_study -> StudyResult, explore |
the plugin's stages in order |
| Geometry | adapters.table_from_geodataframe, adapters.folds_to_geodataframe, adapters.fold_shapes |
optional, needs [geo] |
| Formulas | formulas.FORMULAS, formulas.REFERENCES |
LaTeX of every method formula |
Methods
Validation designs and distance diagnostics
Folds are built on coordinates shifted by their minimum, so a translation of the samples gives
the same folds. Square blocks of side size are anchored at the extent minimum; blocks are
shuffled with the seed, sorted by sample count and each goes to the fold with the fewest samples
(Roberts et al. 2017; Valavi et al. 2019). Hexagons have the same area as a size x size
square. Coordinate clusters use k-means++ (Brenning 2012). Buffered leave-one-out tests one sample
at a time and removes every sample within radius from its training set (Le Rest et al. 2014).
kNNDM (Linnenbrink et al. 2024) cuts a Ward clustering of the coordinates at a grid of cluster
counts, merges the clusters into k folds and keeps the cut whose cross-validation
nearest-neighbour distances are closest to the prediction-to-sample distances. When the samples
are not closer to each other than the prediction locations are to the samples (one-sided
Kolmogorov-Smirnov test, p >= 0.05), random k-fold is returned, as in CAST.
The design is checked with three empirical distributions of nearest-neighbour distances (Milà et al. 2022): sample to sample $G_j$, prediction location to sample $G_{ij}$, and test sample to the nearest training sample of its fold $G^*_j$. The distance between the task and a design is
$$W = \int_0^{\infty} \left|\hat{G}{ij}(d) - \hat{G}^{*}{j}(d)\right|,\mathrm{d}d .$$
The default block size and buffer radius are the practical range of the variogram, fitted to the OLS residuals (or to the target), with the Matheron estimator
$$\hat{\gamma}(h) = \frac{1}{2N(h)} \sum_{\lVert s_i - s_j \rVert \in h} \left(z_i - z_j\right)^2$$
and the weighted least squares of Cressie (1985).
Models and intervals
| Model | Prediction | Interval |
|---|---|---|
| OLS | $\hat{\beta} = (X^\top X)^{-1} X^\top y$ | analytic $t$ interval |
| Random forest | $\hat{f}(x) = \frac{1}{T}\sum_{t=1}^{T} f_t(x)$ | quantile regression forest (Meinshausen 2006) |
| Gradient boosting | $F_m(x) = F_{m-1}(x) + \nu,\gamma_{l(x)}$, $\gamma_l = \frac{\sum g_i}{\sum h_i + \lambda}$ | split-conformal on spatial-CV residuals |
| GWR | $\hat{\beta}(u_i) = (X^\top W_i X)^{-1} X^\top W_i y$ | split-conformal |
| MGWR | $y_i = \sum_{j} \beta_{b_j j}(u_i), x_{ij} + \varepsilon_i$ | split-conformal |
The split-conformal half-width is $q = |r|{(\lceil (n+1)(1-\alpha) \rceil)}$ (Lei et al. 2018); when that order statistic does not exist the interval is reported as missing. GWR uses an adaptive bisquare (or fixed Gaussian) kernel with the bandwidth chosen by AICc or CV (golden section, as PySAL mgwr); MGWR uses backfitting with one bandwidth per covariate (Fotheringham, Yang & Kang 2017). Nested tuning scores the model grid on an inner design inside each outer training set (Varma & Simon 2006). The residual Moran's I uses 8 nearest neighbours with a 999-permutation one-sided test, and the optimism gap is $\Delta = \mathrm{RMSE}{\text{spatial CV}} - \mathrm{RMSE}_{\text{random CV}}$ (Ploton et al. 2020).
Explanations
Permutation importance permutes each covariate within the test rows of each fold and reports the mean increase in RMSE (or log loss). TreeSHAP is the exact path-dependent algorithm of Lundberg et al. (2020), vectorised over rows, with local accuracy $f(x) = \phi_0 + \sum_{j} \phi_j(x)$. Partial dependence $\bar{f}j(z) = \frac{1}{n}\sum{i} f(z, x_{i,-j})$ comes with ICE curves (Goldstein et al. 2015); accumulated local effects follow Apley & Zhu (2020).
Area of applicability
Covariates are scaled by the training mean and standard deviation and weighted by the permutation importance of the selected model (categorical covariates enter as dummy columns). With $\bar{d}$ the mean pairwise distance of the training data,
$$\mathrm{DI}(x) = \frac{\min_i d(x, x_i)}{\bar{d}}, \qquad \text{AOA} = {x : \mathrm{DI}(x) \le \min(Q_3 + 1.5,\mathrm{IQR},\ \max \mathrm{DI}_{\text{train}})},$$
where the training DI of each sample is measured against its own cross-validation training set
(Meyer & Pebesma 2021; CAST trainDI and aoa).
Command line
spatialmllab demo samples.csv --pred pred.csv
spatialmllab variogram samples.csv --target target --categorical c4 --id fid
spatialmllab folds samples.csv --scheme knndm --pred pred.csv -o folds.csv
spatialmllab nnd samples.csv --scheme blocks --size 2000 --pred pred.csv
spatialmllab cv samples.csv --target target --categorical c4 --id fid --scheme blocks --size 2000 --model rf
spatialmllab study samples.csv --target target --categorical c4 --id fid --scheme knndm \
--pred pred.csv --models ols,rf,gbm,gwr -o study.json
Sample tables are CSV files with coordinate columns (--x, --y, default x and y). Without
--covariates every other column except the target and --id is a covariate. Results are JSON
on stdout unless -o is given.
Relation to the QGIS plugin
The plugin reads samples from vector layers, extracts covariates from a harmonised raster stack,
writes GeoTIFF outputs and an HTML model card. This package keeps the computations and replaces
the QGIS input and output with arrays: from_arrays for the sample table, predict_grid for an
in-memory covariate grid, and the optional shapely / geopandas adapters for geometries. With the
same arrays, seeds and options both give the same numbers.
Limitations
- Planar coordinates only; no reprojection and no raster I/O (read rasters with rasterio or GDAL).
- GWR and MGWR predict cell by cell from the training samples and are limited to 250 000 valid cells per grid; aggregate the covariates first for larger grids.
- Gradient boosting supports regression and binary classification.
- Spatial cross-validation estimates map accuracy only approximately; with a probability sample a design-based estimate is preferable (Wadoux et al. 2021).
References
- Apley, D. W., & Zhu, J. (2020). Visualizing the effects of predictor variables in black box supervised learning models. Journal of the Royal Statistical Society B, 82(4), 1059-1086.
- Brenning, A. (2012). Spatial cross-validation and bootstrap for the assessment of prediction rules in remote sensing: the R package sperrorest. IGARSS 2012, 5372-5375.
- Breiman, L. (2001). Random forests. Machine Learning, 45, 5-32.
- Cressie, N. (1985). Fitting variogram models by weighted least squares. Mathematical Geology, 17(5), 563-586.
- Fotheringham, A. S., Yang, W., & Kang, W. (2017). Multiscale geographically weighted regression (MGWR). Annals of the American Association of Geographers, 107(6), 1247-1265.
- Goldstein, A., Kapelner, A., Bleich, J., & Pitkin, E. (2015). Peeking inside the black box. Journal of Computational and Graphical Statistics, 24(1), 44-65.
- Le Rest, K., Pinaud, D., Monestiez, P., Chadoeuf, J., & Bretagnolle, V. (2014). Spatial leave-one-out cross-validation for variable selection in the presence of spatial autocorrelation. Global Ecology and Biogeography, 23(7), 811-820.
- Lei, J., G'Sell, M., Rinaldo, A., Tibshirani, R. J., & Wasserman, L. (2018). Distribution-free predictive inference for regression. Journal of the American Statistical Association, 113(523), 1094-1111.
- Linnenbrink, J., Milà, C., Ludwig, M., & Meyer, H. (2024). kNNDM CV: k-fold nearest-neighbour distance matching cross-validation for map accuracy estimation. Geoscientific Model Development, 17, 5897-5912.
- Lundberg, S. M., Erion, G., Chen, H., et al. (2020). From local explanations to global understanding with explainable AI for trees. Nature Machine Intelligence, 2, 56-67.
- Meinshausen, N. (2006). Quantile regression forests. Journal of Machine Learning Research, 7, 983-999.
- Meyer, H., & Pebesma, E. (2021). Predicting into unknown space? Estimating the area of applicability of spatial prediction models. Methods in Ecology and Evolution, 12(9), 1620-1633.
- Milà, C., Mateu, J., Pebesma, E., & Meyer, H. (2022). Nearest neighbour distance matching leave-one-out cross-validation for map validation. Methods in Ecology and Evolution, 13(6), 1304-1316.
- Ploton, P., Mortier, F., Réjou-Méchain, M., et al. (2020). Spatial validation reveals poor predictive performance of large-scale ecological mapping models. Nature Communications, 11, 4540.
- Roberts, D. R., Bahn, V., Ciuti, S., et al. (2017). Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure. Ecography, 40(8), 913-929.
- Valavi, R., Elith, J., Lahoz-Monfort, J. J., & Guillera-Arroita, G. (2019). blockCV: an R package for generating spatially or environmentally separated folds for k-fold cross-validation of species distribution models. Methods in Ecology and Evolution, 10(2), 225-232.
- Varma, S., & Simon, R. (2006). Bias in error estimation when using cross-validation for model selection. BMC Bioinformatics, 7, 91.
- Wadoux, A. M. J.-C., Heuvelink, G. B. M., de Bruin, S., & Brus, D. J. (2021). Spatial cross-validation is not the right way to evaluate map accuracy. Ecological Modelling, 457, 109692.
Citation
@software{eminoglu_spatialmllab,
author = {Eminoğlu, Yusuf},
title = {spatialmllab},
year = {2026},
version = {0.1.0},
url = {https://gitlab.com/geophilo1/spatialmllab_sdk}
}
See also CITATION.cff.
Related Geophilo SDKs
- spatialcv: scikit-learn compatible spatial cross-validation splitters (blocks, clusters, buffers, NNDM, kNNDM).
- spatialsample: design-based spatial sampling (GRTS, BAS, LPM) and map accuracy estimation.
Contributing
Bug reports, questions and merge requests are welcome; see CONTRIBUTING.md. The project follows a Code of Conduct.
License
GPL-2.0-or-later, as the QGIS plugin it comes from; see LICENSE.
Metadata
Release files for spatialmllab 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| spatialmllab-0.1.0.tar.gz | 181.4 kB | Without provenance | Details for spatialmllab-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| spatialmllab-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for spatialmllab-0.1.0-py3-none-any.whl |
Total release size: 274.4 kB
Release files / spatialmllab-0.1.0.tar.gz
| Download URL | spatialmllab-0.1.0.tar.gz |
|---|---|
| Size | 181.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a6e4da695185dd1d3a93acf37ab10fa8645d02615015e98f86f49f182d94626a
|
|
BLAKE2b-256 checksum How to use checksums |
0d9b85854284f35d1250c7d0b3fedd2a4a331f234d4a20d9a5060e2ad33e1fd4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.18
|
Release files / spatialmllab-0.1.0-py3-none-any.whl
| Download URL | spatialmllab-0.1.0-py3-none-any.whl |
|---|---|
| Size | 93.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
1bdc3c97df7b387cf8e808c4685254061dcead99040fa4cd4a419d2d8c4da50f
|
|
BLAKE2b-256 checksum How to use checksums |
be98b0c50a7368d853e84c0488f59e137751e74a961979c36861756c5fb8b4b1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.18
|
Security for spatialmllab 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.