Tuner API reference#

The GeoPrior-v3 tuning stack provides the hyperparameter-search interface used to adapt GeoPriorSubsNet to a concrete training setup. It is not just a thin wrapper around keras-tuner. The tuning layer separates architecture hyperparameters from compile-only hyperparameters, validates the scientific input contract expected by the subsidence model, and persists search artifacts in a predictable project layout.

This page documents the tuner stack at two complementary levels:

  • the public package surface that application workflows use;

  • the implementation modules that explain how the tuning system is organized internally.

The page also uses fully qualified module names throughout so that Sphinx autosummary resolves modules directly, without relying on package attribute lookup.

Overview#

The tuning code is split across a small public package and a lightweight compatibility shim:

geoprior.models
├── tuners.py                       # public compatibility shim
└── forecast_tuner/
    ├── __init__.py                 # public package surface
    ├── _base_tuner.py             # reusable tuner base class
    └── _geoprior_tuner.py         # GeoPrior-specific specialization

A useful mental model is the following:

This structure is reflected in the code you uploaded: the forecast_tuner package exports both SubsNetTuner and PINNTunerBase from its __init__.py, while the top-level geoprior.models.tuners module simply re-exports SubsNetTuner as a compatibility surface.

Module index#

The targets below are intentionally written as fully qualified module names. This avoids the package-relative lookup behavior that often causes autosummary to build malformed paths.

forecast_tuner

A subpackage for hyperparameter tuning of geoprior models using Keras Tuner.

tuners

Model tuner exports and convenience helpers.

_base_tuner

Base classes and utilities for hyperparameter tuning of PINN models.

_geoprior_tuner

Tuner for GeoPriorSubsNet.

Public package surface#

The main public package is geoprior.models.forecast_tuner. Its __init__.py exposes the tuning-availability flags together with the public tuner classes, including SubsNetTuner and PINNTunerBase.

A subpackage for hyperparameter tuning of geoprior models using Keras Tuner.

class geoprior.models.forecast_tuner.SubsNetTuner(fixed_params, search_space=None, objective='val_loss', max_trials=10, project_name='SubsNetrTuner_Project', directory='subsnet_tuner_results', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite=True, _logger=None, **kwargs)[source]

Bases: PINNTunerBase

Specialized tuner for GeoPriorSubsNet models.

This class provides a flexible hyperparameter tuner for the physics-informed GeoPriorSubsNet. It builds on PINNTunerBase and uses keras-tuner backends to search architectural, physics, and compile-time spaces. Fixed, data-dependent parameters are separated from the search space, and GeoPrior input checks are enforced during run and create.

The recommended entry point is SubsNetTuner.create, which infers data dimensions from NumPy arrays, merges them with robust defaults, and applies user overrides.

Parameters:
  • fixed_params (dict) – Non-tunable configuration passed to the model __init__. Typical keys include static_input_dim, dynamic_input_dim, future_input_dim, output_subsidence_dim, output_gwl_dim, forecast_horizon, and stable flags such as use_batch_norm or pde_mode.

  • search_space (dict, optional) – Hyperparameter definitions. Each entry is either a list of discrete choices or a typed range dictionary such as {"dropout_rate": {"type": "float", "min_value": 0.1, "max_value": 0.4}}. Supported types are int, float, choice, and bool. Items are routed to model __init__ or to compile as noted below.

  • objective (str or keras_tuner.Objective, default "val_loss") – Metric to optimize. If the string contains “loss”, direction is inferred as “min”.

  • max_trials (int, default 10) – Maximum number of trials evaluated by the tuner.

  • project_name (str, default "SubsNetrTuner_Project") – Project name used for directory layout.

  • directory (str, default "subsnet_tuner_results") – Root directory where tuner artifacts are saved.

  • executions_per_trial (int, default 1) – Number of repeated trainings per hyperparameter set.

  • tuner_type ({'randomsearch', 'bayesianoptimization', 'hyperband'}, default 'randomsearch') – Search algorithm used by keras-tuner.

  • seed (int, optional) – Random seed for reproducibility.

  • overwrite (bool, default True) – If True, existing project results are overwritten.

  • _logger (logging.Logger or callable, optional) – Logger or print-like callable for progress lines.

  • kwargs (dict) – Forwarded to PINNTunerBase for advanced control.

Variables:
  • model_class (Type[tf.keras.Model]) – Bound to GeoPriorSubsNet.

  • fixed_params (dict) – Finalized, non-tunable model configuration.

  • search_space (dict) – User-provided hyperparameter search definitions.

  • best_hps (keras_tuner.HyperParameters or None) – Best hyperparameters found by the search.

  • best_model (tf.keras.Model or None) – Model built with the best hyperparameters.

  • tuner (keras_tuner.Tuner or None) – Underlying tuner instance after run or search.

  • tuning_summary (dict) – Compact summary saved under the project directory.

Notes

Required inputs. GeoPriorSubsNet expects coords for spatiotemporal coordinates, dynamic_features for time-varying covariates, and H_field for the soil-thickness field.

The helper canonicalizes H_field from common aliases, e.g., soil_thickness, soil thickness, h_field.

Target canonicalization. Targets are canonicalized to subs_pred and gwl_pred from subsidence and gwl. This is handled internally before data pipelines are built.

Compile-only hyperparameters. These search keys are not passed to __init__ and are routed to compile:

  • learning_rate

  • lambda_gw, lambda_cons, lambda_prior, lambda_smooth, lambda_mv

  • mv_lr_mult, kappa_lr_mult

Losses and metrics. By default the supervised heads use mean squared error with mean absolute error metrics. If fixed_params["quantiles"] is set, a pinball loss can be injected via a user loss factory at compile time.

Physics objectives. GeoPrior adds residuals consistent with consolidation and groundwater flow:

  • \(R_gw = Ss * d(h)/dt - div(K * grad(h)) - Q\)

  • \(R_cons = d(s)/dt - (s_eq - s) / tau\)

with \(s_eq = m_v * gamma_w * (h_ref - h) * H\). Weights are controlled by the compile-time lambdas.

Typical search groups.

  • Architecture: embed_dim, hidden_units, lstm_units, attention_units, num_heads, dropout_rate, vsn_units, use_vsn, use_batch_norm

  • Physics: pde_mode, mv, kappa, use_effective_h, hd_factor, kappa_mode, scale_pde_residuals

  • Optimization: learning_rate and lambda weights

Workflow. run builds tf.data pipelines from NumPy inputs, applies key canonicalization, validates GeoPrior requirements, and delegates to search. The best HPs and a built model are returned and stored on the class. The tuning workflow combines Keras Tuner search patterns with the poromechanics background from [21, 22, 23].

Examples

Create from arrays and tune a small space.

>>> from geoprior.models.forecast_tuner import SubsNetTuner
>>> fixed = {"forecast_horizon": 7}
>>> space = {
...   "embed_dim": [32, 64],
...   "num_heads": [2, 4],
...   "dropout_rate": {"type": "float",
...     "min_value": 0.1, "max_value": 0.3},
...   "learning_rate": [1e-3, 5e-4],
...   "lambda_gw": {"type": "float",
...     "min_value": 0.5, "max_value": 1.5},
... }
>>> tuner = SubsNetTuner.create(
...   inputs_data=inputs_np,
...   targets_data=targets_np,
...   search_space=space,
...   fixed_params=fixed,
...   max_trials=20,
...   project_name="GeoPrior_HP_Search",
... )
>>> best_model, best_hps, kt = tuner.run(
...   inputs=inputs_np,
...   y=targets_np,
...   validation_data=(val_inputs_np, val_targets_np),
...   epochs=30,
...   batch_size=32,
... )

See also

PINNTunerBase

Base hypermodel with the generic search routine.

GeoPriorSubsNet

Target model with physics residuals and priors.

HydroTuner

Generic PINN tuner for HAL and TransFlow models.

__init__(fixed_params, search_space=None, objective='val_loss', max_trials=10, project_name='SubsNetrTuner_Project', directory='subsnet_tuner_results', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite=True, _logger=None, **kwargs)[source]

Initialize the base class.

Parameters:
  • verbose (int, optional) – Verbosity level controlling logging (0 to 3). Defaults to 0.

  • fixed_params (dict[str, Any])

  • search_space (dict[str, Any] | None)

  • objective (str | Objective)

  • max_trials (int)

  • project_name (str)

  • directory (str)

  • executions_per_trial (int)

  • tuner_type (str)

  • seed (int | None)

  • overwrite (bool)

  • _logger (Callable[[str], None] | Logger | None)

classmethod create(inputs_data, targets_data, search_space, fixed_params=None, **tuner_kwargs)[source]
Parameters:
Return type:

SubsNetTuner

build(hp)[source]

Builds and compiles the Keras model with hyperparameters.

This method must be overridden by subclasses (e.g., PIHALTuner) to define the specific model architecture (like PIHALNet), sample hyperparameters using the hp object based on self.param_space, and compile the model.

Args:

hp (kt.HyperParameters): Keras Tuner HyperParameters object.

Returns:

tf.keras.Model: The compiled Keras model.

Parameters:

hp (HyperParameters)

Return type:

Model

run(inputs, y, validation_data=None, epochs=10, batch_size=32, callbacks=None, case_info=None, verbose=1, **search_kwargs)[source]
Parameters:
Return type:

tuple[Model | None, HyperParameters | None, Tuner | None]

help(**kwargs)
my_params = SubsNetTuner(     fixed_params,     search_space=None,     objective='val_loss',     max_trials=10,     project_name='SubsNetrTuner_Project',     directory='subsnet_tuner_results',     executions_per_trial=1,     tuner_type='randomsearch',     seed=None,     overwrite=True,     _logger=None )
geoprior.models.forecast_tuner.check_keras_tuner_is_available(error='warn')[source]

Checks if the ‘keras-tuner’ package is installed.

This helper function is used to determine if the optional tuning dependencies are present in the user’s environment.

Parameters:

error ({'raise', 'warn', 'ignore'}, default 'warn') – Policy for handling the case where ‘keras-tuner’ is not found. - ‘raise’: Raises an ImportError. - ‘warn’: Issues an ImportWarning. - ‘ignore’: Does nothing.

Returns:

True if ‘keras-tuner’ is installed, False otherwise.

Return type:

bool

class geoprior.models.forecast_tuner.PINNTunerBase(objective='val_loss', max_trials=10, project_name='PINN_Tuning', directory='pinn_tuner_results', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite_tuner=True, _logger=None, **tuner_kwargs)[source]

Bases: HyperModel, BaseClass

Base class for hyperparameter tuning of physics-informed models.

This class wraps keras-tuner orchestration for GeoPrior PINN-style models. Subclasses are expected to implement build(hp).

Parameters:
  • objective (str or keras_tuner.Objective, default "val_loss") – Metric to optimize during the search.

  • max_trials (int, default 10) – Maximum number of hyperparameter trials to evaluate.

  • project_name (str, default "PINN_Tuning") – Project name used for tuner artifacts.

  • directory (str, default "pinn_tuner_results") – Root directory for tuner outputs.

  • executions_per_trial (int, default 1) – Number of repeated trainings per sampled hyperparameter set.

  • tuner_type ({"randomsearch", "bayesianoptimization", "hyperband"}, default "randomsearch") – Search backend used by keras-tuner.

  • seed (int or None, default None) – Random seed used for reproducibility.

  • overwrite_tuner (bool, default True) – Whether to overwrite an existing tuner project directory.

  • tuner_kwargs (dict) – Additional keyword arguments forwarded to the underlying tuner backend.

  • _logger (Logger | Callable[[str], None] | None)

Variables:
  • best_hps (keras_tuner.HyperParameters or None) – Best hyperparameters discovered during tuning.

  • best_model (tf.keras.Model or None) – Best compiled model recovered from the tuner.

  • tuner (keras_tuner.Tuner or None) – Underlying tuner instance.

  • tuning_summary (dict) – Compact summary of the completed tuning run.

__init__(objective='val_loss', max_trials=10, project_name='PINN_Tuning', directory='pinn_tuner_results', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite_tuner=True, _logger=None, **tuner_kwargs)[source]

Initialize the base class.

Parameters:
  • verbose (int, optional) – Verbosity level controlling logging (0 to 3). Defaults to 0.

  • objective (str | Objective)

  • max_trials (int)

  • project_name (str)

  • directory (str)

  • executions_per_trial (int)

  • tuner_type (str)

  • seed (int | None)

  • overwrite_tuner (bool)

  • _logger (Logger | Callable[[str], None] | None)

best_hps_: HyperParameters | None
best_model_: Model | None
tuner_: Tuner | None
tuning_summary_: dict[str, Any]
fixed_model_params: dict[str, Any]
param_space_config: dict[str, Any]
build(hp)[source]

Builds and compiles the Keras model with hyperparameters.

This method must be overridden by subclasses (e.g., PIHALTuner) to define the specific model architecture (like PIHALNet), sample hyperparameters using the hp object based on self.param_space, and compile the model.

Args:

hp (kt.HyperParameters): Keras Tuner HyperParameters object.

Returns:

tf.keras.Model: The compiled Keras model.

Parameters:

hp (HyperParameters)

Return type:

Model

search(train_data, epochs, validation_data=None, callbacks=None, verbose=1, patience=10, **additional_search_kwargs)[source]

Performs the hyperparameter search using Keras Tuner.

Parameters:
  • train_data (tf.data.Dataset) – Training dataset. Must yield tuples of (inputs_dict, targets_dict) compatible with the model’s train_step.

  • epochs (int) – Number of epochs to train each model during a trial.

  • validation_data (tf.data.Dataset or None, default None) – Validation dataset.

  • callbacks (list of tf.keras.callbacks.Callback or None, default None) – Keras callbacks for the search phase.

  • verbose (int, default 1) – Verbosity level for Keras Tuner search.

  • patience (int, default 10) – Early-stopping patience.

  • **additional_search_kwargs – Additional keyword arguments passed to the tuner search() method.

Returns:

  • best_model (tf.keras.Model or None) – Best model instance built with the best hyperparameters.

  • best_hps (keras_tuner.HyperParameters or None) – Best hyperparameters found.

  • tuner (keras_tuner.Tuner or None) – Tuner instance used for the search.

Return type:

tuple[Model | None, HyperParameters | None, Tuner | None]

help(**kwargs)
my_params = PINNTunerBase(     objective='val_loss',     max_trials=10,     project_name='PINN_Tuning',     directory='pinn_tuner_results',     executions_per_trial=1,     tuner_type='randomsearch',     seed=None,     overwrite_tuner=True,     _logger=None )

Compatibility shim#

The top-level module geoprior.models.tuners exists as a compact compatibility layer. Rather than implementing the tuning logic itself, it simply re-exports SubsNetTuner from the public models namespace. This is useful when existing code or older imports expect a shorter path under geoprior.models.

Model tuner exports and convenience helpers.

class geoprior.models.tuners.SubsNetTuner(fixed_params, search_space=None, objective='val_loss', max_trials=10, project_name='SubsNetrTuner_Project', directory='subsnet_tuner_results', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite=True, _logger=None, **kwargs)[source]

Bases: PINNTunerBase

Specialized tuner for GeoPriorSubsNet models.

This class provides a flexible hyperparameter tuner for the physics-informed GeoPriorSubsNet. It builds on PINNTunerBase and uses keras-tuner backends to search architectural, physics, and compile-time spaces. Fixed, data-dependent parameters are separated from the search space, and GeoPrior input checks are enforced during run and create.

The recommended entry point is SubsNetTuner.create, which infers data dimensions from NumPy arrays, merges them with robust defaults, and applies user overrides.

Parameters:
  • fixed_params (dict) – Non-tunable configuration passed to the model __init__. Typical keys include static_input_dim, dynamic_input_dim, future_input_dim, output_subsidence_dim, output_gwl_dim, forecast_horizon, and stable flags such as use_batch_norm or pde_mode.

  • search_space (dict, optional) – Hyperparameter definitions. Each entry is either a list of discrete choices or a typed range dictionary such as {"dropout_rate": {"type": "float", "min_value": 0.1, "max_value": 0.4}}. Supported types are int, float, choice, and bool. Items are routed to model __init__ or to compile as noted below.

  • objective (str or keras_tuner.Objective, default "val_loss") – Metric to optimize. If the string contains “loss”, direction is inferred as “min”.

  • max_trials (int, default 10) – Maximum number of trials evaluated by the tuner.

  • project_name (str, default "SubsNetrTuner_Project") – Project name used for directory layout.

  • directory (str, default "subsnet_tuner_results") – Root directory where tuner artifacts are saved.

  • executions_per_trial (int, default 1) – Number of repeated trainings per hyperparameter set.

  • tuner_type ({'randomsearch', 'bayesianoptimization', 'hyperband'}, default 'randomsearch') – Search algorithm used by keras-tuner.

  • seed (int, optional) – Random seed for reproducibility.

  • overwrite (bool, default True) – If True, existing project results are overwritten.

  • _logger (logging.Logger or callable, optional) – Logger or print-like callable for progress lines.

  • kwargs (dict) – Forwarded to PINNTunerBase for advanced control.

Variables:
  • model_class (Type[tf.keras.Model]) – Bound to GeoPriorSubsNet.

  • fixed_params (dict) – Finalized, non-tunable model configuration.

  • search_space (dict) – User-provided hyperparameter search definitions.

  • best_hps (keras_tuner.HyperParameters or None) – Best hyperparameters found by the search.

  • best_model (tf.keras.Model or None) – Model built with the best hyperparameters.

  • tuner (keras_tuner.Tuner or None) – Underlying tuner instance after run or search.

  • tuning_summary (dict) – Compact summary saved under the project directory.

Notes

Required inputs. GeoPriorSubsNet expects coords for spatiotemporal coordinates, dynamic_features for time-varying covariates, and H_field for the soil-thickness field.

The helper canonicalizes H_field from common aliases, e.g., soil_thickness, soil thickness, h_field.

Target canonicalization. Targets are canonicalized to subs_pred and gwl_pred from subsidence and gwl. This is handled internally before data pipelines are built.

Compile-only hyperparameters. These search keys are not passed to __init__ and are routed to compile:

  • learning_rate

  • lambda_gw, lambda_cons, lambda_prior, lambda_smooth, lambda_mv

  • mv_lr_mult, kappa_lr_mult

Losses and metrics. By default the supervised heads use mean squared error with mean absolute error metrics. If fixed_params["quantiles"] is set, a pinball loss can be injected via a user loss factory at compile time.

Physics objectives. GeoPrior adds residuals consistent with consolidation and groundwater flow:

  • \(R_gw = Ss * d(h)/dt - div(K * grad(h)) - Q\)

  • \(R_cons = d(s)/dt - (s_eq - s) / tau\)

with \(s_eq = m_v * gamma_w * (h_ref - h) * H\). Weights are controlled by the compile-time lambdas.

Typical search groups.

  • Architecture: embed_dim, hidden_units, lstm_units, attention_units, num_heads, dropout_rate, vsn_units, use_vsn, use_batch_norm

  • Physics: pde_mode, mv, kappa, use_effective_h, hd_factor, kappa_mode, scale_pde_residuals

  • Optimization: learning_rate and lambda weights

Workflow. run builds tf.data pipelines from NumPy inputs, applies key canonicalization, validates GeoPrior requirements, and delegates to search. The best HPs and a built model are returned and stored on the class. The tuning workflow combines Keras Tuner search patterns with the poromechanics background from [21, 22, 23].

Examples

Create from arrays and tune a small space.

>>> from geoprior.models.forecast_tuner import SubsNetTuner
>>> fixed = {"forecast_horizon": 7}
>>> space = {
...   "embed_dim": [32, 64],
...   "num_heads": [2, 4],
...   "dropout_rate": {"type": "float",
...     "min_value": 0.1, "max_value": 0.3},
...   "learning_rate": [1e-3, 5e-4],
...   "lambda_gw": {"type": "float",
...     "min_value": 0.5, "max_value": 1.5},
... }
>>> tuner = SubsNetTuner.create(
...   inputs_data=inputs_np,
...   targets_data=targets_np,
...   search_space=space,
...   fixed_params=fixed,
...   max_trials=20,
...   project_name="GeoPrior_HP_Search",
... )
>>> best_model, best_hps, kt = tuner.run(
...   inputs=inputs_np,
...   y=targets_np,
...   validation_data=(val_inputs_np, val_targets_np),
...   epochs=30,
...   batch_size=32,
... )

See also

PINNTunerBase

Base hypermodel with the generic search routine.

GeoPriorSubsNet

Target model with physics residuals and priors.

HydroTuner

Generic PINN tuner for HAL and TransFlow models.

__init__(fixed_params, search_space=None, objective='val_loss', max_trials=10, project_name='SubsNetrTuner_Project', directory='subsnet_tuner_results', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite=True, _logger=None, **kwargs)[source]

Initialize the base class.

Parameters:
  • verbose (int, optional) – Verbosity level controlling logging (0 to 3). Defaults to 0.

  • fixed_params (dict[str, Any])

  • search_space (dict[str, Any] | None)

  • objective (str | Objective)

  • max_trials (int)

  • project_name (str)

  • directory (str)

  • executions_per_trial (int)

  • tuner_type (str)

  • seed (int | None)

  • overwrite (bool)

  • _logger (Callable[[str], None] | Logger | None)

model_class: type[Model]
classmethod create(inputs_data, targets_data, search_space, fixed_params=None, **tuner_kwargs)[source]
Parameters:
Return type:

SubsNetTuner

build(hp)[source]

Builds and compiles the Keras model with hyperparameters.

This method must be overridden by subclasses (e.g., PIHALTuner) to define the specific model architecture (like PIHALNet), sample hyperparameters using the hp object based on self.param_space, and compile the model.

Args:

hp (kt.HyperParameters): Keras Tuner HyperParameters object.

Returns:

tf.keras.Model: The compiled Keras model.

Parameters:

hp (HyperParameters)

Return type:

Model

run(inputs, y, validation_data=None, epochs=10, batch_size=32, callbacks=None, case_info=None, verbose=1, **search_kwargs)[source]
Parameters:
Return type:

tuple[Model | None, HyperParameters | None, Tuner | None]

help(**kwargs)
my_params = SubsNetTuner(     fixed_params,     search_space=None,     objective='val_loss',     max_trials=10,     project_name='SubsNetrTuner_Project',     directory='subsnet_tuner_results',     executions_per_trial=1,     tuner_type='randomsearch',     seed=None,     overwrite=True,     _logger=None )

Public tuner entry point#

The primary user-facing entry point is SubsNetTuner.

This class specializes the generic tuner workflow for GeoPriorSubsNet. Its class docstring explains that it is designed for physics-informed hyperparameter search, that it separates data-dependent fixed parameters from the search space, and that create(...) is the recommended constructor when arrays are already available in memory.

Tuner for GeoPriorSubsNet.

class geoprior.models.forecast_tuner._geoprior_tuner.SubsNetTuner(fixed_params, search_space=None, objective='val_loss', max_trials=10, project_name='SubsNetrTuner_Project', directory='subsnet_tuner_results', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite=True, _logger=None, **kwargs)[source]

Bases: PINNTunerBase

Specialized tuner for GeoPriorSubsNet models.

This class provides a flexible hyperparameter tuner for the physics-informed GeoPriorSubsNet. It builds on PINNTunerBase and uses keras-tuner backends to search architectural, physics, and compile-time spaces. Fixed, data-dependent parameters are separated from the search space, and GeoPrior input checks are enforced during run and create.

The recommended entry point is SubsNetTuner.create, which infers data dimensions from NumPy arrays, merges them with robust defaults, and applies user overrides.

Parameters:
  • fixed_params (dict) – Non-tunable configuration passed to the model __init__. Typical keys include static_input_dim, dynamic_input_dim, future_input_dim, output_subsidence_dim, output_gwl_dim, forecast_horizon, and stable flags such as use_batch_norm or pde_mode.

  • search_space (dict, optional) – Hyperparameter definitions. Each entry is either a list of discrete choices or a typed range dictionary such as {"dropout_rate": {"type": "float", "min_value": 0.1, "max_value": 0.4}}. Supported types are int, float, choice, and bool. Items are routed to model __init__ or to compile as noted below.

  • objective (str or keras_tuner.Objective, default "val_loss") – Metric to optimize. If the string contains “loss”, direction is inferred as “min”.

  • max_trials (int, default 10) – Maximum number of trials evaluated by the tuner.

  • project_name (str, default "SubsNetrTuner_Project") – Project name used for directory layout.

  • directory (str, default "subsnet_tuner_results") – Root directory where tuner artifacts are saved.

  • executions_per_trial (int, default 1) – Number of repeated trainings per hyperparameter set.

  • tuner_type ({'randomsearch', 'bayesianoptimization', 'hyperband'}, default 'randomsearch') – Search algorithm used by keras-tuner.

  • seed (int, optional) – Random seed for reproducibility.

  • overwrite (bool, default True) – If True, existing project results are overwritten.

  • _logger (logging.Logger or callable, optional) – Logger or print-like callable for progress lines.

  • kwargs (dict) – Forwarded to PINNTunerBase for advanced control.

Variables:
  • model_class (Type[tf.keras.Model]) – Bound to GeoPriorSubsNet.

  • fixed_params (dict) – Finalized, non-tunable model configuration.

  • search_space (dict) – User-provided hyperparameter search definitions.

  • best_hps (keras_tuner.HyperParameters or None) – Best hyperparameters found by the search.

  • best_model (tf.keras.Model or None) – Model built with the best hyperparameters.

  • tuner (keras_tuner.Tuner or None) – Underlying tuner instance after run or search.

  • tuning_summary (dict) – Compact summary saved under the project directory.

Notes

Required inputs. GeoPriorSubsNet expects coords for spatiotemporal coordinates, dynamic_features for time-varying covariates, and H_field for the soil-thickness field.

The helper canonicalizes H_field from common aliases, e.g., soil_thickness, soil thickness, h_field.

Target canonicalization. Targets are canonicalized to subs_pred and gwl_pred from subsidence and gwl. This is handled internally before data pipelines are built.

Compile-only hyperparameters. These search keys are not passed to __init__ and are routed to compile:

  • learning_rate

  • lambda_gw, lambda_cons, lambda_prior, lambda_smooth, lambda_mv

  • mv_lr_mult, kappa_lr_mult

Losses and metrics. By default the supervised heads use mean squared error with mean absolute error metrics. If fixed_params["quantiles"] is set, a pinball loss can be injected via a user loss factory at compile time.

Physics objectives. GeoPrior adds residuals consistent with consolidation and groundwater flow:

  • \(R_gw = Ss * d(h)/dt - div(K * grad(h)) - Q\)

  • \(R_cons = d(s)/dt - (s_eq - s) / tau\)

with \(s_eq = m_v * gamma_w * (h_ref - h) * H\). Weights are controlled by the compile-time lambdas.

Typical search groups.

  • Architecture: embed_dim, hidden_units, lstm_units, attention_units, num_heads, dropout_rate, vsn_units, use_vsn, use_batch_norm

  • Physics: pde_mode, mv, kappa, use_effective_h, hd_factor, kappa_mode, scale_pde_residuals

  • Optimization: learning_rate and lambda weights

Workflow. run builds tf.data pipelines from NumPy inputs, applies key canonicalization, validates GeoPrior requirements, and delegates to search. The best HPs and a built model are returned and stored on the class. The tuning workflow combines Keras Tuner search patterns with the poromechanics background from [21, 22, 23].

Examples

Create from arrays and tune a small space.

>>> from geoprior.models.forecast_tuner import SubsNetTuner
>>> fixed = {"forecast_horizon": 7}
>>> space = {
...   "embed_dim": [32, 64],
...   "num_heads": [2, 4],
...   "dropout_rate": {"type": "float",
...     "min_value": 0.1, "max_value": 0.3},
...   "learning_rate": [1e-3, 5e-4],
...   "lambda_gw": {"type": "float",
...     "min_value": 0.5, "max_value": 1.5},
... }
>>> tuner = SubsNetTuner.create(
...   inputs_data=inputs_np,
...   targets_data=targets_np,
...   search_space=space,
...   fixed_params=fixed,
...   max_trials=20,
...   project_name="GeoPrior_HP_Search",
... )
>>> best_model, best_hps, kt = tuner.run(
...   inputs=inputs_np,
...   y=targets_np,
...   validation_data=(val_inputs_np, val_targets_np),
...   epochs=30,
...   batch_size=32,
... )

See also

PINNTunerBase

Base hypermodel with the generic search routine.

GeoPriorSubsNet

Target model with physics residuals and priors.

HydroTuner

Generic PINN tuner for HAL and TransFlow models.

__init__(fixed_params, search_space=None, objective='val_loss', max_trials=10, project_name='SubsNetrTuner_Project', directory='subsnet_tuner_results', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite=True, _logger=None, **kwargs)[source]

Initialize the base class.

Parameters:
  • verbose (int, optional) – Verbosity level controlling logging (0 to 3). Defaults to 0.

  • fixed_params (dict[str, Any])

  • search_space (dict[str, Any] | None)

  • objective (str | Objective)

  • max_trials (int)

  • project_name (str)

  • directory (str)

  • executions_per_trial (int)

  • tuner_type (str)

  • seed (int | None)

  • overwrite (bool)

  • _logger (Callable[[str], None] | Logger | None)

model_class: type[Model]
classmethod create(inputs_data, targets_data, search_space, fixed_params=None, **tuner_kwargs)[source]
Parameters:
Return type:

SubsNetTuner

build(hp)[source]

Builds and compiles the Keras model with hyperparameters.

This method must be overridden by subclasses (e.g., PIHALTuner) to define the specific model architecture (like PIHALNet), sample hyperparameters using the hp object based on self.param_space, and compile the model.

Args:

hp (kt.HyperParameters): Keras Tuner HyperParameters object.

Returns:

tf.keras.Model: The compiled Keras model.

Parameters:

hp (HyperParameters)

Return type:

Model

run(inputs, y, validation_data=None, epochs=10, batch_size=32, callbacks=None, case_info=None, verbose=1, **search_kwargs)[source]
Parameters:
Return type:

tuple[Model | None, HyperParameters | None, Tuner | None]

help(**kwargs)
my_params = SubsNetTuner(     fixed_params,     search_space=None,     objective='val_loss',     max_trials=10,     project_name='SubsNetrTuner_Project',     directory='subsnet_tuner_results',     executions_per_trial=1,     tuner_type='randomsearch',     seed=None,     overwrite=True,     _logger=None )

Key public class#

class geoprior.models.forecast_tuner._geoprior_tuner.SubsNetTuner(fixed_params, search_space=None, objective='val_loss', max_trials=10, project_name='SubsNetrTuner_Project', directory='subsnet_tuner_results', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite=True, _logger=None, **kwargs)[source]

Bases: PINNTunerBase

Specialized tuner for GeoPriorSubsNet models.

This class provides a flexible hyperparameter tuner for the physics-informed GeoPriorSubsNet. It builds on PINNTunerBase and uses keras-tuner backends to search architectural, physics, and compile-time spaces. Fixed, data-dependent parameters are separated from the search space, and GeoPrior input checks are enforced during run and create.

The recommended entry point is SubsNetTuner.create, which infers data dimensions from NumPy arrays, merges them with robust defaults, and applies user overrides.

Parameters:
  • fixed_params (dict) – Non-tunable configuration passed to the model __init__. Typical keys include static_input_dim, dynamic_input_dim, future_input_dim, output_subsidence_dim, output_gwl_dim, forecast_horizon, and stable flags such as use_batch_norm or pde_mode.

  • search_space (dict, optional) – Hyperparameter definitions. Each entry is either a list of discrete choices or a typed range dictionary such as {"dropout_rate": {"type": "float", "min_value": 0.1, "max_value": 0.4}}. Supported types are int, float, choice, and bool. Items are routed to model __init__ or to compile as noted below.

  • objective (str or keras_tuner.Objective, default "val_loss") – Metric to optimize. If the string contains “loss”, direction is inferred as “min”.

  • max_trials (int, default 10) – Maximum number of trials evaluated by the tuner.

  • project_name (str, default "SubsNetrTuner_Project") – Project name used for directory layout.

  • directory (str, default "subsnet_tuner_results") – Root directory where tuner artifacts are saved.

  • executions_per_trial (int, default 1) – Number of repeated trainings per hyperparameter set.

  • tuner_type ({'randomsearch', 'bayesianoptimization', 'hyperband'}, default 'randomsearch') – Search algorithm used by keras-tuner.

  • seed (int, optional) – Random seed for reproducibility.

  • overwrite (bool, default True) – If True, existing project results are overwritten.

  • _logger (logging.Logger or callable, optional) – Logger or print-like callable for progress lines.

  • kwargs (dict) – Forwarded to PINNTunerBase for advanced control.

Variables:
  • model_class (Type[tf.keras.Model]) – Bound to GeoPriorSubsNet.

  • fixed_params (dict) – Finalized, non-tunable model configuration.

  • search_space (dict) – User-provided hyperparameter search definitions.

  • best_hps (keras_tuner.HyperParameters or None) – Best hyperparameters found by the search.

  • best_model (tf.keras.Model or None) – Model built with the best hyperparameters.

  • tuner (keras_tuner.Tuner or None) – Underlying tuner instance after run or search.

  • tuning_summary (dict) – Compact summary saved under the project directory.

Notes

Required inputs. GeoPriorSubsNet expects coords for spatiotemporal coordinates, dynamic_features for time-varying covariates, and H_field for the soil-thickness field.

The helper canonicalizes H_field from common aliases, e.g., soil_thickness, soil thickness, h_field.

Target canonicalization. Targets are canonicalized to subs_pred and gwl_pred from subsidence and gwl. This is handled internally before data pipelines are built.

Compile-only hyperparameters. These search keys are not passed to __init__ and are routed to compile:

  • learning_rate

  • lambda_gw, lambda_cons, lambda_prior, lambda_smooth, lambda_mv

  • mv_lr_mult, kappa_lr_mult

Losses and metrics. By default the supervised heads use mean squared error with mean absolute error metrics. If fixed_params["quantiles"] is set, a pinball loss can be injected via a user loss factory at compile time.

Physics objectives. GeoPrior adds residuals consistent with consolidation and groundwater flow:

  • \(R_gw = Ss * d(h)/dt - div(K * grad(h)) - Q\)

  • \(R_cons = d(s)/dt - (s_eq - s) / tau\)

with \(s_eq = m_v * gamma_w * (h_ref - h) * H\). Weights are controlled by the compile-time lambdas.

Typical search groups.

  • Architecture: embed_dim, hidden_units, lstm_units, attention_units, num_heads, dropout_rate, vsn_units, use_vsn, use_batch_norm

  • Physics: pde_mode, mv, kappa, use_effective_h, hd_factor, kappa_mode, scale_pde_residuals

  • Optimization: learning_rate and lambda weights

Workflow. run builds tf.data pipelines from NumPy inputs, applies key canonicalization, validates GeoPrior requirements, and delegates to search. The best HPs and a built model are returned and stored on the class. The tuning workflow combines Keras Tuner search patterns with the poromechanics background from [21, 22, 23].

Examples

Create from arrays and tune a small space.

>>> from geoprior.models.forecast_tuner import SubsNetTuner
>>> fixed = {"forecast_horizon": 7}
>>> space = {
...   "embed_dim": [32, 64],
...   "num_heads": [2, 4],
...   "dropout_rate": {"type": "float",
...     "min_value": 0.1, "max_value": 0.3},
...   "learning_rate": [1e-3, 5e-4],
...   "lambda_gw": {"type": "float",
...     "min_value": 0.5, "max_value": 1.5},
... }
>>> tuner = SubsNetTuner.create(
...   inputs_data=inputs_np,
...   targets_data=targets_np,
...   search_space=space,
...   fixed_params=fixed,
...   max_trials=20,
...   project_name="GeoPrior_HP_Search",
... )
>>> best_model, best_hps, kt = tuner.run(
...   inputs=inputs_np,
...   y=targets_np,
...   validation_data=(val_inputs_np, val_targets_np),
...   epochs=30,
...   batch_size=32,
... )

See also

PINNTunerBase

Base hypermodel with the generic search routine.

GeoPriorSubsNet

Target model with physics residuals and priors.

HydroTuner

Generic PINN tuner for HAL and TransFlow models.

__init__(fixed_params, search_space=None, objective='val_loss', max_trials=10, project_name='SubsNetrTuner_Project', directory='subsnet_tuner_results', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite=True, _logger=None, **kwargs)[source]

Initialize the base class.

Parameters:
  • verbose (int, optional) – Verbosity level controlling logging (0 to 3). Defaults to 0.

  • fixed_params (dict[str, Any])

  • search_space (dict[str, Any] | None)

  • objective (str | Objective)

  • max_trials (int)

  • project_name (str)

  • directory (str)

  • executions_per_trial (int)

  • tuner_type (str)

  • seed (int | None)

  • overwrite (bool)

  • _logger (Callable[[str], None] | Logger | None)

model_class: type[Model]
classmethod create(inputs_data, targets_data, search_space, fixed_params=None, **tuner_kwargs)[source]
Parameters:
Return type:

SubsNetTuner

build(hp)[source]

Builds and compiles the Keras model with hyperparameters.

This method must be overridden by subclasses (e.g., PIHALTuner) to define the specific model architecture (like PIHALNet), sample hyperparameters using the hp object based on self.param_space, and compile the model.

Args:

hp (kt.HyperParameters): Keras Tuner HyperParameters object.

Returns:

tf.keras.Model: The compiled Keras model.

Parameters:

hp (HyperParameters)

Return type:

Model

run(inputs, y, validation_data=None, epochs=10, batch_size=32, callbacks=None, case_info=None, verbose=1, **search_kwargs)[source]
Parameters:
Return type:

tuple[Model | None, HyperParameters | None, Tuner | None]

help(**kwargs)
my_params = SubsNetTuner(     fixed_params,     search_space=None,     objective='val_loss',     max_trials=10,     project_name='SubsNetrTuner_Project',     directory='subsnet_tuner_results',     executions_per_trial=1,     tuner_type='randomsearch',     seed=None,     overwrite=True,     _logger=None )

Important public methods#

classmethod SubsNetTuner.create(inputs_data, targets_data, search_space, fixed_params=None, **tuner_kwargs)[source]
Parameters:
Return type:

SubsNetTuner

SubsNetTuner.run(inputs, y, validation_data=None, epochs=10, batch_size=32, callbacks=None, case_info=None, verbose=1, **search_kwargs)[source]
Parameters:
Return type:

tuple[Model | None, HyperParameters | None, Tuner | None]

SubsNetTuner.build(hp)[source]

Builds and compiles the Keras model with hyperparameters.

This method must be overridden by subclasses (e.g., PIHALTuner) to define the specific model architecture (like PIHALNet), sample hyperparameters using the hp object based on self.param_space, and compile the model.

Args:

hp (kt.HyperParameters): Keras Tuner HyperParameters object.

Returns:

tf.keras.Model: The compiled Keras model.

Parameters:

hp (HyperParameters)

Return type:

Model

What SubsNetTuner is responsible for#

The GeoPrior-specific tuner is responsible for the application-facing part of the search pipeline. In particular, it:

  • binds the tuning workflow to GeoPriorSubsNet;

  • infers and merges fixed data-shape parameters from array inputs when create(...) is used;

  • canonicalizes target names such as subsidence and gwl to the model-facing names subs_pred and gwl_pred;

  • separates model-init hyperparameters from compile-only hyperparameters;

  • constructs the per-trial model and compiles it with losses, metrics, and physics weights;

  • validates GeoPrior input requirements before delegating the actual search loop to the shared base class.

These responsibilities are visible in the implementation itself. The module defines explicit compile-only hyperparameter keys such as learning_rate, lambda_gw, lambda_cons, lambda_prior, lambda_smooth, lambda_mv, lambda_bounds, lambda_q, and lambda_offset; it also binds GeoPriorSubsNet as the target model class and provides a create(...) constructor that canonicalizes training targets before inferring fixed parameters.

This is why the tuner should be read as a model-aware scientific component rather than as a generic high-level helper.

Shared base tuner#

The tuning stack also includes a reusable generic base class: PINNTunerBase.

This base class handles the broader search orchestration shared by PINN or physics-aware tuning workflows. Its implementation includes:

  • objective normalization;

  • tuner backend validation;

  • keras-tuner backend selection;

  • project and directory management;

  • repeated executions per trial;

  • callback plumbing;

  • validation-data handling;

  • best-hyperparameter and best-model recovery.

The uploaded source shows that PINNTunerBase subclasses both HyperModel and BaseClass and centralizes the keras-tuner classes through the KT_DEPS dependency container. It also normalizes tuner backend names such as randomsearch, bayesianoptimization, and hyperband inside its validation logic.

Base classes and utilities for hyperparameter tuning of PINN models.

class geoprior.models.forecast_tuner._base_tuner.PINNTunerBase(objective='val_loss', max_trials=10, project_name='PINN_Tuning', directory='pinn_tuner_results', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite_tuner=True, _logger=None, **tuner_kwargs)[source]#

Bases: HyperModel, BaseClass

Base class for hyperparameter tuning of physics-informed models.

This class wraps keras-tuner orchestration for GeoPrior PINN-style models. Subclasses are expected to implement build(hp).

Parameters:
  • objective (str or keras_tuner.Objective, default "val_loss") – Metric to optimize during the search.

  • max_trials (int, default 10) – Maximum number of hyperparameter trials to evaluate.

  • project_name (str, default "PINN_Tuning") – Project name used for tuner artifacts.

  • directory (str, default "pinn_tuner_results") – Root directory for tuner outputs.

  • executions_per_trial (int, default 1) – Number of repeated trainings per sampled hyperparameter set.

  • tuner_type ({"randomsearch", "bayesianoptimization", "hyperband"}, default "randomsearch") – Search backend used by keras-tuner.

  • seed (int or None, default None) – Random seed used for reproducibility.

  • overwrite_tuner (bool, default True) – Whether to overwrite an existing tuner project directory.

  • tuner_kwargs (dict) – Additional keyword arguments forwarded to the underlying tuner backend.

  • _logger (Logger | Callable[[str], None] | None)

Variables:
  • best_hps (keras_tuner.HyperParameters or None) – Best hyperparameters discovered during tuning.

  • best_model (tf.keras.Model or None) – Best compiled model recovered from the tuner.

  • tuner (keras_tuner.Tuner or None) – Underlying tuner instance.

  • tuning_summary (dict) – Compact summary of the completed tuning run.

__init__(objective='val_loss', max_trials=10, project_name='PINN_Tuning', directory='pinn_tuner_results', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite_tuner=True, _logger=None, **tuner_kwargs)[source]#

Initialize the base class.

Parameters:
  • verbose (int, optional) – Verbosity level controlling logging (0 to 3). Defaults to 0.

  • objective (str | Objective)

  • max_trials (int)

  • project_name (str)

  • directory (str)

  • executions_per_trial (int)

  • tuner_type (str)

  • seed (int | None)

  • overwrite_tuner (bool)

  • _logger (Logger | Callable[[str], None] | None)

best_hps_: HyperParameters | None#
best_model_: Model | None#
tuner_: Tuner | None#
tuning_summary_: dict[str, Any]#
fixed_model_params: dict[str, Any]#
param_space_config: dict[str, Any]#
build(hp)[source]#

Builds and compiles the Keras model with hyperparameters.

This method must be overridden by subclasses (e.g., PIHALTuner) to define the specific model architecture (like PIHALNet), sample hyperparameters using the hp object based on self.param_space, and compile the model.

Args:

hp (kt.HyperParameters): Keras Tuner HyperParameters object.

Returns:

tf.keras.Model: The compiled Keras model.

Parameters:

hp (HyperParameters)

Return type:

Model

search(train_data, epochs, validation_data=None, callbacks=None, verbose=1, patience=10, **additional_search_kwargs)[source]#

Performs the hyperparameter search using Keras Tuner.

Parameters:
  • train_data (tf.data.Dataset) – Training dataset. Must yield tuples of (inputs_dict, targets_dict) compatible with the model’s train_step.

  • epochs (int) – Number of epochs to train each model during a trial.

  • validation_data (tf.data.Dataset or None, default None) – Validation dataset.

  • callbacks (list of tf.keras.callbacks.Callback or None, default None) – Keras callbacks for the search phase.

  • verbose (int, default 1) – Verbosity level for Keras Tuner search.

  • patience (int, default 10) – Early-stopping patience.

  • **additional_search_kwargs – Additional keyword arguments passed to the tuner search() method.

Returns:

  • best_model (tf.keras.Model or None) – Best model instance built with the best hyperparameters.

  • best_hps (keras_tuner.HyperParameters or None) – Best hyperparameters found.

  • tuner (keras_tuner.Tuner or None) – Tuner instance used for the search.

Return type:

tuple[Model | None, HyperParameters | None, Tuner | None]

help(**kwargs)#
my_params = PINNTunerBase(     objective='val_loss',     max_trials=10,     project_name='PINN_Tuning',     directory='pinn_tuner_results',     executions_per_trial=1,     tuner_type='randomsearch',     seed=None,     overwrite_tuner=True,     _logger=None )#

Key base class#

class geoprior.models.forecast_tuner._base_tuner.PINNTunerBase(objective='val_loss', max_trials=10, project_name='PINN_Tuning', directory='pinn_tuner_results', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite_tuner=True, _logger=None, **tuner_kwargs)[source]#

Bases: HyperModel, BaseClass

Base class for hyperparameter tuning of physics-informed models.

This class wraps keras-tuner orchestration for GeoPrior PINN-style models. Subclasses are expected to implement build(hp).

Parameters:
  • objective (str or keras_tuner.Objective, default "val_loss") – Metric to optimize during the search.

  • max_trials (int, default 10) – Maximum number of hyperparameter trials to evaluate.

  • project_name (str, default "PINN_Tuning") – Project name used for tuner artifacts.

  • directory (str, default "pinn_tuner_results") – Root directory for tuner outputs.

  • executions_per_trial (int, default 1) – Number of repeated trainings per sampled hyperparameter set.

  • tuner_type ({"randomsearch", "bayesianoptimization", "hyperband"}, default "randomsearch") – Search backend used by keras-tuner.

  • seed (int or None, default None) – Random seed used for reproducibility.

  • overwrite_tuner (bool, default True) – Whether to overwrite an existing tuner project directory.

  • tuner_kwargs (dict) – Additional keyword arguments forwarded to the underlying tuner backend.

  • _logger (Logger | Callable[[str], None] | None)

Variables:
  • best_hps (keras_tuner.HyperParameters or None) – Best hyperparameters discovered during tuning.

  • best_model (tf.keras.Model or None) – Best compiled model recovered from the tuner.

  • tuner (keras_tuner.Tuner or None) – Underlying tuner instance.

  • tuning_summary (dict) – Compact summary of the completed tuning run.

__init__(objective='val_loss', max_trials=10, project_name='PINN_Tuning', directory='pinn_tuner_results', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite_tuner=True, _logger=None, **tuner_kwargs)[source]#

Initialize the base class.

Parameters:
  • verbose (int, optional) – Verbosity level controlling logging (0 to 3). Defaults to 0.

  • objective (str | Objective)

  • max_trials (int)

  • project_name (str)

  • directory (str)

  • executions_per_trial (int)

  • tuner_type (str)

  • seed (int | None)

  • overwrite_tuner (bool)

  • _logger (Logger | Callable[[str], None] | None)

best_hps_: HyperParameters | None#
best_model_: Model | None#
tuner_: Tuner | None#
tuning_summary_: dict[str, Any]#
fixed_model_params: dict[str, Any]#
param_space_config: dict[str, Any]#
build(hp)[source]#

Builds and compiles the Keras model with hyperparameters.

This method must be overridden by subclasses (e.g., PIHALTuner) to define the specific model architecture (like PIHALNet), sample hyperparameters using the hp object based on self.param_space, and compile the model.

Args:

hp (kt.HyperParameters): Keras Tuner HyperParameters object.

Returns:

tf.keras.Model: The compiled Keras model.

Parameters:

hp (HyperParameters)

Return type:

Model

search(train_data, epochs, validation_data=None, callbacks=None, verbose=1, patience=10, **additional_search_kwargs)[source]#

Performs the hyperparameter search using Keras Tuner.

Parameters:
  • train_data (tf.data.Dataset) – Training dataset. Must yield tuples of (inputs_dict, targets_dict) compatible with the model’s train_step.

  • epochs (int) – Number of epochs to train each model during a trial.

  • validation_data (tf.data.Dataset or None, default None) – Validation dataset.

  • callbacks (list of tf.keras.callbacks.Callback or None, default None) – Keras callbacks for the search phase.

  • verbose (int, default 1) – Verbosity level for Keras Tuner search.

  • patience (int, default 10) – Early-stopping patience.

  • **additional_search_kwargs – Additional keyword arguments passed to the tuner search() method.

Returns:

  • best_model (tf.keras.Model or None) – Best model instance built with the best hyperparameters.

  • best_hps (keras_tuner.HyperParameters or None) – Best hyperparameters found.

  • tuner (keras_tuner.Tuner or None) – Tuner instance used for the search.

Return type:

tuple[Model | None, HyperParameters | None, Tuner | None]

help(**kwargs)#
my_params = PINNTunerBase(     objective='val_loss',     max_trials=10,     project_name='PINN_Tuning',     directory='pinn_tuner_results',     executions_per_trial=1,     tuner_type='randomsearch',     seed=None,     overwrite_tuner=True,     _logger=None )#

Important base methods#

PINNTunerBase.search(train_data, epochs, validation_data=None, callbacks=None, verbose=1, patience=10, **additional_search_kwargs)[source]#

Performs the hyperparameter search using Keras Tuner.

Parameters:
  • train_data (tf.data.Dataset) – Training dataset. Must yield tuples of (inputs_dict, targets_dict) compatible with the model’s train_step.

  • epochs (int) – Number of epochs to train each model during a trial.

  • validation_data (tf.data.Dataset or None, default None) – Validation dataset.

  • callbacks (list of tf.keras.callbacks.Callback or None, default None) – Keras callbacks for the search phase.

  • verbose (int, default 1) – Verbosity level for Keras Tuner search.

  • patience (int, default 10) – Early-stopping patience.

  • **additional_search_kwargs – Additional keyword arguments passed to the tuner search() method.

Returns:

  • best_model (tf.keras.Model or None) – Best model instance built with the best hyperparameters.

  • best_hps (keras_tuner.HyperParameters or None) – Best hyperparameters found.

  • tuner (keras_tuner.Tuner or None) – Tuner instance used for the search.

Return type:

tuple[Model | None, HyperParameters | None, Tuner | None]

PINNTunerBase.build(hp)[source]#

Builds and compiles the Keras model with hyperparameters.

This method must be overridden by subclasses (e.g., PIHALTuner) to define the specific model architecture (like PIHALNet), sample hyperparameters using the hp object based on self.param_space, and compile the model.

Args:

hp (kt.HyperParameters): Keras Tuner HyperParameters object.

Returns:

tf.keras.Model: The compiled Keras model.

Parameters:

hp (HyperParameters)

Return type:

Model

_base_tuner.PINNTunerBase(max_trials=10, project_name='PINN_Tuning', directory='pinn_tuner_results', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite_tuner=True, _logger=None, **tuner_kwargs)#

Base class for hyperparameter tuning of physics-informed models.

This class wraps keras-tuner orchestration for GeoPrior PINN-style models. Subclasses are expected to implement build(hp).

Parameters:
  • objective (str or keras_tuner.Objective, default "val_loss") – Metric to optimize during the search.

  • max_trials (int, default 10) – Maximum number of hyperparameter trials to evaluate.

  • project_name (str, default "PINN_Tuning") – Project name used for tuner artifacts.

  • directory (str, default "pinn_tuner_results") – Root directory for tuner outputs.

  • executions_per_trial (int, default 1) – Number of repeated trainings per sampled hyperparameter set.

  • tuner_type ({"randomsearch", "bayesianoptimization", "hyperband"}, default "randomsearch") – Search backend used by keras-tuner.

  • seed (int or None, default None) – Random seed used for reproducibility.

  • overwrite_tuner (bool, default True) – Whether to overwrite an existing tuner project directory.

  • tuner_kwargs (dict) – Additional keyword arguments forwarded to the underlying tuner backend.

  • _logger (Logger | Callable[[str], None] | None)

Variables:
  • best_hps (keras_tuner.HyperParameters or None) – Best hyperparameters discovered during tuning.

  • best_model (tf.keras.Model or None) – Best compiled model recovered from the tuner.

  • tuner (keras_tuner.Tuner or None) – Underlying tuner instance.

  • tuning_summary (dict) – Compact summary of the completed tuning run.

How the tuning stack is layered#

A useful design map is:

PINNTunerBase
   ├── objective normalization
   ├── keras-tuner backend selection
   ├── trial orchestration
   ├── callback / validation wiring
   └── best-model recovery

SubsNetTuner
   ├── binds GeoPriorSubsNet
   ├── infers data dimensions
   ├── checks required GeoPrior inputs
   ├── canonicalizes targets
   ├── separates init vs compile HPs
   └── builds the tuned GeoPrior model

This layering is one of the strengths of the current design. The base class remains reusable and backend-oriented, while the specialized class keeps the scientific contract of the subsidence model close to the search logic.

GeoPrior-specific tuning logic#

The specialization implemented in geoprior.models.forecast_tuner._geoprior_tuner encodes several assumptions that are specific to GeoPrior subsidence forecasting.

These include:

  • required model inputs such as coords, dynamic_features, and H_field;

  • canonical target names subs_pred and gwl_pred;

  • GeoPrior architecture defaults and default physics settings;

  • compile-time routing for loss weights and physics penalties;

  • direct coupling to the GeoPriorSubsNet constructor and compile stage.

The class docstring also explains that the tuner is aware of the model’s physics objectives and loss balance, and not just its neural-network shape. It explicitly describes the residual structure used during training, including groundwater and consolidation residuals.

Compile-only hyperparameters#

One especially important API concept in the tuner stack is the separation between:

  • model-init hyperparameters, which alter the instantiated model;

  • compile-only hyperparameters, which alter the optimizer and loss weighting behavior without changing the instantiated architecture.

In the current implementation, keys such as the following are treated as compile-only search parameters:

  • learning_rate

  • lambda_gw

  • lambda_cons

  • lambda_prior

  • lambda_smooth

  • lambda_mv

  • lambda_bounds

  • lambda_q

  • lambda_offset

  • scale_mv_with_offset

  • scale_q_with_offset

  • mv_lr_mult

  • kappa_lr_mult

This split matters because it keeps the model definition conceptually separate from the optimization regime and from the weighting of physics terms. The implementation lists these keys explicitly in the _COMPILE_ONLY collection, which makes the behavior easy to trace in the source.

Supported tuner backends#

The shared base class currently normalizes and supports several keras-tuner backends, including:

  • random search,

  • Bayesian optimization,

  • Hyperband.

These are selected through the tuner_type argument and normalized by PINNTunerBase before the actual tuner object is instantiated.

Typical usage therefore looks like:

from geoprior.models.forecast_tuner import SubsNetTuner

tuner = SubsNetTuner.create(
    inputs_data=inputs_np,
    targets_data=targets_np,
    search_space=space,
    tuner_type="randomsearch",
    max_trials=20,
)

The example above matches the intended usage pattern described in the SubsNetTuner class documentation.

Practical read order#

If you are new to the tuning code, a good order is:

  1. SubsNetTuner

  2. create()

  3. search()

  4. build()

  5. geoprior.models.tuners

This order moves from the public entry point to the specialized build logic, then back to the generic search engine and the compatibility surface.

Source listings with comments#

These source listings are included intentionally so that the inline implementation comments remain visible during HTML rendering.

Public compatibility shim#

Shared base tuner#

GeoPrior-specific tuner#

API notes#

A few design details are worth keeping in mind while reading this API page:

  • SubsNetTuner.create(...) is the recommended user entry point when input and target arrays are already available, because it infers fixed dimensions and applies GeoPrior-aware canonicalization.

  • PINNTunerBase is generic in role, while SubsNetTuner provides the model-aware specialization. This is what keeps the tuning stack reusable without losing the scientific contract of GeoPrior.

  • The compatibility shim geoprior.models.tuners is a public import convenience, not a second implementation of the tuning logic.

  • The tuning layer is tightly coupled to the GeoPrior forecasting and physics assumptions, so it should be read together with the subsidence model API and with the Stage-3 tuning workflow.

See also#