gpclarity.HyperparameterTracker
Constructor
- gpclarity.hyperparam_tracker.__init__(model)
Initialize tracker with GP model.
- Parameters:
model (Any) – GPy model or compatible object with
.parametersattribute and.optimize()method- Raises:
TrackingError – If model lacks required attributes
Example:
import GPy from gpclarity.hyperparam_tracker import HyperparameterTracker kernel = GPy.kern.RBF(input_dim=1) model = GPy.models.GPRegression(X_train, y_train, kernel) tracker = HyperparameterTracker(model)
Properties
- gpclarity.hyperparam_tracker.history: Dict[str, List[float]]
Dictionary mapping parameter names to lists of values across iterations.
Example:
hist = tracker.history lengthscale_values = hist['rbf_lengthscale'] import matplotlib.pyplot as plt plt.plot(lengthscale_values) plt.xlabel('Iteration') plt.ylabel('Lengthscale')
Methods
- gpclarity.hyperparam_tracker.record_state(iteration=None) OptimizationState
Snapshot current hyperparameter values.
Returns an
OptimizationStatedataclass with these attributes:iteration(int): Iteration numberparameters(Dict[str, Union[float, np.ndarray]]): Parameter valueslog_likelihood(Optional[float]): Model log-likelihoodgradient_norm(Optional[float]): L2 norm of gradienttimestamp(float): Wall clock time
- Parameters:
iteration (int, optional) – Iteration number. Auto-incremented if None.
- Returns:
Recorded state
- Return type:
OptimizationState
Example:
state = tracker.record_state() print(f"Iter {state.iteration}: LL={state.log_likelihood:.3f}") print(f"Parameters: {state.parameters}")
- gpclarity.hyperparam_tracker.wrapped_optimize(max_iters=100, callback=None, capture_every=1, convergence_tolerance=1e-6, patience=10, **optimize_kwargs) Dict[str, List[float]]
Perform optimization with intelligent tracking and early stopping.
- Parameters:
max_iters (int) – Maximum optimization iterations. Default:
100callback (Callable, optional) – Optional callback function called each iteration with
(model, iteration, history)capture_every (int) – Record state every N iterations. Default:
1convergence_tolerance (float) – Minimum log-likelihood improvement for convergence. Default:
1e-6patience (int) – Iterations without improvement before early stopping. Default:
10optimize_kwargs – Additional arguments passed to
model.optimize()
- Returns:
Optimization history as dictionary
- Return type:
- Raises:
OptimizationError – If optimization fails
Example:
# Basic usage with early stopping history = tracker.wrapped_optimize( max_iters=200, patience=20, convergence_tolerance=1e-4 ) # With callback def callback(model, iteration, history): if iteration % 10 == 0: print(f"Iter {iteration}: LL={history[-1].log_likelihood:.2f}") history = tracker.wrapped_optimize(max_iters=100, callback=callback)
- gpclarity.hyperparam_tracker.get_parameter_trajectory(param_name) Tuple[np.ndarray, np.ndarray]
Extract time-series data for a specific parameter.
- Parameters:
param_name (str) – Name of parameter to extract
- Returns:
Tuple of
(iterations, values)- Return type:
- Raises:
KeyError – If parameter not found
TrackingError – If no history recorded
Example:
iters, values = tracker.get_parameter_trajectory('rbf_lengthscale') plt.plot(iters, values) plt.xlabel('Iteration') plt.ylabel('Lengthscale')
- gpclarity.hyperparam_tracker.get_convergence_report(window=10, convergence_threshold=0.01) Dict[str, Dict]
Analyze parameter convergence with statistical rigor.
Returns convergence metrics for each parameter. The metrics dictionary contains:
initial_mean(float): Mean over first windowfinal_mean(float): Mean over last windowrelative_change(float): Relative change between windowsfinal_std(float): Standard deviation over last windowcoefficient_of_variation(float): CV = std / meanis_converged(bool): Whether CV < thresholdconverged(bool): Alias for is_convergedtrend_direction(str): ‘increasing’, ‘decreasing’, or ‘stable’
- Parameters:
- Returns:
Dictionary mapping parameter names to convergence metrics
- Return type:
Dict[str, Dict]
- Raises:
TrackingError – If insufficient history
Example:
report = tracker.get_convergence_report(window=20) for param, metrics in report.items(): if metrics['converged']: print(f"✓ {param} converged to {metrics['final_mean']:.4f}") else: print(f"✗ {param} still {metrics['trend_direction']}")
- gpclarity.hyperparam_tracker.detect_optimization_issues() Dict[str, Any]
Detect common optimization problems.
- Returns:
Dictionary with
warnings,recommendations, andmetrics- Return type:
Dict[str, Any]
Example:
issues = tracker.detect_optimization_issues() for warning in issues['warnings']: print(f"⚠️ {warning}") for rec in issues['recommendations']: print(f"💡 {rec}")
- gpclarity.hyperparam_tracker.plot_evolution(params=None, figsize=None, show_convergence=True, show_ll=True, n_cols=2) plt.Figure
Plot parameter trajectories with optional convergence indicators.
- Parameters:
params (List[str], optional) – List of parameter names to plot. All if None.
figsize (Tuple[float, float], optional) – Figure size as
(width, height)show_convergence (bool) – Whether to show convergence bands. Default:
Trueshow_ll (bool) – Whether to show log-likelihood subplot. Default:
Truen_cols (int) – Number of columns in subplot grid. Default:
2
- Returns:
Matplotlib figure object
- Return type:
plt.Figure
- Raises:
TrackingError – If no history recorded
Example:
fig = tracker.plot_evolution( params=['rbf_lengthscale', 'rbf_variance'], show_convergence=True, n_cols=2 ) plt.show()
- gpclarity.hyperparam_tracker.to_dataframe() pd.DataFrame
Export history to pandas DataFrame for analysis.
- Returns:
DataFrame with columns:
iteration,log_likelihood,gradient_norm,timestamp, plus parameter columns- Return type:
pd.DataFrame
- Raises:
ImportError – If pandas not installed
Example:
df = tracker.to_dataframe() # Analyze specific parameter print(df['rbf_lengthscale'].describe()) # Export to CSV df.to_csv('optimization_history.csv', index=False)