fusionlab.nn.forecast_tuner.PiHALTuner¶
- class fusionlab.nn.forecast_tuner.PiHALTuner[source]¶
Bases:
PINNTunerBaseHyperparameter tuner for the PIHALNet model, which jointly predicts land subsidence and groundwater level (GWL) via a physics-informed neural network (PINN) framework.
PiHALTuner leverages Keras Tuner (e.g., RandomSearch or BayesianOptimization) to search over architectural and PINN-specific hyperparameters—embedding dimension, hidden units, LSTM layers, attention heads, dropout, activation functions, PDE coefficients, learning rates, etc.—while keeping the core model dimensions fixed. Fixed dimensions (input/output dims, forecast horizon, quantiles) are passed in fixed_model_params, ensuring that only the desired hyperparameters vary during tuning.
Objective¶
Minimize the combined validation loss for subsidence and GWL: .. math:
\theta^* \;=\; \arg\min_{\theta\in\Theta} \Bigl[ L_{\text{val}}^{\text{subs}}\bigl(f_{\theta}(X),y^{\text{subs}}\bigr) + \lambda_{\text{gwl}} \, L_{\text{val}}^{\text{gwl}}\bigl(f_{\theta}(X),y^{\text{gwl}}\bigr) \Bigr]
where \(\Theta\) is the joint hyperparameter space, and \(\lambda_{\text{gwl}}\) can be tuned via loss_weights in fixed_model_params.
- param fixed_model_params:
Dictionary of parameters that are fixed for this tuning session. These parameters are not searched over by the tuner but are passed directly to the model constructor. Typical entries include:
static_input_dim: dimensionality of static (time‐invariant) inputs.
dynamic_input_dim: dimensionality of dynamic (time‐varying) inputs.
future_input_dim: dimensionality of future covariates (if any).
output_subsidence_dim: output dimension for subsidence predictions.
output_gwl_dim: output dimension for groundwater level predictions.
forecast_horizon: number of time steps ahead to predict.
quantiles: list of quantiles (e.g. [0.1, 0.5, 0.9]) for quantile loss.
Any other model‐specific settings (e.g., use_vsn, use_batch_norm).
These values are required; there is no default. The tuner will treat them as constants while varying only the hyperparameters in param_space.
- type fixed_model_params:
dict- param param_space:
A mapping from hyperparameter names (strings) to search‐space definitions understood by Keras Tuner. For example:
For integer ranges: {“embed_dim”: {“min_value”: 32, “max_value”: 128, “step”: 32}}
For choices: {“activation”: [“relu”, “gelu”]}
For floats: {“dropout_rate”: {“min_value”: 0.05, “max_value”: 0.3, “step”: 0.05}}
When set to None, the tuner will rely on defaults defined in the subclass’s build(hp) method. Users may omit this to use built‐in defaults or supply a custom search space dictionary here.
- type param_space:
dict, optional- param objective:
- The metric that the tuner should optimize. Examples:
“val_loss”: minimize validation loss.
“val_total_loss”: minimize combined validation loss if the model reports multiple loss terms.
If passed as a raw string, any name containing “loss” is treated as a minimization objective; otherwise it is maximized. For more control (e.g. to override direction or specify a threshold), supply a keras_tuner.Objective(“metric_name”, direction=”max”) instance. Defaults:
“val_loss” in PINNTunerBase.
“val_total_loss” in PIHALTuner.
- type objective:
strorkeras_tuner.Objective, optional- param max_trials:
The maximum number of hyperparameter combinations (trials) to explore during the search. Each trial corresponds to one sampled set of hyperparameters, built, trained, and evaluated. Must be a positive integer. Defaults:
10 in PINNTunerBase.
20 in PIHALTuner.
Larger values increase search coverage but proportionally increase total computation time.
- type max_trials:
int, optional- param project_name:
Name of the subdirectory under directory in which tuner artifacts are stored (trial summaries, checkpoints, logs). If omitted, the tuner will generate a slug from the class name and a timestamp. This folder will contain model checkpoints, best‐hyperparameters logs, and any JSON summaries for each trial.
- type project_name:
str, optional- param directory:
Root directory where Keras Tuner stores results for this project. All tuner artifacts (checkpoints, logs, JSON summaries) for every trial are saved under directory/project_name. Defaults:
“pinn_tuner_results” for PINNTunerBase.
“pihalnet_tuner_results” for PIHALTuner.
Specify a writable path if you wish to archive or inspect tuning runs.
- type directory:
str, optional- param executions_per_trial:
Number of models to build and fit for each trial. Each execution will initialize and train a separate model with the same hyperparameters, then compute the average (or aggregated) objective to reduce variance due to random initialization. Defaults to 1. Setting >1 is useful when each trial’s performance is noisy and you want more robust ranking of hyperparameter sets.
- type executions_per_trial:
int, optional- param tuner_type:
- Search strategy to use. Supported values:
“randomsearch”: sample uniformly at random.
“bayesianoptimization”: use Bayesian optimization to propose hyperparameters based on past trial results.
“hyperband”: use Hyperband to adaptively allocate resources among trials based on early performance.
Defaults to “randomsearch”. Choose “bayesianoptimization” if you want more sample‐efficient search (may require specifying a prior).
- type tuner_type:
str, optional- param seed:
- Random seed for reproducibility. Controls:
Hyperparameter sampling (for random search).
Initial model weight initialization.
If None, Keras Tuner’s default seeding logic is used. Setting a fixed seed ensures that repeated runs with the same configuration produce identical trial order and model initializations.
- type seed:
int, optional- param overwrite_tuner:
If True, any existing tuner directory with the same project_name under directory will be removed and replaced. Use this to restart a fresh tuning run without retaining previous trials. Defaults to True. If set to False, existing trial results may be reused if present.
- type overwrite_tuner:
bool, optional- param **tuner_kwargs:
Additional keyword arguments to pass directly to the chosen Keras Tuner constructor. Examples:
For BayesianOptimization: {“beta”: 2.0} to control exploration.
For Hyperband: {“hyperband_iterations”: 3} to set bracket depth.
For RandomSearch: {“overwrite”: False} or other tuner‐specific flags. Any argument accepted by the underlying tuner API is valid.
- type **tuner_kwargs:
dict- param verbose:
Controls console logging verbosity. ``0``=silent, ``1``=high-level, ``2``=detailed, ``>=3``=debug. Higher levels print inferred dims, override warnings, and per-epoch metrics.
- type verbose:
int, default1
- fit(inputs, y, validation_data=None, forecast_horizon=None,
quantiles=None, epochs=10, batch_size=32, callbacks=None, verbose=1, case_info=None, **search_kwargs) Prepares data, infers/finalizes fixed_model_params, builds a tf.data.Dataset, and runs the Keras Tuner search() method.
- Other Parameters (fit method)
- -----------------------------
- inputs : dict[str, np.ndarray]
Dictionary of NumPy arrays for model inputs. Must contain:
"coords","static_features","dynamic_features". Optionally,"future_features"if forecasting with exogenous variables. Shapes:coords: (batch_size, 2)static_features: (batch_size, static_dim)dynamic_features: (batch_size, time_steps, dynamic_dim)future_features: (batch_size, time_steps, future_dim)
- y : dict[str, np.ndarray]
Dictionary of NumPy arrays for targets. Must contain either
"subsidence"or"subs_pred"(renamed tosubs_pred), and either"gwl"or"gwl_pred"(renamed togwl_pred). Shapes typically: (batch_size, time_steps, 1) for multi-horizon or (batch_size, 1) for point forecasts.
- validation_data : tuple, optional
A tuple
(val_inputs_dict, val_targets_dict)analogous toinputsandy. Used for early stopping and objective evaluation during search.
- forecast_horizon : int, optional
Horizon length for multi-step forecasting. If not provided in
fixed_model_params, PiHALTuner will attempt to infer from the second dimension ofy['subs_pred']ory['gwl_pred'].
- quantiles : list[float], optional
List of quantiles (e.g., [0.1, 0.5, 0.9]) for probabilistic PINN training. If not given, defaults to those already in
fixed_model_params, or omitted if none.
- epochs : int, default ``10``
Number of training epochs for each model built during the search.
- batch_size : int, default ``32``
Batch size for converting NumPy arrays to tf.data.Dataset.
- callbacks : list[tf.keras.callbacks.Callback], optional
List of Keras callbacks (e.g., EarlyStopping) active during both the search and refit phases. If None, a sensible default EarlyStopping on validation loss is applied.
- case_info : dict[str, Any], optional
Dictionary of metadata to include in the tuner’s run case info. Used for logging/descriptions. Keys such as
"description"may be formatted with “Point” or “Quantile” based on whetherquantilesis provided.
- \*\*search_kwargs : Any
Additional keyword arguments forwarded to Keras Tuner’s search() method (e.g.,
tuner.search(train_data=..., validation_data=...,...)).
- returns:
(model, best_hps, tuner_oracle) –
model (tf.keras.Model): The best‐performing PIHALNet model retrained on the full training set with the champion hyperparameters.
best_hps (keras_tuner.HyperParameters): The winning hyperparameter configuration.
tuner_oracle (keras_tuner.Oracle): The underlying Keras Tuner object containing search history and trial results.
- rtype:
tuple
Examples
# 1) Create and run a tuning session using raw NumPy data: >>> import numpy as np >>> from fusionlab.nn.pinn.tuning import PiHALTuner >>> B, T, Sdim, Ddim, Fdim, O = 128, 12, 5, 3, 2, 1 >>> rng = np.random.default_rng(123) >>> inputs = { … “coords”: rng.normal(size=(B, 2)).astype(“float32”), … “static_features”: rng.normal(size=(B, Sdim)).astype(“float32”), … “dynamic_features”: rng.normal(size=(B, T, Ddim)).astype(“float32”), … “future_features”: rng.normal(size=(B, T, Fdim)).astype(“float32”), … } >>> targets = { … “subsidence”: rng.normal(size=(B, T, O)).astype(“float32”), … “gwl”: rng.normal(size=(B, T, O)).astype(“float32”), … } >>> fixed_params = { … “static_input_dim”: Sdim, … “dynamic_input_dim”: Ddim, … “future_input_dim”: Fdim, … “output_subsidence_dim”: O, … “output_gwl_dim”: O, … “forecast_horizon”: T, … “quantiles”: [0.1, 0.5, 0.9], … } >>> tuner = PiHALTuner( … fixed_model_params=fixed_params, … param_space={ … “learning_rate”: { … “min_value”: 1e-4, “max_value”: 1e-2, “sampling”: “log” … }, … “dropout_rate”: {“min_value”: 0.0, “max_value”: 0.5}, … “embed_dim”: {“min_value”: 16, “max_value”: 64, “step”: 16}, … }, … objective=”val_total_loss”, … max_trials=5, … tuner_type=”bayesianoptimization”, … verbose=2, … ) >>> best_model, best_hps, oracle = tuner.fit( … inputs=inputs, … y=targets, … validation_data=(inputs, targets), … epochs=3, … batch_size=32, … callbacks=None, … verbose=2, … )
# 2) Alternative: Use create() to infer dimensions automatically: >>> tuner2 = PiHALTuner.create( … inputs_data=inputs, … targets_data=targets, … forecast_horizon=None, # will be inferred as T=12 … quantiles=[0.05, 0.95], … param_space={“learning_rate”: lambda hp: hp.Float(“lr”, 1e-5, 1e-3, sampling=”log”)}, … objective=”val_total_loss”, … max_trials=3, … directory=”my_tuner_dir”, … verbose=1, … ) >>> best_model2, best_hps2, oracle2 = tuner2.fit( … inputs=inputs, … y=targets, … validation_data=(inputs, targets), … epochs=3, … batch_size=16, … )
See also
PINNTunerBaseBase class for PINN hyperparameter tuning; implements .search().
fusionlab.nn.pinn.models.PIHALNetThe core physics-informed neural network architecture being tuned.
References
- __init__(fixed_model_params, param_space=None, objective='val_loss', max_trials=20, project_name='PIHALNet_Tuning', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite_tuner=True, directory='pihalnet_tuner_results', **tuner_kwargs)[source]¶
Initialize the base class.
- Parameters:
verbose (
int, optional) – Verbosity level controlling logging (0 to 3). Defaults to 0.fixed_model_params (Dict[str, Any])
param_space (Dict[str, Any] | None)
objective (str | Objective)
max_trials (int)
project_name (str)
executions_per_trial (int)
tuner_type (str)
seed (int)
overwrite_tuner (bool)
directory (str)
Methods
__init__(fixed_model_params[, param_space, ...])Initialize the base class.
build(hp)Builds and compiles a PIHALNet model given a set of hyperparameters.
create([fixed_model_params, inputs_data, ...])Creates a PiHALTuner instance.
declare_hyperparameters(hp)fit(hp, model, *args, **kwargs)Train the model.
help(**kwargs)run(inputs, y[, validation_data, ...])Prepares data if needed, ensures fixed parameters are set, and runs hyperparameter search.
save([obj, file_path, format, encoding, ...])Save the object's data to a specified file in the desired format.
search(train_data, epochs[, ...])Performs the hyperparameter search using Keras Tuner.
Attributes
MAX_DISPLAY_ITEMS- __init__(fixed_model_params, param_space=None, objective='val_loss', max_trials=20, project_name='PIHALNet_Tuning', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite_tuner=True, directory='pihalnet_tuner_results', **tuner_kwargs)[source]¶
Initialize the base class.
- Parameters:
verbose (
int, optional) – Verbosity level controlling logging (0 to 3). Defaults to 0.fixed_model_params (Dict[str, Any])
param_space (Dict[str, Any] | None)
objective (str | Objective)
max_trials (int)
project_name (str)
executions_per_trial (int)
tuner_type (str)
seed (int)
overwrite_tuner (bool)
directory (str)
- classmethod create(fixed_model_params=None, inputs_data=None, targets_data=None, forecast_horizon=None, quantiles=None, objective='val_loss', max_trials=20, project_name='PIHALNet_Tuning_From_Config', directory='pihalnet_tuner_results', param_space=None, verbose=0, **tuner_init_kwargs)[source]¶
Creates a PiHALTuner instance.
Fixed model parameters for PIHALNet are determined with the following priority:
Values in fixed_model_params if provided.
Inferred from inputs_data and targets_data if provided.
Default values from DEFAULT_PIHALNET_FIXED_PARAMS.
After computing the final fixed_model_params, this method instantiates and returns a PiHALTuner with all required configuration for hyperparameter search.
- Parameters:
fixed_model_params (
Dict[str,Any], optional) – A complete dictionary of fixed parameters for PIHALNet. These typically include input/output dimensions (static, dynamic, future), output dimensions for subsidence and GWL, forecast_horizon, quantiles, etc. If not provided, inference occurs using inputs_data and targets_data, or defaults.inputs_data (
Dict[str,np.ndarray], optional) – Dictionary of NumPy arrays for model inputs. Used to infer dimensions if fixed_model_params is incomplete.targets_data (
Dict[str,np.ndarray], optional) – Dictionary of NumPy arrays for model targets. Used to infer output dimensions if fixed_model_params is incomplete.forecast_horizon (
int, optional) – Explicitly set forecast horizon. Used during inference if not already in fixed_model_params.quantiles (
List[float], optional) – Explicitly set quantiles for probabilistic forecasts. Used during inference if not already in fixed_model_params.objective (
strorkeras_tuner.Objective, optional) – The optimization metric name (e.g. “val_loss” or “val_total_loss”) that the tuner should optimize. Defaults to “val_loss”.max_trials (
int, optional) – The maximum number of hyperparameter combinations (trials) to explore. Defaults to 20.project_name (
str, optional) – Name of the tuner project folder under directory. Defaults to “PIHALNet_Tuning_From_Config”.directory (
str, optional) – Root directory where Keras Tuner stores results for this project. Defaults to “pihalnet_tuner_results”.param_space (
Dict[str,Any], optional) – A mapping from hyperparameter names to search-space definitions understood by Keras Tuner (e.g. hp.Choice, hp.Int, hp.Float). When None, the tuner will use the built-in default space defined in PiHALTuner.build().verbose (
int, default0) – Logging verbosity level. 0 = silent; 1 = info; >=2 = debug.**tuner_init_kwargs (
Any) – Additional keyword arguments forwarded to the PINNTunerBase constructor (e.g. executions_per_trial, tuner_type, seed, overwrite_tuner, etc.).
- Returns:
An instance of PiHALTuner with fixed_model_params fully populated and ready to run hyperparameter search.
- Return type:
Examples
>>> # Example: infer dimensions from data and create the tuner >>> inputs = { ... "coords": np.random.rand(100, 2, 3), ... "static_features": np.random.rand(100, 5), ... "dynamic_features": np.random.rand(100, 2, 4), ... "future_features": np.random.rand(100, 2, 1) ... } >>> targets = { ... "subsidence": np.random.rand(100, 2, 1), ... "gwl": np.random.rand(100, 2, 1) ... } >>> tuner = PiHALTuner.create( ... inputs_data=inputs, ... targets_data=targets, ... forecast_horizon=2, ... quantiles=[0.1, 0.5, 0.9], ... max_trials=5, ... project_name="zh_config_test", ... tuner_type="bayesian", ... verbose=1 ... )
- build(hp)[source]¶
Builds and compiles a PIHALNet model given a set of hyperparameters.
This method assumes that self.fixed_model_params has already been populated (either in __init__ or via a prior run()/fit() call). It will:
Verify that all required fixed parameters (e.g., “dynamic_input_dim”) exist.
Extract architecture‐related hyperparameters from hp (e.g., embed_dim, hidden_units, LSTM units, attention units, etc.).
Extract PINN‐specific hyperparameters (e.g., pde_mode, whether to learn or fix coefficient \(C\), PDE weight lambda_pde, learning rate).
Merge the hyperparameters with self.fixed_model_params, discarding any unexpected keys via _get_valid_kwargs.
Instantiate PIHALNet(**model_params).
Compile with an Adam optimizer (clipping gradients at norm = 1.0), two separate MSE losses (subs_pred vs. gwl_pred), and their corresponding MAE metrics. Loss weights default to {“subs_pred”: 1.0, “gwl_pred”: 0.8} if not provided in fixed_model_params.
Return the compiled tf.keras.Model.
- Parameters:
hp (
keras_tuner.HyperParameters) –A HyperParameters instance provided by Keras Tuner containing values for:
embed_dim (int between 16 and 64, step 16)
hidden_units (int between 32 and 128, step 32)
lstm_units (int between 32 and 128, step 32)
attention_units (int between 32 and 128, step 32)
num_heads (choice among [1, 2, 4])
dropout_rate (float between 0.0 and 0.3)
activation (choice among [“relu”,”gelu”])
use_vsn (boolean)
vsn_units (int between max(16, hidden_units//4) and hidden_units if use_vsn=True)
pde_mode (choice among [“consolidation”,”none”])
pinn_coefficient_C_type (choice among [“learnable”,”fixed”])
pinn_coefficient_C_value (float between 1e–5 and 1e–1 if pinn_coefficient_C_type=”fixed”)
lambda_pde (float between 0.01 and 1.0)
learning_rate (choice among [1e–3, 5e–4, 1e–4])
- Returns:
A compiled PIHALNet instance, ready for training. The model’s compile() call uses:
optimizer: Adam(learning_rate=<chosen>, clipnorm=1.0)
loss: {‘subs_pred’: MSE(name=”subs_data_loss”), ‘gwl_pred’: MSE(name=”gwl_data_loss”)}
metrics: {‘subs_pred’: [MAE(name=”subs_mae”)], ‘gwl_pred’: [MAE(name=”gwl_mae”)]}
loss_weights: as given in self.fixed_model_params[“loss_weights”] or {“subs_pred”: 1.0, “gwl_pred”: 0.8} by default
lambda_pde: the PDE‐weight hyperparameter
- Return type:
tf.keras.Model- Raises:
RuntimeError – If self.fixed_model_params is empty or missing “dynamic_input_dim”, indicating that the tuner has not yet inferred or been given fixed dimensions.
- run(inputs, y, validation_data=None, forecast_horizon=None, quantiles=None, epochs=10, batch_size=32, callbacks=None, verbose=1, case_info=None, **search_kwargs)[source]¶
Prepares data if needed, ensures fixed parameters are set, and runs hyperparameter search.
- Steps:
Logs a message indicating the start of fit() for this tuner.
If self.fixed_model_params is empty, or missing any of [“static_input_dim”,”dynamic_input_dim”,”future_input_dim”, “output_subsidence_dim”,”output_gwl_dim”,”forecast_horizon”], call _infer_dims_and_prepare_fixed_params(…):
Uses inputs, y, plus any explicitly given forecast_horizon or quantiles to fill in missing dimensions (static, dynamic, future, output dims) and other defaults from DEFAULT_PIHALNET_FIXED_PARAMS.
Updates self.fixed_model_params in‐place.
Logs (at debug/verbose ≥3) all final entries in self.fixed_model_params.
- Renames target keys:
Validates that y contains keys “subsidence” and “gwl” (or already “subs_pred”, “gwl_pred”) via check_required_input_keys.
Calls rename_dict_keys(y, {“subsidence”: “subs_pred”, “gwl”: “gwl_pred”}).
- Constructs tf.data.Dataset for training:
train_dataset = Dataset.from_tensor_slices((inputs, {‘subs_pred’: …,’gwl_pred’: …}))
Batch by batch_size and .prefetch(AUTOTUNE).
- If validation_data is provided:
Unpack into (val_inputs, val_targets).
Rename val_targets similarly.
Create val_dataset = Dataset.from_tensor_slices((val_inputs, {‘subs_pred’: …,’gwl_pred’: …})) with same batching/prefetch.
Prepare self._current_run_case_info by copying DEFAULT_PIHAL_CASE_INFO, updating with self.fixed_model_params, and formatting the “description” field (inserting “Quantile” vs. “Point” depending on quantiles). If the user passed case_info, merge those keys last.
- Call super().search(…) with:
train_data=train_dataset
validation_data=val_dataset
epochs=epochs
callbacks=callbacks
verbose=verbose
Any additional **search_kwargs (e.g., max_trials, project_name, directory, etc., are already set on the tuner object)
Return whatever super().search(…) returns (typically best model, best HP, and tuner instance).
- Parameters:
inputs (
Dict[str,np.ndarray]) – A dictionary of NumPy arrays for model inputs. Keys must match the input‐layer names expected by PIHALNet (e.g., “coords”, “static_features”, “dynamic_features”, “future_features”, etc.).y (
Dict[str,np.ndarray]) –- A dictionary of NumPy arrays for targets. Expected keys:
”subsidence” and “gwl” if not already renamed, or
”subs_pred” and “gwl_pred” if already in model format.
Values must be arrays of shape (batch_size, …, 1) matching the output dimensions.
validation_data (
Optional[) – Tuple[Dict[str, np.ndarray],Dict[str, np.ndarray]]] – If provided, a tuple (val_inputs, val_targets), with the same key conventions as inputs and y. If None, no validation set is used.
default=None – If provided, a tuple (val_inputs, val_targets), with the same key conventions as inputs and y. If None, no validation set is used.
forecast_horizon (
Optional[int], defaultNone) – The number of time‐steps ahead the model predicts. Used only if self.fixed_model_params still lacks “forecast_horizon” and must be inferred.quantiles (
Optional[List[float]], defaultNone) – If using quantile predictions, the list of quantiles. Used only if self.fixed_model_params lacks “quantiles” and must be inferred.epochs (
int, default10) – The maximum number of epochs to train each trial during the search.batch_size (
int, default32) – Batch size for both training and validation datasets.callbacks (
Optional[List[tf.keras.callbacks.Callback]],) – default=None List of Keras callbacks (e.g., EarlyStopping) to apply during each trial. If None, no additional callbacks are used.verbose (
int, default1) – Verbosity mode. 0 = silent; 1 = progress bars; ≥2 = debug/log.case_info (
Optional[Dict[str,Any]], defaultNone) – Additional metadata (strings, numbers) to merge into self._current_run_case_info, which is ultimately saved in the tuner’s summary JSON. Common keys include “description”, “run_id”, etc.**search_kwargs (
Any) – Additional keyword arguments forwarded to KerasTuner.search(…), such as max_trials, project_name, directory, etc. All other tuning configuration (e.g., tuner_type, executions_per_trial) should already be set on the tuner instance.
- Returns:
The return value of super().search(…), which for Keras Tuner is typically a tuple (best_model, best_hyperparameters, tuner_instance).
- Return type:
Any- Raises:
RuntimeError – If self.fixed_model_params cannot be inferred (e.g. missing critical dimensions and no forecast_horizon/quantiles provided).
ValueError – If required target keys are missing in y (after attempting to rename).
Notes
This method replaces the usual fit(…) interface; users should call PiHALTuner.run(…) (or tuner.fit(…) if aliased) instead of directly calling search(…).
After this returns, self.best_hps_, self.best_model_, etc. are populated and self._save_tuning_summary() is called internally.
Examples
>>> # Suppose `inputs_train` and `targets_train` are dicts of NumPy >>> # arrays: >>> tuner = PiHALTuner( ... fixed_model_params={'static_input_dim': 5, ... 'dynamic_input_dim': 4, ... 'future_input_dim': 1, ... 'output_subsidence_dim': 1, ... 'output_gwl_dim': 1, ... 'forecast_horizon': 3}, ... max_trials=10, ... project_name="zh_tuning", ... tuner_type="bayesian" ... ) >>> best_model, best_hps, tuner_obj = tuner.run( ... inputs=inputs_train, ... y={'subsidence': subs_arr, 'gwl': gwl_arr}, ... validation_data=(inputs_val, ... {'subsidence': subs_val, 'gwl': gwl_val}), ... epochs=20, ... batch_size=64, ... callbacks=[tf.keras.callbacks.EarlyStopping(patience=5)], ... verbose=2 ... )
- help(**kwargs)¶
- my_params = PiHALTuner( fixed_model_params, param_space=None, objective='val_loss', max_trials=20, project_name='PIHALNet_Tuning', executions_per_trial=1, tuner_type='randomsearch', seed=None, overwrite_tuner=True, directory='pihalnet_tuner_results' )¶