Regression Kriging (RK) combines a deterministic trend (here, a TensorFlow/Keras multilayer perceptron of SOC from environmental covariates) with ordinary kriging of the residuals. At location \(\mathbf{s}\),
where \(\hat{m}(\mathbf{s})\) is the neural-network prediction and \(\hat{e}(\mathbf{s})\) is the kriged residual. Tutorial 7.1 uses scikit-learn-style trend models, tutorial 7.2 uses H2O-3, and tutorial 7.3 uses PyTorch; this notebook uses TensorFlow/Keras via pygstat.DeepRegressionKrigingTF.
The MLP is a feed-forward Keras Sequential network trained with Adam, dropout, and early stopping. TensorFlow uses a GPU automatically when one is registered (tf.config.list_physical_devices('GPU')). After the network is fit, training residuals are interpolated with a spherical ordinary-kriging model — the same residual step as in 7.1–7.3.
This tutorial
We map soil organic carbon across the US Great Plains using 5,000 samples and a ~10 km prediction grid. NLCD land-cover class is one-hot encoded (a neural net has no native factor type). Samples are split stratified by NLCD into train / valid / test. Train is used to fit and tune the network (Optuna K-fold RMSE); valid is the early-stopping frame for the final refit; the best of a default MLP vs the Optuna winner is scored on the test set and then used to predict SOC at grid locations. Section 13 times residual ordinary kriging on CPU vs GPU for prefixes of data/gp_data_5000.csv.
tune_hyperparameters=True runs an Optuna TPE search over architecture and optimizer settings, scores each trial by 3-fold CV RMSE (median pruning of weak trials), then refits one MLP on the full training set with the winning hyperparameters.
This notebook’s param_space (a slightly tighter, tutorial-scale grid — the same shape as pygstat.regression_kriging_tf._default_param_space):
Hyperparameter
Search
Hidden layers
1–3 layers, 32 / 64 / 128 / 256 units each
Dropout
\(0\)–\(0.4\)
Learning rate
\(10^{-4}\)–\(10^{-2}\) (log)
Weight decay
\(10^{-6}\)–\(10^{-3}\) (log)
Batch size
32 / 64 / 128
Pass a different param_space(trial) -> dict to widen the search. Residual kriging is still fit on training residuals only. Requires pip install pygstat[optuna] (or pip install optuna).
2. Mathematical Formulation
The target \(Z(\mathbf{s})\) at location \(\mathbf{s}\) is
where \(\mu(\mathbf{s})\) is a deterministic trend explained by covariates and \(\varepsilon(\mathbf{s})\) is a zero-mean, spatially autocorrelated residual.
Fit a Keras MLP trend
Covariates \(\mathbf{x}(\mathbf{s})\) (NDVI, climate, terrain, soils, NLCD dummies) are standardized, then enter a feed-forward network \(f_{\theta}\):
Each hidden layer is dense \(\to\) ReLU \(\to\) dropout. The network is trained by mini-batch Adam on mean squared error, with gradient clipping (clipnorm=1.0) and early stopping on the validation loss.
Hyperparameters \(\theta\) (layer widths, dropout, learning rate, weight decay, batch size) are chosen by Optuna: trial \(t\) is scored by K-fold validation RMSE, weak trials are pruned, and the minimizer is refit on the full training set.
Trend: SOC tends to increase with NDVI and MAP; land cover is a class effect, not a numeric score
Residuals: unmeasured soil type, management, and local climate
RK: the MLP captures the global / nonlinear trend; kriging adds local spatial structure
3. Python Setup
3.1 CPU and GPU
DeepRegressionKrigingTF has two independent backends:
Argument / stack
What it controls
TensorFlow / Keras
MLP training and inference (GPU if tf.config.list_physical_devices('GPU') is non-empty).
use_gpu
Residual ordinary kriging covariance + solve (NumPy or CuPy).
use_gpu is:
Value
Behaviour
'auto' (default)
GPU when CuPy can run a kernel on this card. Falls back to CPU otherwise.
True
Force GPU. Warns and falls back to CPU if CuPy is missing or cannot run a kernel.
False
Always CPU (NumPy/SciPy).
This notebook probes the GPU once with cupy_gpu_usable() (a real op, not just import cupy) and stores the result in USE_GPU. Every DeepRegressionKrigingTF(...) call below passes use_gpu=USE_GPU. The Keras MLP still uses whatever TensorFlow devices are visible (which can be CPU-only even when CuPy works).
Install CuPy with pip install pygstat[gpu] (CUDA 11) or pip install cupy-cuda12x for CUDA 12.
Section 13 times residual OK (the kriging step inside DeepRegressionKrigingTF) on both backends using prefixes of data/gp_data_5000.csv.
Code
%matplotlib inlineimport sysimport warningsfrom collections import Counterfrom pathlib import Path# pygstat optionally imports PyTorch for DeepRegressionKriging / GNN backends.# Loading that stack in the same process as TensorFlow can crash; keep torch out.sys.modules.setdefault("torch", None)import geopandas as gpdimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport tensorflow as tffrom sklearn.metrics import mean_absolute_error, mean_squared_error, r2_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import OneHotEncoderfrom IPython.display import displayimport ossys.path.insert(0, os.path.abspath("../src"))import pygstatfrom pygstat import DeepRegressionKrigingTF, Variogramfrom pygstat.utils.backend import CUPY_AVAILABLE, cupy_gpu_usablewarnings.filterwarnings("ignore", category=UserWarning)pd.set_option("display.float_format", lambda v: f"{v:0.3f}")print("tensorflow version:", tf.__version__)print("built with CUDA :", tf.test.is_built_with_cuda())gpus = tf.config.list_physical_devices("GPU")print("TensorFlow GPUs :", gpus if gpus else"none (CPU)")if gpus:for gpu in gpus: details = tf.config.experimental.get_device_details(gpu)print("GPU :", details.get("device_name", gpu))else:print("Using device : CPU")try:import optunaprint("optuna version :", optuna.__version__)exceptImportError:raiseImportError("This notebook needs Optuna for hyperparameter tuning. ""Install it with: pip install optuna (or: pip install pygstat[optuna])" )# ── Residual OK: CPU / GPU dispatch (CuPy; independent of TensorFlow GPU) ─────# cupy_gpu_usable() runs a real kernel (not just `import cupy`). Older cards can# import CuPy and still fail at compile time; those stay on CPU.print(f"pygstat version : {pygstat.__version__}")USE_GPU = cupy_gpu_usable()if USE_GPU:import cupy as cpprint(f"CuPy : {cp.__version__}")try: name = cp.cuda.runtime.getDeviceProperties(0)["name"]ifisinstance(name, bytes): name = name.decode()print(f"GPU (CuPy) : {name}")exceptException:print("GPU (CuPy) : available")print("Backend : GPU (CuPy) — residual OK covariance + solve on GPU")else:if CUPY_AVAILABLE:import cupy as cpprint(f"CuPy : {cp.__version__} (installed, but cannot run a kernel on this GPU/CUDA setup)")else:print("CuPy : not installed (pip install pygstat[gpu] or cupy-cuda12x)")print("Backend : CPU (NumPy)")print(f"use_gpu : {USE_GPU}")
tensorflow version: 2.21.0
built with CUDA : True
TensorFlow GPUs : none (CPU)
Using device : CPU
optuna version : 5.0.0
pygstat version : 0.1.0
CuPy : 14.2.0
GPU (CuPy) : NVIDIA GeForce RTX 2080 Ti
Backend : GPU (CuPy) — residual OK covariance + solve on GPU
use_gpu : True
4. Load and Explore the Great Plains Data
Point samples live in data/gp_data_5000.csv (SOC plus covariates at 5,000 locations). The prediction grid is data/gp_grid.csv (covariates only). Coordinates are US Albers Equal Area (EPSG:5070), in metres.
The CSV header repeats NLCD; pandas renames the second copy to NLCD.1. That extra column is dropped. The first NLCD column matches the grid (classes 3–7).
Unlike tutorial 7.2, NLCD is not a native H2O factor. A Keras MLP sees a numeric matrix, so land cover is one-hot encoded — the same encoding as tutorials 7.1 and 7.3:
OneHotEncoder(drop="first") creates dummy columns and drops the first class as the baseline.
The encoder is fit on the sample table and applied to the prediction grid (handle_unknown="ignore").
Before residual kriging, look at the raw SOC variogram on the training coordinates. Lag count uses Scott’s rule on pairwise distances, capped at 30 lags: bin width \(h = 3.5 \, \mathrm{std}\,/\, n^{1/3}\).
Residual variograms (next section) typically have a shorter range than the raw SOC variogram, because the regression has already absorbed the large-scale trend. Residual models use maxlag=50 km and 15 lags — the same setting as tutorials 7.1–7.3.
8. Fit Deep Regression-Kriging Models
Two DeepRegressionKrigingTF trends are fit on the same train / valid split:
default — library architecture [128, 64, 32], no search.
tuned — Optuna searches hidden-layer widths, dropout, learning rate, weight decay, and batch size (n_trials=20, 3-fold CV RMSE, median pruning). The winning trial is refit on the full training set with early stopping on the validation frame.
The best of the two on the test set is kept for mapping. Residual kriging uses training residuals only.
The models above never saw the test coordinates. For each family we report RMSE, MAE, and \(R^2\) of the full RK prediction (MLP trend + kriged residual) on the 20% test set.
Code
rows = []for name, rk in fitted.items(): y_hat = rk.predict(X_test, coords_test) rows.append({"family": name,"hidden_layers": rk.fitted_params_["hidden_layers"],"dropout": rk.fitted_params_["dropout"],"learning_rate": rk.fitted_params_["learning_rate"],"batch_size": rk.fitted_params_["batch_size"],"test_rmse": float(np.sqrt(mean_squared_error(y_test, y_hat))),"test_mae": float(mean_absolute_error(y_test, y_hat)),"test_r2": float(r2_score(y_test, y_hat)),"y_pred_test": y_hat, })results = pd.DataFrame(rows).drop(columns=["y_pred_test"])results = results.sort_values("test_rmse").reset_index(drop=True)best_name = results.iloc[0]["family"]print(f"Best family on the test set: {best_name}")results
One-to-one plots for the best family and the other fitted MLP.
Code
show = [best_name]for extra in ("tuned", "default"):if extra in fitted and extra notin show: show.append(extra)pred_lookup = {row["family"]: row for row in rows}fig, axes = plt.subplots(1, len(show), figsize=(5.5*len(show), 5.2))iflen(show) ==1: axes = [axes]lims = [min(y_test.min(), min(pred_lookup[n]["y_pred_test"].min() for n in show)),max(y_test.max(), max(pred_lookup[n]["y_pred_test"].max() for n in show)),]for ax, name inzip(np.atleast_1d(axes).ravel(), show): y_hat = pred_lookup[name]["y_pred_test"] ax.scatter(y_test, y_hat, s=12, alpha=0.45, edgecolors="none") ax.plot(lims, lims, color="black", linewidth=1) ax.set_title(f"{name} RMSE={pred_lookup[name]['test_rmse']:.2f} "f"$R^2$={pred_lookup[name]['test_r2']:.2f}" ) ax.set_xlabel("Observed SOC (%)") ax.set_ylabel("Predicted SOC (%)") ax.set_aspect("equal", adjustable="box") ax.set_xlim(lims) ax.set_ylim(lims)plt.tight_layout()plt.show()
Residual variograms of two trend models
The residual variogram depends on the trend: a better-tuned MLP typically leaves less structured residual spatial variation (smaller sill / shorter range).
Code
pair = [n for n in ("default", best_name) if n in fitted]iflen(pair) <2: pair =list(fitted.keys())[:2]fig, axes = plt.subplots(1, 2, figsize=(12, 5), sharey=True)for ax, name inzip(axes, pair): vg_r = fitted[name].variogram_ h_fine = np.linspace(0, vg_r.maxlag, 200) ax.scatter(vg_r.lags, vg_r.experimental, color="black", s=22, label="Empirical", zorder=3) ax.plot(h_fine, vg_r(h_fine), color="red", linewidth=2, label="Fitted") nug, ps, rng_r = vg_r.fitted_params ax.axhline(nug + ps, color="gray", linestyle=":", label="Sill") ax.axvline(rng_r, color="gray", linestyle="--", label="Range") ax.set_xlabel("Distance (m)") ax.set_title(f"Residual variogram — {name}") ax.legend()axes[0].set_ylabel("Semivariance")plt.tight_layout()plt.show()
10. Feature Importance
A feed-forward MLP has no native split-based importances. We report permutation importance on the test set: each encoded feature is shuffled in turn, and the increase in RK RMSE is the importance. Residuals depend only on coordinates, so permuting \(X\) isolates the trend contribution.
Code
def permutation_importance_rk(rk, X, y, coords, feature_names, n_repeats=8, seed=42): baseline = np.sqrt(mean_squared_error(y, rk.predict(X, coords))) rng = np.random.default_rng(seed) rows = []for j, name inenumerate(feature_names): deltas = []for _ inrange(n_repeats): Xp = np.array(X, copy=True) rng.shuffle(Xp[:, j]) rmse = np.sqrt(mean_squared_error(y, rk.predict(Xp, coords))) deltas.append(rmse - baseline) rows.append({"feature": name,"importance": float(np.mean(deltas)),"std": float(np.std(deltas)), })return pd.DataFrame(rows).sort_values("importance")imp_names = [n for n in (best_name, "tuned", "default") if n in fitted]seen = []for n in imp_names:if n notin seen: seen.append(n)imp_names = seen[:2]fig, axes = plt.subplots(1, max(1, len(imp_names)), figsize=(5.5*max(1, len(imp_names)), 4.8))iflen(imp_names) <=1: axes = [axes]for ax, name inzip(np.atleast_1d(axes).ravel(), imp_names): imp = permutation_importance_rk( fitted[name], X_test, y_test, coords_test, encoded_feature_names ) ax.barh(imp["feature"], imp["importance"], xerr=imp["std"], color="C0", alpha=0.85) ax.set_title(f"Permutation importance — {name}") ax.set_xlabel("Increase in test RMSE")plt.tight_layout()plt.show()
11. Predict SOC on Grid Locations
Each fitted family predicts at the gp_grid.csv nodes. For the best family we also store the regression-only surface, kriged residuals, and kriging standard error.
Code
print("Predicting SOC on the grid for every MLP family ...")for name, rk in fitted.items(): grid_df[f"SOC_{name}"] = rk.predict(X_grid, coords_grid)best_rk = fitted[best_name]soc_best, se_best = best_rk.predict(X_grid, coords_grid, return_std=True)grid_df["SOC_best"] = soc_bestgrid_df["SOC_best_se"] = se_best# Regression-only trend = RK prediction minus kriged residualgrid_df["resid_best"] = best_rk.krige_.predict(coords_grid)grid_df["reg_best"] = grid_df["SOC_best"] - grid_df["resid_best"]print(grid_df[["x", "y", "SOC_best", "SOC_best_se", "reg_best", "resid_best"]].describe())
Predicting SOC on the grid for every MLP family ...
x y SOC_best SOC_best_se reg_best resid_best
count 10674.000 10674.000 10674.000 10674.000 10674.000 10674.000
mean -753412.225 1757164.871 5.994 0.506 5.965 0.029
std 327749.190 382369.477 3.628 0.317 3.594 0.497
min -1245285.000 1003795.000 0.389 0.000 0.833 -8.131
25% -1005285.000 1503795.000 3.232 0.000 3.186 -0.147
50% -825285.000 1743795.000 5.101 0.690 5.126 0.032
75% -625285.000 2023795.000 7.927 0.711 7.955 0.208
max 114715.000 2533795.000 24.806 0.741 24.750 5.503
Code
out_path = DATA_DIR /"gp_prediction_RK_tf.csv"grid_df.to_csv(out_path, index=False)print(f"Grid predictions saved to {out_path}")
Grid predictions saved to ../data/gp_prediction_RK_tf.csv
12. Map Predictions
Points are plotted in EPSG:5070 with Great Plains state boundaries (data/GP_STATE.shp).
Section 3.1 showed how to select a backend. Here we measure how long residual ordinary kriging — the spatial step inside DeepRegressionKrigingTF — takes on CPU (use_gpu=False, NumPy/SciPy) versus GPU (use_gpu=True, CuPy) for prefixes of the Great Plains SOC survey (data/gp_data_5000.csv, \(n\) up to 5{,}000).
The Keras MLP trend uses TensorFlow’s own devices and is not part of these timings (training an MLP at every \(n\) would dwarf the kriging solve). The GPU-accelerated steps are the \(n \times n\) residual covariance among training points, the \(n_{\text{pred}} \times n\) covariance to the targets, and the linear solve of the augmented OK system. A linear trend (an MLP analogue for residual extraction) is fit once per prefix; that fit and the residual variogram are not included in the OK times.
Two practical notes:
Small \(n\) and few targets (a few hundred training and prediction points) often shows little GPU gain: host→device copies and kernel-launch overhead dominate.
Larger \(n\), or a dense prediction grid, is where the GPU pays off: the OK system scales as \(O(n^3)\) for the solve and \(O(n \cdot n_{\text{pred}})\) for the target covariances.
Each timing is the median of three OrdinaryKriging.fit + predict(..., return_variance=True) calls after a short GPU warmup so CUDA kernel compilation is not counted. If CuPy cannot run a kernel here, the GPU column is skipped and only CPU times are reported.
Code
import timefrom sklearn.linear_model import LinearRegressionfrom pygstat import OrdinaryKrigingN_REPEATS =3N_PRED_GP =500GP_SIZES = [500, 1000, 2000, 4000, 5000]rng_bench = np.random.default_rng(42)pred_idx = rng_bench.choice(len(coords_grid), size=N_PRED_GP, replace=False)xy_pred_b = coords_grid[pred_idx]def _residual_variogram(X_tr, y_tr, xy_tr):"""Linear trend (CPU); residual field is what OK interpolates.""" lin = LinearRegression().fit(np.asarray(X_tr, dtype=float), y_tr) resid = y_tr - lin.predict(np.asarray(X_tr, dtype=float)) vg_kw =dict(VARIOGRAM_KWARGS) vg_kw.pop("use_gpu", None)return Variogram( np.asarray(xy_tr, dtype=float), np.asarray(resid, dtype=float), model="spherical", estimator="matheron", use_gpu=False,**vg_kw, ).fit(), residdef _time_ok(xy_train, z_train, xy_pred, vg, use_gpu, repeats=N_REPEATS, warmup=True):"""Median wall time of OrdinaryKriging.fit + predict(return_variance=True)."""if warmup: k_tr =min(40, len(xy_train)) k_pr =min(40, len(xy_pred)) OrdinaryKriging(vg, use_gpu=use_gpu).fit( xy_train[:k_tr], z_train[:k_tr] ).predict(xy_pred[:k_pr], return_variance=True)if use_gpu:import cupy as cp cp.cuda.Device(0).synchronize() times = [] last =Nonefor _ inrange(repeats): t0 = time.perf_counter() ok_m = OrdinaryKriging(vg, use_gpu=use_gpu).fit(xy_train, z_train) last = ok_m.predict(xy_pred, return_variance=True)if use_gpu:import cupy as cp cp.cuda.Device(0).synchronize() times.append(time.perf_counter() - t0)returnfloat(np.median(times)), lastprint(f"GPU usable : {USE_GPU}")print(f"Repeats : {N_REPEATS} (median wall time of residual OK fit + predict)")print(f"GP SOC : {len(y)} samples from data/gp_data_5000.csv")print("Trend : linear (MLP analogue; residual OK uses use_gpu)")print(f"GP n_pred : {N_PRED_GP} grid locations")print()rows = []for n in GP_SIZES: X_tr = np.asarray(X[:n], dtype=float) y_tr = y[:n] xy_tr = coords[:n] vg, resid = _residual_variogram(X_tr, y_tr, xy_tr) cpu_t, pred_cpu = _time_ok(xy_tr, resid, xy_pred_b, vg, use_gpu=False) row = {"dataset": "GP (SOC)","n_train": n,"n_pred": N_PRED_GP,"CPU (s)": cpu_t,"GPU (s)": np.nan,"speedup": np.nan,"match": "—", }if USE_GPU: gpu_t, pred_gpu = _time_ok(xy_tr, resid, xy_pred_b, vg, use_gpu=True) row["GPU (s)"] = gpu_t row["speedup"] = cpu_t / gpu_t z_c, se_c = pred_cpu z_g, se_g = pred_gpu row["match"] =bool( np.allclose(z_c, z_g, rtol=1e-4, atol=1e-4, equal_nan=True)and np.allclose(se_c, se_g, rtol=1e-4, atol=1e-4, equal_nan=True) )import cupy as cp cp.get_default_memory_pool().free_all_blocks() rows.append(row)df_bench = pd.DataFrame(rows)df_show = df_bench.copy()df_show["CPU (ms)"] = (df_show["CPU (s)"] *1000).round(1)df_show["GPU (ms)"] = (df_show["GPU (s)"] *1000).round(1)df_show["speedup"] = df_show["speedup"].map(lambda x: "—"if pd.isna(x) elsef"{x:.2f}×")print(df_show[["dataset", "n_train", "n_pred", "CPU (ms)", "GPU (ms)", "speedup", "match"]].to_string(index=False))fig, axes = plt.subplots(1, 2, figsize=(12, 4.2))n_vals = df_bench["n_train"].to_numpy()cpu_ms = df_bench["CPU (s)"].to_numpy() *1000gpu_ms = df_bench["GPU (s)"].to_numpy() *1000labels = [str(int(n)) for n in n_vals]x = np.arange(len(n_vals))w =0.36axes[0].bar(x - w /2, cpu_ms, w, label="CPU (NumPy)", color="steelblue")if USE_GPU and np.isfinite(gpu_ms).all(): axes[0].bar(x + w /2, gpu_ms, w, label="GPU (CuPy)", color="darkorange")axes[0].set_xticks(x)axes[0].set_xticklabels(labels, fontsize=9)axes[0].set_xlabel("Number of training points $n$")axes[0].set_ylabel("Median time (ms)")axes[0].set_title("Residual OrdinaryKriging (TensorFlow RK) — CPU vs GPU")axes[0].legend()axes[0].set_yscale("log")if USE_GPU: axes[1].plot(n_vals, df_bench["speedup"], "o-", color="darkgreen", lw=2) axes[1].axhline(1.0, color="grey", ls="--", lw=1) axes[1].set_xlabel("Number of training points $n$") axes[1].set_ylabel("Speedup (CPU time / GPU time)") axes[1].set_title("GPU speedup vs training size") axes[1].grid(True, alpha=0.3)else: axes[1].text(0.5, 0.5,"GPU not usable in this environment\nCPU-only timings shown", ha="center", va="center", transform=axes[1].transAxes, ) axes[1].set_axis_off()plt.tight_layout()plt.show()
GPU usable : True
Repeats : 3 (median wall time of residual OK fit + predict)
GP SOC : 5000 samples from data/gp_data_5000.csv
Trend : linear (MLP analogue; residual OK uses use_gpu)
GP n_pred : 500 grid locations
dataset n_train n_pred CPU (ms) GPU (ms) speedup match
GP (SOC) 500 500 61.2 11.4 5.36× True
GP (SOC) 1000 500 150.0 25.4 5.91× True
GP (SOC) 2000 500 376.9 60.3 6.26× True
GP (SOC) 4000 500 1333.8 213.3 6.25× True
GP (SOC) 5000 500 2128.8 362.1 5.88× True
Predictions and residual-kriging standard errors from the two backends should match (match = True). The Keras MLP trend is independent of this comparison; the GPU speedup comes from the residual OK covariance build and solve. On the Great Plains SOC prefixes the \(O(n^2)\) covariance and \(O(n^3)\) solve keep the GPU several times faster as \(n\) grows to 5{,}000. Use use_gpu=USE_GPU (as the rest of this notebook does) so the same cells run on a laptop CPU or a CUDA workstation without edits.
14. Summary and Conclusions
This notebook applied regression kriging to Great Plains soil organic carbon with a TensorFlow/Keras MLP trend (pygstat.DeepRegressionKrigingTF).
Data. 5,000 samples (gp_data_5000.csv) and a 10 km grid (gp_grid.csv). NLCD is a categorical land-cover class, dummy-encoded with OneHotEncoder(drop="first") rather than treated as an ordinal score.
Split. NLCD-stratified 60% train / 20% valid / 20% test. Train fits the trend (and Optuna CV) and residual kriging; valid is the early-stopping frame for the final MLP; test is used only for the final comparison.
Families. A default MLP ([128, 64, 32]) and an Optuna-tuned MLP (20 trials, 3-fold CV RMSE, median pruning) were each scored on the test set. The best of the two was used to map SOC on the grid.
Mapping. SOC, the MLP trend, kriged residuals, and kriging standard error were written to data/gp_prediction_RK_tf.csv.
CPU / GPU. Residual ordinary kriging (use_gpu=USE_GPU) was timed on prefixes of gp_data_5000.csv. The Keras MLP uses TensorFlow’s own devices; the \(O(n^2)\) covariance and \(O(n^3)\) OK solve are the CuPy-accelerated steps.
Regression kriging with a TensorFlow MLP is a practical workflow when you want nonlinear capacity, Keras/GPU training, Optuna architecture search, and geostatistical residuals on the same spatial support. The calling API matches tutorial 7.3 (DeepRegressionKriging) so the two backends can be swapped with the same code.
15. Resources
Papers and books
Reference
Notes
Hengl, T., Heuvelink, G.B.M. & Stein, A. (2004). A generic framework for spatial prediction of soil variables based on regression-kriging. Geoderma 120, 75–93.
RK as used in digital soil mapping
Hengl, T., Heuvelink, G.B.M. & Rossiter, D.G. (2007). About regression-kriging: from equations to case studies. Computers & Geosciences 33, 1301–1315.
Practical RK workflow
Odeh, I.O.A., McBratney, A.B. & Chittleborough, D.J. (1995). Further results on prediction of soil properties from terrain attributes: heterotopic cokriging and regression-kriging. Geoderma 67, 215–226.
Early RK for soil properties
Goovaerts, P. (1997). Geostatistics for Natural Resources Evaluation. Oxford University Press.
SK with a varying local mean
Akiba, T., Sano, S., Yanase, T., Ohta, T. & Koyama, M. (2019). Optuna: A next-generation hyperparameter optimization framework. KDD.
TPE sampler and pruning used here
Abadi, M. et al. (2016). TensorFlow: A system for large-scale machine learning. OSDI.
Keras/TensorFlow backend used here
In this library
Object
Role
pygstat.DeepRegressionKrigingTF
Keras MLP trend + ordinary kriging of residuals (use_gpu)
Custom trial -> dict search space (defaults to _default_param_space)
fit(..., X_val=, y_val=)
Validation arrays for early stopping of the final MLP
best_params_, best_score_, study_
Winning hyperparameters, CV RMSE, and the Optuna study
plot_losses(), plot_optuna_history()
Training curves and optimization history
pygstat.Variogram
Residual (and exploratory) variogram
Install extras with pip install pygstat[tensorflow,optuna]. TensorFlow uses a GPU automatically when tf.config.list_physical_devices('GPU') is non-empty; otherwise training runs on CPU.