6.3 Regression Kriging with PyTorch

Dataset: Great Plains soil survey (data/gp_data_5000.csv, data/gp_grid.csv)

Target: Soil Organic Carbon (SOC, %)

Covariates: NDVI, MAP, MAT, elevation, slope, TPI, aspect, K-factor, silt+clay, NLCD (categorical)

Library: pygstat v0.1.0 — DeepRegressionKriging


Table of Contents

  1. Overview
  2. Mathematical Formulation
  3. Python Setup
  4. Load and Explore the Great Plains Data
  5. Prepare Features
  6. Stratified Train / Valid / Test Split
  7. Exploratory Variogram of SOC
  8. Fit Deep Regression-Kriging Models
  9. Hold-Out Comparison on the Test Set
  10. Feature Importance
  11. Predict SOC on Grid Locations
  12. Map Predictions
  13. CPU vs GPU RK Timing
  14. Summary and Conclusions
  15. Resources

1. Overview

Regression Kriging (RK) combines a deterministic trend (here, a PyTorch multilayer perceptron of SOC from environmental covariates) with ordinary kriging of the residuals. At location \(\mathbf{s}\),

\[ Z(\mathbf{s}) = \hat{m}(\mathbf{s}) + \hat{e}(\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 and tutorial 7.2 uses H2O-3; this notebook uses PyTorch via pygstat.DeepRegressionKriging.

The MLP is a feed-forward network trained with Adam, dropout, and early stopping. GPU acceleration is used automatically when CUDA is available (device='auto'). After the network is fit, training residuals are interpolated with a spherical ordinary-kriging model — the same residual step as in 7.1 and 7.2.

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.

2. Mathematical Formulation

The target \(Z(\mathbf{s})\) at location \(\mathbf{s}\) is

\[ Z(\mathbf{s}) = \mu(\mathbf{s}) + \varepsilon(\mathbf{s}) \]

where \(\mu(\mathbf{s})\) is a deterministic trend explained by covariates and \(\varepsilon(\mathbf{s})\) is a zero-mean, spatially autocorrelated residual.

Fit a PyTorch MLP trend

Covariates \(\mathbf{x}(\mathbf{s})\) (NDVI, climate, terrain, soils, NLCD dummies) are standardized, then enter a feed-forward network \(f_{\theta}\):

\[ \hat{\mu}(\mathbf{s}) = f_{\theta}\bigl(\mathbf{x}(\mathbf{s})\bigr) \]

Each hidden layer is linear \(\to\) ReLU \(\to\) dropout. The network is trained by mini-batch Adam on mean squared error, with gradient clipping 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.

Residuals and variogram

\[ e_i = z_i - \hat{\mu}(\mathbf{s}_i), \quad i = 1, \ldots, n_{\mathrm{train}} \]

\[ \hat{\gamma}(h) = \frac{1}{2|N(h)|} \sum_{(i,j) \in N(h)} (e_i - e_j)^2 \]

Spherical model:

\[ \gamma(h) = \begin{cases} c_0 + c \left(1.5 \frac{h}{a} - 0.5 \left(\frac{h}{a}\right)^3 \right), & h < a \\ c_0 + c, & h \geq a \end{cases} \]

Ordinary kriging of residuals

\[ \hat{\varepsilon}(\mathbf{s}_0) = \sum_{i=1}^{n} \lambda_i e_i \]

with the usual unbiasedness constraint \(\sum_i \lambda_i = 1\). Final prediction:

\[ \hat{Z}(\mathbf{s}_0) = \hat{\mu}(\mathbf{s}_0) + \hat{\varepsilon}(\mathbf{s}_0) \]

Kriging variance \(\sigma_K^2(\mathbf{s}_0)\) is reported as a standard error when return_std=True.

Why a neural net for the trend?

Method Pros Cons
sklearn ensembles (tutorial 7.1) Simple Python API, native importances No GPU training / AutoML-style architecture search
H2O GLM / DRF / GBM / AutoML (tutorial 7.2) Native categoricals, grid search Requires Java / H2O cluster
PyTorch MLP (this notebook) Nonlinear capacity, GPU, Optuna architecture search Needs dummy-coded factors; less interpretable

Real-world example: soil organic carbon

  • Covariates: NDVI, MAP, MAT, elevation, slope, TPI, aspect, K-factor, silt+clay, NLCD class
  • 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

DeepRegressionKriging has two independent backends:

Argument What it controls
device PyTorch MLP training / inference ('cpu' or 'cuda').
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 DeepRegressionKriging(...) call below passes use_gpu=USE_GPU. The MLP still uses device=DEVICE (PyTorch CUDA, which can be unavailable 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 DeepRegressionKriging) on both backends using prefixes of data/gp_data_5000.csv.

Code
%matplotlib inline

import sys
import warnings
from collections import Counter
from 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 gpd
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder

from IPython.display import display

import os
sys.path.insert(0, os.path.abspath("../src"))

import pygstat
from pygstat import DeepRegressionKriging, Variogram
from pygstat.utils.backend import CUPY_AVAILABLE, cupy_gpu_usable

warnings.filterwarnings("ignore", category=UserWarning)
pd.set_option("display.float_format", lambda v: f"{v:0.3f}")

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)
try:
    import optuna
    print("optuna version:", optuna.__version__)
except ImportError:
    raise ImportError(
        "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 PyTorch DEVICE) ─────
# 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 cp
    print(f"CuPy            : {cp.__version__}")
    try:
        name = cp.cuda.runtime.getDeviceProperties(0)["name"]
        if isinstance(name, bytes):
            name = name.decode()
        print(f"GPU (CuPy)      : {name}")
    except Exception:
        print("GPU (CuPy)      : available")
    print("Backend         : GPU (CuPy) — residual OK covariance + solve on GPU")
else:
    if CUPY_AVAILABLE:
        import cupy as cp
        print(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}")
torch version : 2.13.0+cu132
CUDA available: False
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).

Code
DATA_DIR = Path("..") / "data"
df = pd.read_csv(DATA_DIR / "gp_data_5000.csv")
grid_df = pd.read_csv(DATA_DIR / "gp_grid.csv")
df = df.drop(columns=["NLCD.1"], errors="ignore")

print(f"Samples: {len(df):,}  |  Grid nodes: {len(grid_df):,}")
print("Sample columns:", list(df.columns))
print("Grid columns  :", list(grid_df.columns))
df.head()
Samples: 5,000  |  Grid nodes: 10,674
Sample columns: ['x', 'y', 'Aspect', 'ELEV', 'FRG', 'K_Factor', 'MAP', 'MAT', 'NDVI', 'NLCD', 'Silt_Clay', 'Slope', 'TPI', 'SOC']
Grid columns  : ['x', 'y', 'Aspect', 'ELEV', 'FRG', 'K_Factor', 'MAP', 'MAT', 'NDVI', 'NLCD', 'Silt_Clay', 'Slope', 'TPI']
x y Aspect ELEV FRG K_Factor MAP MAT NDVI NLCD Silt_Clay Slope TPI SOC
0 -955285 1723795 190.940 3253.481 3 0.215 509.138 1.762 0.556 4 43.669 16.048 -10.496 7.543
1 -735285 1973795 151.478 1464.636 2 0.213 346.082 9.494 0.598 7 48.345 1.105 -0.606 6.102
2 -975285 1103795 129.981 1441.645 133 0.113 372.746 15.772 0.240 5 38.460 12.090 2.134 3.612
3 -395285 1883795 143.176 841.139 2 0.320 548.891 10.720 0.483 6 87.090 2.587 -0.656 7.510
4 -925285 1173795 224.582 1490.576 3 0.284 357.764 14.428 0.216 5 53.868 6.122 0.595 2.378
Code
print(df[["SOC", "NDVI", "MAP", "MAT", "ELEV", "Silt_Clay"]].describe().round(2))

NLCD_DES = {
    3: "Barren / other",
    4: "Forest",
    5: "Shrubland",
    6: "Herbaceous",
    7: "Planted/Cultivated",
}
print("\nNLCD classes (samples):")
print(
    df.groupby("NLCD").size().rename("n").to_frame()
    .assign(description=lambda s: s.index.map(NLCD_DES))
)
           SOC     NDVI      MAP      MAT     ELEV  Silt_Clay
count 5000.000 5000.000 5000.000 5000.000 5000.000   5000.000
mean     6.030    0.410  488.670    9.100 1657.040     53.890
std      3.700    0.160  213.480    4.180  743.290     16.410
min      0.030    0.050  153.580   -2.520  234.550      1.750
25%      3.240    0.270  345.480    6.290 1207.240     42.360
50%      5.120    0.380  424.780    9.570 1656.710     52.610
75%      8.030    0.530  585.630   12.420 2175.490     62.700
max     23.750    0.820 1749.110   17.880 3688.660     90.740

NLCD classes (samples):
         n         description
NLCD                          
3       19      Barren / other
4      956              Forest
5     1657           Shrubland
6     1519          Herbaceous
7      849  Planted/Cultivated
Code
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
axes[0].hist(df["SOC"], bins=30, color="steelblue", edgecolor="white")
axes[0].set_xlabel("SOC (%)")
axes[0].set_ylabel("Count")
axes[0].set_title("SOC distribution (5,000 samples)")

sc = axes[1].scatter(df["x"], df["y"], c=df["SOC"], s=6, cmap="YlGn", edgecolors="none")
axes[1].set_xlabel("Easting (m)")
axes[1].set_ylabel("Northing (m)")
axes[1].set_title("SOC sample locations")
axes[1].set_aspect("equal", adjustable="datalim")
fig.colorbar(sc, ax=axes[1], label="SOC (%)")
plt.tight_layout()
plt.show()


5. Prepare Features

Unlike tutorial 7.2, NLCD is not a native H2O factor. A PyTorch MLP sees a numeric matrix, so land cover is one-hot encoded — the same encoding as tutorial 7.1:

  • 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").
Code
required_cols = [
    "x", "y", "NDVI", "MAP", "MAT", "ELEV", "Slope", "TPI",
    "Aspect", "K_Factor", "Silt_Clay", "NLCD",
]
for col in required_cols:
    if col not in df.columns or col not in grid_df.columns:
        raise ValueError(f"Missing column: {col}")

numeric_cols = [
    "NDVI", "MAP", "MAT", "ELEV", "Slope", "TPI",
    "Aspect", "K_Factor", "Silt_Clay",
]
cat_cols = ["NLCD"]

encoder = OneHotEncoder(
    drop="first",
    handle_unknown="ignore",
    sparse_output=False,
    dtype=float,
)
encoder.fit(df[cat_cols])
nlcd_dummy_names = encoder.get_feature_names_out(cat_cols).tolist()
encoded_feature_names = numeric_cols + nlcd_dummy_names
baseline = encoder.categories_[0][0]


def encode_X(frame):
    num = frame[numeric_cols].to_numpy(dtype=float)
    cat = encoder.transform(frame[cat_cols])
    return np.hstack([num, cat])


X = encode_X(df)
y = df["SOC"].to_numpy(dtype=float)
coords = df[["x", "y"]].to_numpy(dtype=float)
X_grid = encode_X(grid_df)
coords_grid = grid_df[["x", "y"]].to_numpy(dtype=float)
nlcd_labels = df["NLCD"].to_numpy()

print("Numeric features:", numeric_cols)
print("NLCD categories :", list(encoder.categories_[0]))
print(f"Dropped baseline: {int(baseline)} ({NLCD_DES.get(int(baseline), '?')})")
print("Dummy columns   :", nlcd_dummy_names)
print("Encoded features:", encoded_feature_names)
print("X:", X.shape, "  y:", y.shape, "  coords:", coords.shape)
print("Grid X:", X_grid.shape)
Numeric features: ['NDVI', 'MAP', 'MAT', 'ELEV', 'Slope', 'TPI', 'Aspect', 'K_Factor', 'Silt_Clay']
NLCD categories : [np.int64(3), np.int64(4), np.int64(5), np.int64(6), np.int64(7)]
Dropped baseline: 3 (Barren / other)
Dummy columns   : ['NLCD_4', 'NLCD_5', 'NLCD_6', 'NLCD_7']
Encoded features: ['NDVI', 'MAP', 'MAT', 'ELEV', 'Slope', 'TPI', 'Aspect', 'K_Factor', 'Silt_Clay', 'NLCD_4', 'NLCD_5', 'NLCD_6', 'NLCD_7']
X: (5000, 13)   y: (5000,)   coords: (5000, 2)
Grid X: (10674, 13)

6. Stratified Train / Valid / Test Split

A 60% / 20% / 20% split, stratified by NLCD so each land-cover class appears in train, valid, and test (random_state=42).

  • Train — fit the MLP trend (and Optuna CV folds) and the residual variogram / kriging
  • Valid — early-stopping frame for the final production MLP (X_val, y_val in fit())
  • Test — untouched hold-out used only after the best of default vs tuned is chosen
Code
counts = Counter(nlcd_labels)
stratify_arg = nlcd_labels if min(counts.values()) >= 3 else None

(
    X_temp, X_test,
    y_temp, y_test,
    coords_temp, coords_test,
    nlcd_temp, nlcd_test,
) = train_test_split(
    X, y, coords, nlcd_labels,
    test_size=0.20,
    random_state=42,
    shuffle=True,
    stratify=stratify_arg,
)

(
    X_train, X_valid,
    y_train, y_valid,
    coords_train, coords_valid,
    nlcd_train, nlcd_valid,
) = train_test_split(
    X_temp, y_temp, coords_temp, nlcd_temp,
    test_size=0.25,  # 0.25 * 0.80 = 0.20 overall
    random_state=42,
    shuffle=True,
    stratify=nlcd_temp if stratify_arg is not None else None,
)


def _nlcd_counts(arr):
    return sorted(Counter(arr).items())


print(f"Train: {len(X_train):,}  |  Valid: {len(X_valid):,}  |  Test: {len(X_test):,}")
print("NLCD train:", _nlcd_counts(nlcd_train))
print("NLCD valid:", _nlcd_counts(nlcd_valid))
print("NLCD test :", _nlcd_counts(nlcd_test))
Train: 3,000  |  Valid: 1,000  |  Test: 1,000
NLCD train: [(np.int64(3), 11), (np.int64(4), 574), (np.int64(5), 995), (np.int64(6), 911), (np.int64(7), 509)]
NLCD valid: [(np.int64(3), 4), (np.int64(4), 191), (np.int64(5), 331), (np.int64(6), 304), (np.int64(7), 170)]
NLCD test : [(np.int64(3), 4), (np.int64(4), 191), (np.int64(5), 331), (np.int64(6), 304), (np.int64(7), 170)]

7. Exploratory Variogram of SOC

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}\).

Code
# Scott's rule on a random subset keeps the n=3,000 distance matrix light
rng = np.random.default_rng(42)
idx = rng.choice(len(coords_train), size=min(1200, len(coords_train)), replace=False)
sample_xy = coords_train[idx]
distances = np.sqrt(((sample_xy[:, None, :] - sample_xy[None, :, :]) ** 2).sum(axis=2))
upper_triangle = distances[np.triu_indices_from(distances, k=1)]
std_dist = np.nanstd(upper_triangle)
n_pairs = len(upper_triangle)
scott_bin_width = 3.5 * std_dist / (n_pairs ** (1 / 3))
maxlag_soc = float(np.nanpercentile(upper_triangle, 50))
n_lags_soc = max(5, min(30, int(maxlag_soc / scott_bin_width)))
print(f"Using Scott rule → n_lags: {n_lags_soc}, maxlag: {maxlag_soc:.1f} m")
Using Scott rule → n_lags: 30, maxlag: 601664.4 m
Code
vg = Variogram(
    coords_train, y_train,
    model="spherical",
    estimator="matheron",
    maxlag=maxlag_soc,
    n_lags=n_lags_soc,
    use_gpu="auto",
)
vg.fit()
mask = ~np.isnan(vg.experimental)
rmse_vg = np.sqrt(np.mean((vg.experimental[mask] - vg(vg.lags)[mask]) ** 2))
nugget, psill, rng_m = vg.fitted_params
print(f"Spherical model RMSE: {rmse_vg:.2f}")
print(f"nugget={nugget:.3f}, partial sill={psill:.3f}, range={rng_m:.1f} m")
Spherical model RMSE: 0.51
nugget=3.209, partial sill=10.594, range=300832.2 m
Code
plt.figure(figsize=(6, 5))
plt.scatter(vg.lags, vg.experimental, color="black", label="Empirical", zorder=3)
h_fine = np.linspace(0, vg.maxlag, 200)
plt.plot(h_fine, vg(h_fine), color="red", linewidth=2, label="Fitted spherical")
plt.axhline(nugget + psill, color="gray", linestyle=":", label="Sill")
plt.axvline(rng_m, color="gray", linestyle="--", label="Range")
plt.xlabel("Distance (m)")
plt.ylabel("Semivariance")
plt.title("Exploratory variogram of SOC (train)")
plt.legend()
plt.tight_layout()
plt.show()

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 and 7.2.


8. Fit Deep Regression-Kriging Models

Two DeepRegressionKriging trends are fit on the same train / valid split:

  1. default — library architecture [128, 64, 32], no search.
  2. 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.

Code
VARIOGRAM_KWARGS = {"maxlag": 50_000, "n_lags": 15}

COMMON = dict(
    device=DEVICE,
    use_gpu=USE_GPU,
    variogram_model="spherical",
    variogram_kwargs=VARIOGRAM_KWARGS,
    max_epochs=200,
    patience=20,
)


def param_space(trial):
    n_layers = trial.suggest_int("n_layers", 1, 3)
    hidden_layers = [
        trial.suggest_categorical(f"n_units_l{i}", [32, 64, 128, 256])
        for i in range(n_layers)
    ]
    return {
        "hidden_layers": hidden_layers,
        "dropout": trial.suggest_float("dropout", 0.0, 0.4),
        "learning_rate": trial.suggest_float("learning_rate", 1e-4, 1e-2, log=True),
        "weight_decay": trial.suggest_float("weight_decay", 1e-6, 1e-3, log=True),
        "batch_size": trial.suggest_categorical("batch_size", [32, 64, 128]),
    }


FAMILY_SPECS = {
    "default": dict(
        hidden_layers=[128, 64, 32],
        dropout=0.2,
        learning_rate=1e-3,
        weight_decay=0.0,
        batch_size=64,
        tune_hyperparameters=False,
    ),
    "tuned": dict(
        tune_hyperparameters=True,
        param_space=param_space,
        n_trials=20,
        cv_folds=3,
        tuning_max_epochs=80,
        tuning_patience=10,
        tuning_seed=42,
        tuning_verbose=True,
    ),
}

fitted = {}
fit_errors = {}

for name, extra in FAMILY_SPECS.items():
    print(f"\n=== Fitting DeepRegressionKriging '{name}' ===")
    try:
        rk = DeepRegressionKriging(**COMMON, **extra)
        rk.fit(X_train, y_train, coords_train, X_val=X_valid, y_val=y_valid)
        fitted[name] = rk
        print("  ", rk)
        print("  fitted_params_:", rk.fitted_params_)
        if hasattr(rk, "best_score_"):
            print(f"  Optuna CV RMSE: {rk.best_score_:.4f}")
            trials = rk.study_.trials_dataframe()
            display(trials.sort_values("value").head(8))
    except Exception as exc:
        fit_errors[name] = str(exc)
        print(f"  FAILED: {exc}")

print("\nFitted families:", list(fitted))
if fit_errors:
    print("Failures:", fit_errors)

=== Fitting DeepRegressionKriging 'default' ===
Epoch 1/200 - Train Loss: 18.810551, Val Loss: 3.615897
Epoch 2/200 - Train Loss: 5.134625, Val Loss: 2.675757
Epoch 3/200 - Train Loss: 4.319208, Val Loss: 2.541654
Epoch 4/200 - Train Loss: 4.135131, Val Loss: 2.459474
Epoch 5/200 - Train Loss: 3.951844, Val Loss: 2.205008
Epoch 6/200 - Train Loss: 3.766086, Val Loss: 2.468686
Epoch 7/200 - Train Loss: 3.844938, Val Loss: 2.111066
Epoch 8/200 - Train Loss: 3.276914, Val Loss: 2.114988
Epoch 9/200 - Train Loss: 3.526283, Val Loss: 1.961713
Epoch 10/200 - Train Loss: 3.486563, Val Loss: 1.881606
Epoch 11/200 - Train Loss: 3.241820, Val Loss: 1.888735
Epoch 12/200 - Train Loss: 3.305532, Val Loss: 1.881006
Epoch 13/200 - Train Loss: 3.156972, Val Loss: 1.791517
Epoch 14/200 - Train Loss: 3.114797, Val Loss: 1.740660
Epoch 15/200 - Train Loss: 3.052254, Val Loss: 1.769683
Epoch 16/200 - Train Loss: 3.154771, Val Loss: 1.728826
Epoch 17/200 - Train Loss: 2.917768, Val Loss: 1.765085
Epoch 18/200 - Train Loss: 3.070506, Val Loss: 1.737792
Epoch 19/200 - Train Loss: 2.833912, Val Loss: 1.675215
Epoch 20/200 - Train Loss: 2.895495, Val Loss: 1.660927
Epoch 21/200 - Train Loss: 2.771256, Val Loss: 1.604915
Epoch 22/200 - Train Loss: 2.742045, Val Loss: 1.670042
Epoch 23/200 - Train Loss: 2.750870, Val Loss: 1.751367
Epoch 24/200 - Train Loss: 2.790560, Val Loss: 1.559720
Epoch 25/200 - Train Loss: 2.565650, Val Loss: 1.606180
Epoch 26/200 - Train Loss: 2.711809, Val Loss: 1.525171
Epoch 27/200 - Train Loss: 2.695268, Val Loss: 1.591236
Epoch 28/200 - Train Loss: 2.681319, Val Loss: 1.552961
Epoch 29/200 - Train Loss: 2.573574, Val Loss: 1.595541
Epoch 30/200 - Train Loss: 2.419249, Val Loss: 1.549698
Epoch 31/200 - Train Loss: 2.421514, Val Loss: 1.629645
Epoch 32/200 - Train Loss: 2.583763, Val Loss: 1.436810
Epoch 33/200 - Train Loss: 2.422569, Val Loss: 1.646755
Epoch 34/200 - Train Loss: 2.512928, Val Loss: 1.519096
Epoch 35/200 - Train Loss: 2.536540, Val Loss: 1.670426
Epoch 36/200 - Train Loss: 2.339937, Val Loss: 1.477265
Epoch 37/200 - Train Loss: 2.219543, Val Loss: 1.511283
Epoch 38/200 - Train Loss: 2.321862, Val Loss: 1.416111
Epoch 39/200 - Train Loss: 2.354116, Val Loss: 1.398306
Epoch 40/200 - Train Loss: 2.184581, Val Loss: 1.457650
Epoch 41/200 - Train Loss: 2.355312, Val Loss: 1.421798
Epoch 42/200 - Train Loss: 2.292329, Val Loss: 1.482793
Epoch 43/200 - Train Loss: 2.348309, Val Loss: 1.435639
Epoch 44/200 - Train Loss: 2.069203, Val Loss: 1.387414
Epoch 45/200 - Train Loss: 2.126595, Val Loss: 1.529859
Epoch 46/200 - Train Loss: 2.132458, Val Loss: 1.417685
Epoch 47/200 - Train Loss: 2.164514, Val Loss: 1.447371
Epoch 48/200 - Train Loss: 2.109487, Val Loss: 1.394134
Epoch 49/200 - Train Loss: 2.214307, Val Loss: 1.393148
Epoch 50/200 - Train Loss: 2.163525, Val Loss: 1.391086
Epoch 51/200 - Train Loss: 2.161390, Val Loss: 1.415324
Epoch 52/200 - Train Loss: 2.064496, Val Loss: 1.359369
Epoch 53/200 - Train Loss: 2.271495, Val Loss: 1.472679
Epoch 54/200 - Train Loss: 2.140872, Val Loss: 1.426654
Epoch 55/200 - Train Loss: 2.071413, Val Loss: 1.363436
Epoch 56/200 - Train Loss: 1.992654, Val Loss: 1.551570
Epoch 57/200 - Train Loss: 2.035180, Val Loss: 1.539428
Epoch 58/200 - Train Loss: 2.035427, Val Loss: 1.352189
Epoch 59/200 - Train Loss: 1.916707, Val Loss: 1.331647
Epoch 60/200 - Train Loss: 2.041711, Val Loss: 1.374484
Epoch 61/200 - Train Loss: 2.035263, Val Loss: 1.290284
Epoch 62/200 - Train Loss: 2.084027, Val Loss: 1.296797
Epoch 63/200 - Train Loss: 2.052929, Val Loss: 1.352603
Epoch 64/200 - Train Loss: 1.940768, Val Loss: 1.556432
Epoch 65/200 - Train Loss: 1.949393, Val Loss: 1.336667
Epoch 66/200 - Train Loss: 1.949702, Val Loss: 1.340336
Epoch 67/200 - Train Loss: 1.948379, Val Loss: 1.329016
Epoch 68/200 - Train Loss: 1.865773, Val Loss: 1.322853
Epoch 69/200 - Train Loss: 1.982893, Val Loss: 1.448635
Epoch 70/200 - Train Loss: 1.848167, Val Loss: 1.325147
Epoch 71/200 - Train Loss: 1.913332, Val Loss: 1.346557
Epoch 72/200 - Train Loss: 1.881352, Val Loss: 1.266742
Epoch 73/200 - Train Loss: 1.824153, Val Loss: 1.335081
Epoch 74/200 - Train Loss: 1.927994, Val Loss: 1.330948
Epoch 75/200 - Train Loss: 1.981131, Val Loss: 1.285661
Epoch 76/200 - Train Loss: 1.842138, Val Loss: 1.355156
Epoch 77/200 - Train Loss: 1.820123, Val Loss: 1.372663
Epoch 78/200 - Train Loss: 1.976091, Val Loss: 1.309348
Epoch 79/200 - Train Loss: 1.828714, Val Loss: 1.368402
Epoch 80/200 - Train Loss: 1.957194, Val Loss: 1.437947
Epoch 81/200 - Train Loss: 1.788300, Val Loss: 1.348792
Epoch 82/200 - Train Loss: 1.785813, Val Loss: 1.368588
Epoch 83/200 - Train Loss: 1.914566, Val Loss: 1.381410
Epoch 84/200 - Train Loss: 1.892039, Val Loss: 1.424562
Epoch 85/200 - Train Loss: 1.845664, Val Loss: 1.303695
Epoch 86/200 - Train Loss: 1.790940, Val Loss: 1.210025
Epoch 87/200 - Train Loss: 1.806704, Val Loss: 1.360214
Epoch 88/200 - Train Loss: 1.871717, Val Loss: 1.265136
Epoch 89/200 - Train Loss: 1.755122, Val Loss: 1.199062
Epoch 90/200 - Train Loss: 1.781598, Val Loss: 1.292826
Epoch 91/200 - Train Loss: 1.800895, Val Loss: 1.234963
Epoch 92/200 - Train Loss: 1.800078, Val Loss: 1.269676
Epoch 93/200 - Train Loss: 1.714110, Val Loss: 1.262699
Epoch 94/200 - Train Loss: 1.800094, Val Loss: 1.373234
Epoch 95/200 - Train Loss: 1.805033, Val Loss: 1.267386
Epoch 96/200 - Train Loss: 1.653105, Val Loss: 1.251065
Epoch 97/200 - Train Loss: 1.686938, Val Loss: 1.340806
Epoch 98/200 - Train Loss: 1.675680, Val Loss: 1.248473
Epoch 99/200 - Train Loss: 1.694009, Val Loss: 1.326006
Epoch 100/200 - Train Loss: 1.783729, Val Loss: 1.238426
Epoch 101/200 - Train Loss: 1.677991, Val Loss: 1.230886
Epoch 102/200 - Train Loss: 1.698673, Val Loss: 1.246013
Epoch 103/200 - Train Loss: 1.705444, Val Loss: 1.300258
Epoch 104/200 - Train Loss: 1.673392, Val Loss: 1.260855
Epoch 105/200 - Train Loss: 1.712249, Val Loss: 1.249899
Epoch 106/200 - Train Loss: 1.672329, Val Loss: 1.302757
Epoch 107/200 - Train Loss: 1.679130, Val Loss: 1.294714
Epoch 108/200 - Train Loss: 1.622433, Val Loss: 1.263745
   DeepRegressionKriging(hidden_layers=[128, 64, 32], variogram_model='spherical')
  fitted_params_: {'hidden_layers': [128, 64, 32], 'dropout': 0.2, 'learning_rate': 0.001, 'weight_decay': 0.0, 'batch_size': 64}

=== Fitting DeepRegressionKriging 'tuned' ===
[I 2026-09-08 23:51:30,945] Trial 0 finished with value: 1.563685893361974 and parameters: {'n_layers': 2, 'n_units_l0': 32, 'n_units_l1': 128, 'dropout': 0.2832290311184182, 'learning_rate': 0.00010994335574766199, 'weight_decay': 0.0008123245085588687, 'batch_size': 32}. Best is trial 0 with value: 1.563685893361974.

[I 2026-09-08 23:51:41,684] Trial 1 finished with value: 1.666670514879397 and parameters: {'n_layers': 1, 'n_units_l0': 64, 'dropout': 0.2447411578889518, 'learning_rate': 0.00019010245319870352, 'weight_decay': 7.523742884534855e-06, 'batch_size': 128}. Best is trial 0 with value: 1.563685893361974.

[I 2026-09-08 23:52:06,934] Trial 2 finished with value: 1.4267523407844243 and parameters: {'n_layers': 1, 'n_units_l0': 256, 'dropout': 0.06820964947491662, 'learning_rate': 0.00013492834268013249, 'weight_decay': 0.0007025166339242157, 'batch_size': 32}. Best is trial 2 with value: 1.4267523407844243.

[I 2026-09-08 23:52:19,425] Trial 3 finished with value: 1.2671642388048001 and parameters: {'n_layers': 1, 'n_units_l0': 32, 'dropout': 0.013755408446087358, 'learning_rate': 0.006586289317583112, 'weight_decay': 5.975027999960295e-06, 'batch_size': 32}. Best is trial 3 with value: 1.2671642388048001.

[I 2026-09-08 23:52:31,785] Trial 4 finished with value: 1.488105994970392 and parameters: {'n_layers': 2, 'n_units_l0': 64, 'n_units_l1': 128, 'dropout': 0.07839314496765809, 'learning_rate': 0.00012315571723666037, 'weight_decay': 9.462175356461487e-06, 'batch_size': 128}. Best is trial 3 with value: 1.2671642388048001.

[I 2026-09-08 23:52:40,180] Trial 5 finished with value: 1.2068092845974299 and parameters: {'n_layers': 2, 'n_units_l0': 256, 'n_units_l1': 64, 'dropout': 0.00220884684944096, 'learning_rate': 0.004274869455295219, 'weight_decay': 0.00013199942261535007, 'batch_size': 64}. Best is trial 5 with value: 1.2068092845974299.

[I 2026-09-08 23:52:49,509] Trial 6 finished with value: 1.2696292967487952 and parameters: {'n_layers': 2, 'n_units_l0': 64, 'n_units_l1': 256, 'dropout': 0.25502298854208527, 'learning_rate': 0.0059487468132197715, 'weight_decay': 2.6100256506134754e-05, 'batch_size': 128}. Best is trial 5 with value: 1.2068092845974299.

[I 2026-09-08 23:53:02,002] Trial 7 finished with value: 1.2860638539183047 and parameters: {'n_layers': 2, 'n_units_l0': 32, 'n_units_l1': 256, 'dropout': 0.12574239243053068, 'learning_rate': 0.0010402587615883842, 'weight_decay': 0.0005280796376895364, 'batch_size': 128}. Best is trial 5 with value: 1.2068092845974299.

[I 2026-09-08 23:53:12,806] Trial 8 finished with value: 1.282015826062237 and parameters: {'n_layers': 1, 'n_units_l0': 256, 'dropout': 0.3232481518257668, 'learning_rate': 0.0018484491720988621, 'weight_decay': 0.00041151130495610907, 'batch_size': 128}. Best is trial 5 with value: 1.2068092845974299.

[I 2026-09-08 23:53:24,387] Trial 9 finished with value: 1.2177763913295163 and parameters: {'n_layers': 2, 'n_units_l0': 64, 'n_units_l1': 256, 'dropout': 0.0027808522124762817, 'learning_rate': 0.001050738402418141, 'weight_decay': 1.7874463256238412e-05, 'batch_size': 128}. Best is trial 5 with value: 1.2068092845974299.

[I 2026-09-08 23:53:46,709] Trial 10 finished with value: 1.188245076739974 and parameters: {'n_layers': 3, 'n_units_l0': 256, 'n_units_l1': 64, 'n_units_l2': 256, 'dropout': 0.12470804503987869, 'learning_rate': 0.0005595774553700965, 'weight_decay': 0.000548568524786249, 'batch_size': 64}. Best is trial 10 with value: 1.188245076739974.

[I 2026-09-08 23:53:59,098] Trial 11 finished with value: 1.2145448008835422 and parameters: {'n_layers': 3, 'n_units_l0': 256, 'n_units_l1': 64, 'n_units_l2': 256, 'dropout': 0.11353200194085802, 'learning_rate': 0.0008285649741721701, 'weight_decay': 0.0005038340060002843, 'batch_size': 64}. Best is trial 10 with value: 1.188245076739974.

[I 2026-09-08 23:54:18,320] Trial 12 finished with value: 1.228074268862434 and parameters: {'n_layers': 2, 'n_units_l0': 256, 'n_units_l1': 64, 'dropout': 0.11434172337803966, 'learning_rate': 0.0005593526550677545, 'weight_decay': 3.72038870203887e-05, 'batch_size': 64}. Best is trial 10 with value: 1.188245076739974.

[I 2026-09-08 23:54:34,270] Trial 13 finished with value: 1.1896576238267749 and parameters: {'n_layers': 3, 'n_units_l0': 256, 'n_units_l1': 64, 'n_units_l2': 256, 'dropout': 0.0019739047277728683, 'learning_rate': 0.0005551854060963082, 'weight_decay': 0.00017364177524307437, 'batch_size': 64}. Best is trial 10 with value: 1.188245076739974.

[I 2026-09-08 23:54:40,374] Trial 14 pruned. 

[I 2026-09-08 23:54:44,995] Trial 15 pruned. 

[I 2026-09-08 23:54:50,701] Trial 16 pruned. 

[I 2026-09-08 23:55:02,834] Trial 17 finished with value: 1.223463382997885 and parameters: {'n_layers': 3, 'n_units_l0': 256, 'n_units_l1': 32, 'n_units_l2': 32, 'dropout': 0.07066145975109982, 'learning_rate': 0.003202885124957175, 'weight_decay': 7.447105612876198e-05, 'batch_size': 64}. Best is trial 10 with value: 1.188245076739974.

[I 2026-09-08 23:55:10,264] Trial 18 pruned. 

[I 2026-09-08 23:55:16,758] Trial 19 pruned. 

Epoch 1/200 - Train Loss: 17.214343, Val Loss: 3.947533

Epoch 2/200 - Train Loss: 3.572902, Val Loss: 2.539681

Epoch 3/200 - Train Loss: 2.897916, Val Loss: 2.206180

Epoch 4/200 - Train Loss: 2.706790, Val Loss: 2.150314

Epoch 5/200 - Train Loss: 2.501312, Val Loss: 2.019435

Epoch 6/200 - Train Loss: 2.453894, Val Loss: 2.046367

Epoch 7/200 - Train Loss: 2.299836, Val Loss: 1.975223

Epoch 8/200 - Train Loss: 2.331161, Val Loss: 1.820569

Epoch 9/200 - Train Loss: 2.184636, Val Loss: 1.799341

Epoch 10/200 - Train Loss: 2.186663, Val Loss: 1.698566

Epoch 11/200 - Train Loss: 2.115041, Val Loss: 1.948594

Epoch 12/200 - Train Loss: 2.096523, Val Loss: 1.751243

Epoch 13/200 - Train Loss: 1.965277, Val Loss: 1.640696

Epoch 14/200 - Train Loss: 1.938289, Val Loss: 1.643406

Epoch 15/200 - Train Loss: 1.918290, Val Loss: 1.549411

Epoch 16/200 - Train Loss: 1.878545, Val Loss: 1.535216

Epoch 17/200 - Train Loss: 1.824327, Val Loss: 1.633916

Epoch 18/200 - Train Loss: 1.837656, Val Loss: 1.539804

Epoch 19/200 - Train Loss: 1.767237, Val Loss: 1.556874

Epoch 20/200 - Train Loss: 1.698281, Val Loss: 1.500595

Epoch 21/200 - Train Loss: 1.736294, Val Loss: 1.731510

Epoch 22/200 - Train Loss: 1.648666, Val Loss: 1.448799

Epoch 23/200 - Train Loss: 1.681673, Val Loss: 1.446652

Epoch 24/200 - Train Loss: 1.696105, Val Loss: 1.551271

Epoch 25/200 - Train Loss: 1.553642, Val Loss: 1.539809

Epoch 26/200 - Train Loss: 1.644935, Val Loss: 1.502744

Epoch 27/200 - Train Loss: 1.555325, Val Loss: 1.410197

Epoch 28/200 - Train Loss: 1.591164, Val Loss: 1.433732

Epoch 29/200 - Train Loss: 1.513581, Val Loss: 1.448347

Epoch 30/200 - Train Loss: 1.542391, Val Loss: 1.349371

Epoch 31/200 - Train Loss: 1.431235, Val Loss: 1.431294

Epoch 32/200 - Train Loss: 1.597605, Val Loss: 1.501485

Epoch 33/200 - Train Loss: 1.506704, Val Loss: 1.385385

Epoch 34/200 - Train Loss: 1.526908, Val Loss: 1.387615

Epoch 35/200 - Train Loss: 1.526221, Val Loss: 1.411027

Epoch 36/200 - Train Loss: 1.423111, Val Loss: 1.372180

Epoch 37/200 - Train Loss: 1.432161, Val Loss: 1.370094

Epoch 38/200 - Train Loss: 1.489135, Val Loss: 1.616796

Epoch 39/200 - Train Loss: 1.520948, Val Loss: 1.459338

Epoch 40/200 - Train Loss: 1.449469, Val Loss: 1.368176

Epoch 41/200 - Train Loss: 1.517350, Val Loss: 1.352303

Epoch 42/200 - Train Loss: 1.439666, Val Loss: 1.355152

Epoch 43/200 - Train Loss: 1.431381, Val Loss: 1.477804

Epoch 44/200 - Train Loss: 1.408912, Val Loss: 1.336407

Epoch 45/200 - Train Loss: 1.388649, Val Loss: 1.388777

Epoch 46/200 - Train Loss: 1.378459, Val Loss: 1.322179

Epoch 47/200 - Train Loss: 1.333722, Val Loss: 1.355345

Epoch 48/200 - Train Loss: 1.422593, Val Loss: 1.357484

Epoch 49/200 - Train Loss: 1.344804, Val Loss: 1.395122

Epoch 50/200 - Train Loss: 1.362878, Val Loss: 1.418857

Epoch 51/200 - Train Loss: 1.359975, Val Loss: 1.296583

Epoch 52/200 - Train Loss: 1.353419, Val Loss: 1.332554

Epoch 53/200 - Train Loss: 1.337205, Val Loss: 1.319139

Epoch 54/200 - Train Loss: 1.365556, Val Loss: 1.440086

Epoch 55/200 - Train Loss: 1.396028, Val Loss: 1.272787

Epoch 56/200 - Train Loss: 1.355294, Val Loss: 1.331402

Epoch 57/200 - Train Loss: 1.274733, Val Loss: 1.329762

Epoch 58/200 - Train Loss: 1.307321, Val Loss: 1.372375

Epoch 59/200 - Train Loss: 1.329471, Val Loss: 1.310260

Epoch 60/200 - Train Loss: 1.323871, Val Loss: 1.270170

Epoch 61/200 - Train Loss: 1.341732, Val Loss: 1.354465

Epoch 62/200 - Train Loss: 1.263938, Val Loss: 1.314857

Epoch 63/200 - Train Loss: 1.345463, Val Loss: 1.329608

Epoch 64/200 - Train Loss: 1.310977, Val Loss: 1.379726

Epoch 65/200 - Train Loss: 1.278877, Val Loss: 1.283932

Epoch 66/200 - Train Loss: 1.259071, Val Loss: 1.318627

Epoch 67/200 - Train Loss: 1.261640, Val Loss: 1.294130

Epoch 68/200 - Train Loss: 1.287331, Val Loss: 1.279822

Epoch 69/200 - Train Loss: 1.245148, Val Loss: 1.292472

Epoch 70/200 - Train Loss: 1.210872, Val Loss: 1.282172

Epoch 71/200 - Train Loss: 1.164454, Val Loss: 1.249649

Epoch 72/200 - Train Loss: 1.210279, Val Loss: 1.261684

Epoch 73/200 - Train Loss: 1.264629, Val Loss: 1.273504

Epoch 74/200 - Train Loss: 1.223240, Val Loss: 1.283000

Epoch 75/200 - Train Loss: 1.297629, Val Loss: 1.264452

Epoch 76/200 - Train Loss: 1.206288, Val Loss: 1.264424

Epoch 77/200 - Train Loss: 1.287625, Val Loss: 1.241750

Epoch 78/200 - Train Loss: 1.232052, Val Loss: 1.310454

Epoch 79/200 - Train Loss: 1.155505, Val Loss: 1.263604

Epoch 80/200 - Train Loss: 1.173810, Val Loss: 1.231114

Epoch 81/200 - Train Loss: 1.191039, Val Loss: 1.256284

Epoch 82/200 - Train Loss: 1.229061, Val Loss: 1.220103

Epoch 83/200 - Train Loss: 1.145115, Val Loss: 1.230979

Epoch 84/200 - Train Loss: 1.128639, Val Loss: 1.261963

Epoch 85/200 - Train Loss: 1.160595, Val Loss: 1.355744

Epoch 86/200 - Train Loss: 1.192386, Val Loss: 1.227819

Epoch 87/200 - Train Loss: 1.152877, Val Loss: 1.235206

Epoch 88/200 - Train Loss: 1.127469, Val Loss: 1.260014

Epoch 89/200 - Train Loss: 1.188197, Val Loss: 1.271308

Epoch 90/200 - Train Loss: 1.249895, Val Loss: 1.329360

Epoch 91/200 - Train Loss: 1.156238, Val Loss: 1.203742

Epoch 92/200 - Train Loss: 1.255443, Val Loss: 1.206614

Epoch 93/200 - Train Loss: 1.157879, Val Loss: 1.220291

Epoch 94/200 - Train Loss: 1.108349, Val Loss: 1.229111

Epoch 95/200 - Train Loss: 1.172485, Val Loss: 1.355647

Epoch 96/200 - Train Loss: 1.186158, Val Loss: 1.210060

Epoch 97/200 - Train Loss: 1.074067, Val Loss: 1.260903

Epoch 98/200 - Train Loss: 1.168207, Val Loss: 1.319112

Epoch 99/200 - Train Loss: 1.177457, Val Loss: 1.277740

Epoch 100/200 - Train Loss: 1.098039, Val Loss: 1.205376

Epoch 101/200 - Train Loss: 1.068116, Val Loss: 1.231183

Epoch 102/200 - Train Loss: 1.081952, Val Loss: 1.257822

Epoch 103/200 - Train Loss: 1.147944, Val Loss: 1.185739

Epoch 104/200 - Train Loss: 1.118028, Val Loss: 1.225588

Epoch 105/200 - Train Loss: 1.074386, Val Loss: 1.257585

Epoch 106/200 - Train Loss: 1.157910, Val Loss: 1.260639

Epoch 107/200 - Train Loss: 1.113002, Val Loss: 1.318113

Epoch 108/200 - Train Loss: 1.079845, Val Loss: 1.253923

Epoch 109/200 - Train Loss: 1.113554, Val Loss: 1.187609

Epoch 110/200 - Train Loss: 1.071244, Val Loss: 1.242691

Epoch 111/200 - Train Loss: 1.054166, Val Loss: 1.236047

Epoch 112/200 - Train Loss: 1.095503, Val Loss: 1.197766

Epoch 113/200 - Train Loss: 1.080940, Val Loss: 1.196516

Epoch 114/200 - Train Loss: 1.105790, Val Loss: 1.216153

Epoch 115/200 - Train Loss: 1.046861, Val Loss: 1.205350

Epoch 116/200 - Train Loss: 1.062082, Val Loss: 1.325877

Epoch 117/200 - Train Loss: 1.086062, Val Loss: 1.171789

Epoch 118/200 - Train Loss: 1.034529, Val Loss: 1.316935

Epoch 119/200 - Train Loss: 1.034886, Val Loss: 1.244946

Epoch 120/200 - Train Loss: 1.056420, Val Loss: 1.220971

Epoch 121/200 - Train Loss: 1.034880, Val Loss: 1.202415

Epoch 122/200 - Train Loss: 1.014771, Val Loss: 1.183322

Epoch 123/200 - Train Loss: 1.048997, Val Loss: 1.174188

Epoch 124/200 - Train Loss: 1.041153, Val Loss: 1.278081

Epoch 125/200 - Train Loss: 1.044841, Val Loss: 1.233002

Epoch 126/200 - Train Loss: 1.081427, Val Loss: 1.201797

Epoch 127/200 - Train Loss: 1.045481, Val Loss: 1.215790

Epoch 128/200 - Train Loss: 1.033386, Val Loss: 1.216657

Epoch 129/200 - Train Loss: 1.047145, Val Loss: 1.174844

Epoch 130/200 - Train Loss: 1.056731, Val Loss: 1.201105

Epoch 131/200 - Train Loss: 1.093664, Val Loss: 1.184809

Epoch 132/200 - Train Loss: 1.025960, Val Loss: 1.174341

Epoch 133/200 - Train Loss: 1.045354, Val Loss: 1.197468

Epoch 134/200 - Train Loss: 1.000714, Val Loss: 1.198164

Epoch 135/200 - Train Loss: 1.022391, Val Loss: 1.179917

Epoch 136/200 - Train Loss: 1.011394, Val Loss: 1.406487

   DeepRegressionKriging(hidden_layers=[256, 64, 256], variogram_model='spherical', tuned (best RMSE=1.188))

  fitted_params_: {'hidden_layers': [256, 64, 256], 'dropout': 0.12470804503987869, 'learning_rate': 0.0005595774553700965, 'weight_decay': 0.000548568524786249, 'batch_size': 64}

  Optuna CV RMSE: 1.1882
number value datetime_start datetime_complete duration params_batch_size params_dropout params_learning_rate params_n_layers params_n_units_l0 params_n_units_l1 params_n_units_l2 params_weight_decay user_attrs_resolved_params system_attrs_tpe:relative_params:0 state
10 10 1.188 2026-09-08 23:53:24.390363 2026-09-08 23:53:46.709083 0 days 00:00:22.318720 64 0.125 0.001 3 256 64.000 256.000 0.001 {'hidden_layers': [256, 64, 256], 'dropout': 0... {"batch_size": 64, "dropout": 0.12470804503987... COMPLETE
13 13 1.190 2026-09-08 23:54:18.321949 2026-09-08 23:54:34.270601 0 days 00:00:15.948652 64 0.002 0.001 3 256 64.000 256.000 0.000 {'hidden_layers': [256, 64, 256], 'dropout': 0... {"batch_size": 64, "dropout": 0.00197390472777... COMPLETE
5 5 1.207 2026-09-08 23:52:31.787466 2026-09-08 23:52:40.180612 0 days 00:00:08.393146 64 0.002 0.004 2 256 64.000 NaN 0.000 {'hidden_layers': [256, 64], 'dropout': 0.0022... NaN COMPLETE
11 11 1.215 2026-09-08 23:53:46.712259 2026-09-08 23:53:59.098467 0 days 00:00:12.386208 64 0.114 0.001 3 256 64.000 256.000 0.001 {'hidden_layers': [256, 64, 256], 'dropout': 0... {"batch_size": 64, "dropout": 0.11353200194085... COMPLETE
9 9 1.218 2026-09-08 23:53:12.808264 2026-09-08 23:53:24.387679 0 days 00:00:11.579415 128 0.003 0.001 2 64 256.000 NaN 0.000 {'hidden_layers': [64, 256], 'dropout': 0.0027... NaN COMPLETE
17 17 1.223 2026-09-08 23:54:50.703575 2026-09-08 23:55:02.834183 0 days 00:00:12.130608 64 0.071 0.003 3 256 32.000 32.000 0.000 {'hidden_layers': [256, 32, 32], 'dropout': 0.... {"batch_size": 64, "dropout": 0.07066145975109... COMPLETE
12 12 1.228 2026-09-08 23:53:59.100426 2026-09-08 23:54:18.320031 0 days 00:00:19.219605 64 0.114 0.001 2 256 64.000 NaN 0.000 {'hidden_layers': [256, 64], 'dropout': 0.1143... {"batch_size": 64, "dropout": 0.11434172337803... COMPLETE
3 3 1.267 2026-09-08 23:52:06.936348 2026-09-08 23:52:19.425358 0 days 00:00:12.489010 32 0.014 0.007 1 32 NaN NaN 0.000 {'hidden_layers': [32], 'dropout': 0.013755408... NaN COMPLETE

Fitted families: ['default', 'tuned']

Training curves for each fitted MLP, and Optuna’s optimization history for the tuned model.

Code
n = len(fitted)
fig, axes = plt.subplots(1, max(n, 1), figsize=(6.2 * max(n, 1), 4.5), sharey=True)
if n <= 1:
    axes = [axes]
for ax, (name, rk) in zip(np.atleast_1d(axes).ravel(), fitted.items()):
    ax.plot(rk.train_losses_, label="Training")
    if rk.val_losses_ is not None:
        ax.plot(rk.val_losses_, label="Validation")
    ax.set_xlabel("Epoch")
    ax.set_ylabel("MSE loss")
    ax.set_title(f"Loss — {name}")
    ax.legend()
    ax.grid(alpha=0.3)
plt.tight_layout()
plt.show()

if "tuned" in fitted:
    fitted["tuned"].plot_optuna_history()


9. Hold-Out Comparison on the Test Set

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
Best family on the test set: tuned
family hidden_layers dropout learning_rate batch_size test_rmse test_mae test_r2
0 tuned [256, 64, 256] 0.125 0.001 64 0.982 0.676 0.932
1 default [128, 64, 32] 0.200 0.001 64 0.997 0.687 0.930
Code
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
order = results.sort_values("test_rmse")
axes[0].barh(order["family"], order["test_rmse"], color="C0", alpha=0.85)
axes[0].set_xlabel("Test RMSE (SOC %)")
axes[0].set_title("Hold-out RMSE by MLP family")
axes[0].invert_yaxis()

axes[1].barh(order["family"], order["test_r2"], color="C1", alpha=0.85)
axes[1].set_xlabel("$R^2$")
axes[1].set_title("Hold-out $R^2$ by MLP family")
axes[1].invert_yaxis()
plt.tight_layout()
plt.show()

Observed vs predicted on the test set

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 not in 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))
if len(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 in zip(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]
if len(pair) < 2:
    pair = list(fitted.keys())[:2]

fig, axes = plt.subplots(1, 2, figsize=(12, 5), sharey=True)
for ax, name in zip(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 in enumerate(feature_names):
        deltas = []
        for _ in range(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 not in 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))
if len(imp_names) <= 1:
    axes = [axes]
for ax, name in zip(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_best
grid_df["SOC_best_se"] = se_best

# Regression-only trend = RK prediction minus kriged residual
grid_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.995        0.513     6.209      -0.213
std     327749.190  382369.477     3.604        0.322     3.541       0.505
min   -1245285.000 1003795.000     0.389        0.000     1.887      -7.590
25%   -1005285.000 1503795.000     3.282        0.000     3.529      -0.416
50%    -825285.000 1743795.000     5.083        0.695     5.319      -0.216
75%    -625285.000 2023795.000     7.919        0.722     8.133      -0.032
max     114715.000 2533795.000    23.482        0.764    22.408       4.688
Code
out_path = DATA_DIR / "gp_prediction_RK_pytorch.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_pytorch.csv

12. Map Predictions

Points are plotted in EPSG:5070 with Great Plains state boundaries (data/GP_STATE.shp).

Code
states = gpd.read_file(DATA_DIR / "GP_STATE.shp")
gdf_pred = gpd.GeoDataFrame(
    grid_df,
    geometry=gpd.points_from_xy(grid_df.x, grid_df.y),
    crs="EPSG:5070",
)
states = states.to_crs(gdf_pred.crs)


def map_points(ax, column, cmap, title, vmin=None, vmax=None):
    gdf_pred.plot(
        column=column, ax=ax, legend=True, cmap=cmap,
        markersize=4, vmin=vmin, vmax=vmax,
        legend_kwds={"shrink": 0.7},
    )
    states.boundary.plot(ax=ax, color="black", linewidth=0.4)
    ax.set_title(title)
    ax.set_axis_off()
Code
vmin = np.nanpercentile(grid_df["SOC_best"], 2)
vmax = np.nanpercentile(grid_df["SOC_best"], 98)

fig, axes = plt.subplots(1, 3, figsize=(18, 5.5))
map_points(axes[0], "SOC_best", "YlGn", f"RK prediction ({best_name})", vmin, vmax)
map_points(axes[1], "reg_best", "YlGn", "MLP regression trend only", vmin, vmax)
map_points(axes[2], "resid_best", "coolwarm", "Kriged residuals",
           vmin=-5, vmax=5)
plt.tight_layout()
plt.show()

Code
fig, axes = plt.subplots(1, 2, figsize=(12, 5.5))
map_points(axes[0], "SOC_best", "YlGn", f"Best RK SOC ({best_name})", vmin, vmax)
map_points(axes[1], "SOC_best_se", "magma", "Kriging standard error")
plt.tight_layout()
plt.show()

Code
# Side-by-side grid predictions for every MLP family
model_names = list(fitted)
n = len(model_names)
ncols = min(2, n)
nrows = int(np.ceil(n / ncols))
fig, axes = plt.subplots(nrows, ncols, figsize=(6 * ncols, 5 * nrows))
axes = np.atleast_1d(axes).ravel()
for ax, name in zip(axes, model_names):
    map_points(ax, f"SOC_{name}", "YlGn", f"RK — {name}", vmin, vmax)
for ax in axes[n:]:
    ax.axis("off")
plt.tight_layout()
plt.show()


13. CPU vs GPU RK Timing

Section 3.1 showed how to select a backend. Here we measure how long residual ordinary kriging — the spatial step inside DeepRegressionKriging — 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 PyTorch MLP trend uses device=DEVICE 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 time
from sklearn.linear_model import LinearRegression

from pygstat import OrdinaryKriging

N_REPEATS = 3
N_PRED_GP = 500
GP_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(), resid


def _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 = None
    for _ in range(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)
    return float(np.median(times)), last


print(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) else f"{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() * 1000
gpu_ms = df_bench["GPU (s)"].to_numpy() * 1000
labels = [str(int(n)) for n in n_vals]

x = np.arange(len(n_vals))
w = 0.36
axes[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 (PyTorch 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      57.4       9.8   5.88×   True
GP (SOC)     1000     500     141.2      24.1   5.86×   True
GP (SOC)     2000     500     360.7      67.5   5.34×   True
GP (SOC)     4000     500    1283.8     205.2   6.26×   True
GP (SOC)     5000     500    2090.7     346.3   6.04×   True

Predictions and residual-kriging standard errors from the two backends should match (match = True). The 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 PyTorch MLP trend (pygstat.DeepRegressionKriging).

  • 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_pytorch.csv.
  • CPU / GPU. Residual ordinary kriging (use_gpu=USE_GPU) was timed on prefixes of gp_data_5000.csv. The MLP uses device=DEVICE; the \(O(n^2)\) covariance and \(O(n^3)\) OK solve are the CuPy-accelerated steps.

Regression kriging with a PyTorch MLP is a practical workflow when you want nonlinear capacity, GPU training, Optuna architecture search, and geostatistical residuals on the same spatial support.


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

In this library

Object Role
pygstat.DeepRegressionKriging PyTorch MLP trend + ordinary kriging of residuals (device, use_gpu)
tune_hyperparameters=True Optuna search over hidden layers, dropout, learning rate, weight decay, batch size
param_space Custom trial -> dict search space (defaults to _default_param_space)
fit(..., X_val=, y_val=) Validation tensors 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[pytorch,optuna]. Set device='cuda' to force a GPU, or leave device='auto' (used here) to fall back to CPU when CUDA is unavailable.

Back to top