pod.optimise_bandwidth

optimise_bandwidth(X, residuals, min_ratio=0.01, max_ratio=0.5)

Finds the optimal kernel smoothing bandwidth using Leave-One-Out Cross-Validation (LOO-CV).

This function automatically determines the best smoothing window (sigma) for the variance model. It evaluates different bandwidths by predicting the squared residual of each point using a Gaussian weighted average of all other points, selecting the bandwidth that minimizes the Mean Squared Error (MSE) of these predictions.

Parameters

Name Type Description Default
X np.ndarray A 1D array of the original input locations (e.g., flaw sizes). required
residuals np.ndarray The raw residuals calculated from the mean model (differences between observed y and predicted mean y). required
min_ratio float The lower bound for the optimizer’s search space, as a fraction of the largest range of the standardised inputs. Defaults to 0.01. 0.01
max_ratio float The upper bound for the optimizer’s search space, as a fraction of the same range. Defaults to 0.5. 0.5

Returns

Name Type Description
float float The optimal smoothing bandwidth, in standard deviations of the inputs
float (the units predict_local_std expects).

Examples

import numpy as np

# 1. Generate dummy input data and simulated residuals
X = np.linspace(0, 10, 50)
# Simulate heteroscedastic noise (variance increases with X)
residuals = np.random.normal(0, X * 0.5, size=50)

# 2. Find the optimal bandwidth
optimal_bw = optimise_bandwidth(X, residuals)
print(f"Optimal Bandwidth: {optimal_bw:.4f}")