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:
SubsNetTuneris the main public tuner class exposed by the forecast-tuner package;PINNTunerBaseprovides the reusable keras-tuner integration and generic search orchestration;geoprior.models.tunersis a compact compatibility shim that re-exportsSubsNetTunerfrom the public models namespace;geoprior.models.forecast_tuner._geoprior_tunerimplements the GeoPrior-specific tuning logic that binds the search flow toGeoPriorSubsNet.
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.
A subpackage for hyperparameter tuning of geoprior models using Keras Tuner. |
|
Model tuner exports and convenience helpers. |
|
Base classes and utilities for hyperparameter tuning of PINN models. |
|
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:
PINNTunerBaseSpecialized tuner for
GeoPriorSubsNetmodels.This class provides a flexible hyperparameter tuner for the physics-informed
GeoPriorSubsNet. It builds onPINNTunerBaseand 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 duringrunandcreate.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 includestatic_input_dim,dynamic_input_dim,future_input_dim,output_subsidence_dim,output_gwl_dim,forecast_horizon, and stable flags such asuse_batch_normorpde_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 areint,float,choice, andbool. Items are routed to model__init__or tocompileas noted below.objective (
strorkeras_tuner.Objective, default"val_loss") – Metric to optimize. If the string contains “loss”, direction is inferred as “min”.max_trials (
int, default10) – 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, default1) – 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, defaultTrue) – If True, existing project results are overwritten._logger (
logging.Loggerorcallable, optional) – Logger or print-like callable for progress lines.kwargs (
dict) – Forwarded toPINNTunerBasefor advanced control.
- Variables:
model_class (
Type[tf.keras.Model]) – Bound toGeoPriorSubsNet.fixed_params (
dict) – Finalized, non-tunable model configuration.search_space (
dict) – User-provided hyperparameter search definitions.best_hps (
keras_tuner.HyperParametersorNone) – Best hyperparameters found by the search.best_model (
tf.keras.ModelorNone) – Model built with the best hyperparameters.tuner (
keras_tuner.TunerorNone) – Underlying tuner instance afterrunorsearch.tuning_summary (
dict) – Compact summary saved under the project directory.
Notes
Required inputs.
GeoPriorSubsNetexpectscoordsfor spatiotemporal coordinates,dynamic_featuresfor time-varying covariates, andH_fieldfor the soil-thickness field.The helper canonicalizes
H_fieldfrom common aliases, e.g.,soil_thickness,soil thickness,h_field.Target canonicalization. Targets are canonicalized to
subs_predandgwl_predfromsubsidenceandgwl. This is handled internally before data pipelines are built.Compile-only hyperparameters. These search keys are not passed to
__init__and are routed tocompile:learning_ratelambda_gw,lambda_cons,lambda_prior,lambda_smooth,lambda_mvmv_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_normPhysics:
pde_mode,mv,kappa,use_effective_h,hd_factor,kappa_mode,scale_pde_residualsOptimization:
learning_rateand lambda weights
Workflow.
runbuildstf.datapipelines from NumPy inputs, applies key canonicalization, validates GeoPrior requirements, and delegates tosearch. 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
PINNTunerBaseBase hypermodel with the generic
searchroutine.GeoPriorSubsNetTarget model with physics residuals and priors.
HydroTunerGeneric 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.
- classmethod create(inputs_data, targets_data, search_space, fixed_params=None, **tuner_kwargs)[source]
- 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:
- 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,BaseClassBase 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 (
strorkeras_tuner.Objective, default"val_loss") – Metric to optimize during the search.max_trials (
int, default10) – 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, default1) – Number of repeated trainings per sampled hyperparameter set.tuner_type (
{"randomsearch", "bayesianoptimization", "hyperband"}, default"randomsearch") – Search backend used by keras-tuner.seed (
intorNone, defaultNone) – Random seed used for reproducibility.overwrite_tuner (
bool, defaultTrue) – Whether to overwrite an existing tuner project directory.tuner_kwargs (
dict) – Additional keyword arguments forwarded to the underlying tuner backend.
- Variables:
best_hps (
keras_tuner.HyperParametersorNone) – Best hyperparameters discovered during tuning.best_model (
tf.keras.ModelorNone) – Best compiled model recovered from the tuner.tuner (
keras_tuner.TunerorNone) – 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:
- best_hps_: HyperParameters | None
- best_model_: Model | None
- tuner_: Tuner | None
- 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’strain_step.epochs (
int) – Number of epochs to train each model during a trial.validation_data (
tf.data.DatasetorNone, defaultNone) – Validation dataset.callbacks (
listoftf.keras.callbacks.CallbackorNone, defaultNone) – Keras callbacks for the search phase.verbose (
int, default1) – Verbosity level for Keras Tuner search.patience (
int, default10) – Early-stopping patience.**additional_search_kwargs – Additional keyword arguments passed to the tuner
search()method.
- Returns:
- 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:
PINNTunerBaseSpecialized tuner for
GeoPriorSubsNetmodels.This class provides a flexible hyperparameter tuner for the physics-informed
GeoPriorSubsNet. It builds onPINNTunerBaseand 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 duringrunandcreate.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 includestatic_input_dim,dynamic_input_dim,future_input_dim,output_subsidence_dim,output_gwl_dim,forecast_horizon, and stable flags such asuse_batch_normorpde_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 areint,float,choice, andbool. Items are routed to model__init__or tocompileas noted below.objective (
strorkeras_tuner.Objective, default"val_loss") – Metric to optimize. If the string contains “loss”, direction is inferred as “min”.max_trials (
int, default10) – 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, default1) – 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, defaultTrue) – If True, existing project results are overwritten._logger (
logging.Loggerorcallable, optional) – Logger or print-like callable for progress lines.kwargs (
dict) – Forwarded toPINNTunerBasefor advanced control.
- Variables:
model_class (
Type[tf.keras.Model]) – Bound toGeoPriorSubsNet.fixed_params (
dict) – Finalized, non-tunable model configuration.search_space (
dict) – User-provided hyperparameter search definitions.best_hps (
keras_tuner.HyperParametersorNone) – Best hyperparameters found by the search.best_model (
tf.keras.ModelorNone) – Model built with the best hyperparameters.tuner (
keras_tuner.TunerorNone) – Underlying tuner instance afterrunorsearch.tuning_summary (
dict) – Compact summary saved under the project directory.
Notes
Required inputs.
GeoPriorSubsNetexpectscoordsfor spatiotemporal coordinates,dynamic_featuresfor time-varying covariates, andH_fieldfor the soil-thickness field.The helper canonicalizes
H_fieldfrom common aliases, e.g.,soil_thickness,soil thickness,h_field.Target canonicalization. Targets are canonicalized to
subs_predandgwl_predfromsubsidenceandgwl. This is handled internally before data pipelines are built.Compile-only hyperparameters. These search keys are not passed to
__init__and are routed tocompile:learning_ratelambda_gw,lambda_cons,lambda_prior,lambda_smooth,lambda_mvmv_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_normPhysics:
pde_mode,mv,kappa,use_effective_h,hd_factor,kappa_mode,scale_pde_residualsOptimization:
learning_rateand lambda weights
Workflow.
runbuildstf.datapipelines from NumPy inputs, applies key canonicalization, validates GeoPrior requirements, and delegates tosearch. 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
PINNTunerBaseBase hypermodel with the generic
searchroutine.GeoPriorSubsNetTarget model with physics residuals and priors.
HydroTunerGeneric 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.
- model_class: type[Model]
- classmethod create(inputs_data, targets_data, search_space, fixed_params=None, **tuner_kwargs)[source]
- 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:
PINNTunerBaseSpecialized tuner for
GeoPriorSubsNetmodels.This class provides a flexible hyperparameter tuner for the physics-informed
GeoPriorSubsNet. It builds onPINNTunerBaseand 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 duringrunandcreate.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 includestatic_input_dim,dynamic_input_dim,future_input_dim,output_subsidence_dim,output_gwl_dim,forecast_horizon, and stable flags such asuse_batch_normorpde_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 areint,float,choice, andbool. Items are routed to model__init__or tocompileas noted below.objective (
strorkeras_tuner.Objective, default"val_loss") – Metric to optimize. If the string contains “loss”, direction is inferred as “min”.max_trials (
int, default10) – 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, default1) – 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, defaultTrue) – If True, existing project results are overwritten._logger (
logging.Loggerorcallable, optional) – Logger or print-like callable for progress lines.kwargs (
dict) – Forwarded toPINNTunerBasefor advanced control.
- Variables:
model_class (
Type[tf.keras.Model]) – Bound toGeoPriorSubsNet.fixed_params (
dict) – Finalized, non-tunable model configuration.search_space (
dict) – User-provided hyperparameter search definitions.best_hps (
keras_tuner.HyperParametersorNone) – Best hyperparameters found by the search.best_model (
tf.keras.ModelorNone) – Model built with the best hyperparameters.tuner (
keras_tuner.TunerorNone) – Underlying tuner instance afterrunorsearch.tuning_summary (
dict) – Compact summary saved under the project directory.
Notes
Required inputs.
GeoPriorSubsNetexpectscoordsfor spatiotemporal coordinates,dynamic_featuresfor time-varying covariates, andH_fieldfor the soil-thickness field.The helper canonicalizes
H_fieldfrom common aliases, e.g.,soil_thickness,soil thickness,h_field.Target canonicalization. Targets are canonicalized to
subs_predandgwl_predfromsubsidenceandgwl. This is handled internally before data pipelines are built.Compile-only hyperparameters. These search keys are not passed to
__init__and are routed tocompile:learning_ratelambda_gw,lambda_cons,lambda_prior,lambda_smooth,lambda_mvmv_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_normPhysics:
pde_mode,mv,kappa,use_effective_h,hd_factor,kappa_mode,scale_pde_residualsOptimization:
learning_rateand lambda weights
Workflow.
runbuildstf.datapipelines from NumPy inputs, applies key canonicalization, validates GeoPrior requirements, and delegates tosearch. 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
PINNTunerBaseBase hypermodel with the generic
searchroutine.GeoPriorSubsNetTarget model with physics residuals and priors.
HydroTunerGeneric 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.
- model_class: type[Model]
- classmethod create(inputs_data, targets_data, search_space, fixed_params=None, **tuner_kwargs)[source]
- 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:
PINNTunerBaseSpecialized tuner for
GeoPriorSubsNetmodels.This class provides a flexible hyperparameter tuner for the physics-informed
GeoPriorSubsNet. It builds onPINNTunerBaseand 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 duringrunandcreate.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 includestatic_input_dim,dynamic_input_dim,future_input_dim,output_subsidence_dim,output_gwl_dim,forecast_horizon, and stable flags such asuse_batch_normorpde_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 areint,float,choice, andbool. Items are routed to model__init__or tocompileas noted below.objective (
strorkeras_tuner.Objective, default"val_loss") – Metric to optimize. If the string contains “loss”, direction is inferred as “min”.max_trials (
int, default10) – 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, default1) – 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, defaultTrue) – If True, existing project results are overwritten._logger (
logging.Loggerorcallable, optional) – Logger or print-like callable for progress lines.kwargs (
dict) – Forwarded toPINNTunerBasefor advanced control.
- Variables:
model_class (
Type[tf.keras.Model]) – Bound toGeoPriorSubsNet.fixed_params (
dict) – Finalized, non-tunable model configuration.search_space (
dict) – User-provided hyperparameter search definitions.best_hps (
keras_tuner.HyperParametersorNone) – Best hyperparameters found by the search.best_model (
tf.keras.ModelorNone) – Model built with the best hyperparameters.tuner (
keras_tuner.TunerorNone) – Underlying tuner instance afterrunorsearch.tuning_summary (
dict) – Compact summary saved under the project directory.
Notes
Required inputs.
GeoPriorSubsNetexpectscoordsfor spatiotemporal coordinates,dynamic_featuresfor time-varying covariates, andH_fieldfor the soil-thickness field.The helper canonicalizes
H_fieldfrom common aliases, e.g.,soil_thickness,soil thickness,h_field.Target canonicalization. Targets are canonicalized to
subs_predandgwl_predfromsubsidenceandgwl. This is handled internally before data pipelines are built.Compile-only hyperparameters. These search keys are not passed to
__init__and are routed tocompile:learning_ratelambda_gw,lambda_cons,lambda_prior,lambda_smooth,lambda_mvmv_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_normPhysics:
pde_mode,mv,kappa,use_effective_h,hd_factor,kappa_mode,scale_pde_residualsOptimization:
learning_rateand lambda weights
Workflow.
runbuildstf.datapipelines from NumPy inputs, applies key canonicalization, validates GeoPrior requirements, and delegates tosearch. 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
PINNTunerBaseBase hypermodel with the generic
searchroutine.GeoPriorSubsNetTarget model with physics residuals and priors.
HydroTunerGeneric 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.
- model_class: type[Model]
- classmethod create(inputs_data, targets_data, search_space, fixed_params=None, **tuner_kwargs)[source]
- 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]
- 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
subsidenceandgwlto the model-facing namessubs_predandgwl_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.
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, andH_field;canonical target names
subs_predandgwl_pred;GeoPrior architecture defaults and default physics settings;
compile-time routing for loss weights and physics penalties;
direct coupling to the
GeoPriorSubsNetconstructor 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_ratelambda_gwlambda_conslambda_priorlambda_smoothlambda_mvlambda_boundslambda_qlambda_offsetscale_mv_with_offsetscale_q_with_offsetmv_lr_multkappa_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:
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.PINNTunerBaseis generic in role, whileSubsNetTunerprovides the model-aware specialization. This is what keeps the tuning stack reusable without losing the scientific contract of GeoPrior.The compatibility shim
geoprior.models.tunersis 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.