Skip to content

Bandwidth selection

This page documents 5 public symbols. Each entry includes its purpose, import path, full API docstring, and the maintained example that exercises it.

Conceptual guide

BandwidthSelector

Abstract base class for bandwidth selection methods.

Property Value
Type class
Import from pygwrx.core import BandwidthSelector
Signature BandwidthSelector()
Maintained example examples/core/07_bandwidth_selectors.py

BandwidthSelector

Bases: ABC

Abstract base class for bandwidth selection methods.

select abstractmethod

select(
    X: ndarray,
    y: ndarray,
    coords: ndarray,
    kernel_func: KernelFunction,
    bandwidth_range: BandwidthRange = None,
    distance_metric: str = "euclidean",
) -> Bandwidth

Select an optimal fixed-distance or adaptive integer bandwidth.

Source code in src/pygwrx/core/bandwidth.py
@abstractmethod
def select(
    self,
    X: np.ndarray,
    y: np.ndarray,
    coords: np.ndarray,
    kernel_func: KernelFunction,
    bandwidth_range: BandwidthRange = None,
    distance_metric: str = "euclidean",
) -> Bandwidth:
    """Select an optimal fixed-distance or adaptive integer bandwidth."""
    raise NotImplementedError

CrossValidationSelector

Select bandwidth by strict leave-one-out squared prediction error.

Property Value
Type class
Import from pygwrx.core import CrossValidationSelector
Signature CrossValidationSelector(n_intervals: 'int' = 20, optimization_method: 'str' = 'golden_section', adaptive: 'bool' = False, verbose: 'bool' = False) -> 'None'
Maintained example examples/core/07_bandwidth_selectors.py

CrossValidationSelector

CrossValidationSelector(
    n_intervals: int = 20,
    optimization_method: str = "golden_section",
    adaptive: bool = False,
    verbose: bool = False,
)

Bases: _BaseSelector

Select bandwidth by strict leave-one-out squared prediction error.

Source code in src/pygwrx/core/bandwidth.py
def __init__(
    self,
    n_intervals: int = 20,
    optimization_method: str = "golden_section",
    adaptive: bool = False,
    verbose: bool = False,
) -> None:
    self.n_intervals = _validate_positive_int(n_intervals, "n_intervals", minimum=2)
    self.adaptive = _validate_bool(adaptive, "adaptive")
    self.verbose = _validate_bool(verbose, "verbose")

    if not isinstance(optimization_method, str):
        raise TypeError("optimization_method must be a string.")
    optimization_method = optimization_method.strip().lower()
    if optimization_method not in {"grid", "golden_section", "brent"}:
        raise ValueError(
            "optimization_method must be 'grid', 'golden_section', or 'brent'; "
            f"got {optimization_method!r}."
        )
    self.optimization_method = optimization_method

AICSelector

Select bandwidth using Gaussian GWR AIC or AICc.

Property Value
Type class
Import from pygwrx.core import AICSelector
Signature AICSelector(n_intervals: 'int' = 20, corrected: 'bool' = True, adaptive: 'bool' = False, optimization_method: 'str' = 'golden_section', verbose: 'bool' = False) -> 'None'
Maintained example examples/core/07_bandwidth_selectors.py

AICSelector

AICSelector(
    n_intervals: int = 20,
    corrected: bool = True,
    adaptive: bool = False,
    optimization_method: str = "golden_section",
    verbose: bool = False,
)

Bases: _BaseSelector

Select bandwidth using Gaussian GWR AIC or AICc.

Source code in src/pygwrx/core/bandwidth.py
def __init__(
    self,
    n_intervals: int = 20,
    corrected: bool = True,
    adaptive: bool = False,
    optimization_method: str = "golden_section",
    verbose: bool = False,
) -> None:
    super().__init__(
        n_intervals=n_intervals,
        optimization_method=optimization_method,
        adaptive=adaptive,
        verbose=verbose,
    )
    self.corrected = _validate_bool(corrected, "corrected")

BICSelector

Select bandwidth using Gaussian GWR BIC.

Property Value
Type class
Import from pygwrx.core import BICSelector
Signature BICSelector(n_intervals: 'int' = 20, optimization_method: 'str' = 'golden_section', adaptive: 'bool' = False, verbose: 'bool' = False) -> 'None'
Maintained example examples/core/07_bandwidth_selectors.py

BICSelector

BICSelector(
    n_intervals: int = 20,
    optimization_method: str = "golden_section",
    adaptive: bool = False,
    verbose: bool = False,
)

Bases: _BaseSelector

Select bandwidth using Gaussian GWR BIC.

Source code in src/pygwrx/core/bandwidth.py
def __init__(
    self,
    n_intervals: int = 20,
    optimization_method: str = "golden_section",
    adaptive: bool = False,
    verbose: bool = False,
) -> None:
    self.n_intervals = _validate_positive_int(n_intervals, "n_intervals", minimum=2)
    self.adaptive = _validate_bool(adaptive, "adaptive")
    self.verbose = _validate_bool(verbose, "verbose")

    if not isinstance(optimization_method, str):
        raise TypeError("optimization_method must be a string.")
    optimization_method = optimization_method.strip().lower()
    if optimization_method not in {"grid", "golden_section", "brent"}:
        raise ValueError(
            "optimization_method must be 'grid', 'golden_section', or 'brent'; "
            f"got {optimization_method!r}."
        )
    self.optimization_method = optimization_method

get_bandwidth_selector

Create a bandwidth selector by method name.

Property Value
Type function
Import from pygwrx.core import get_bandwidth_selector
Signature get_bandwidth_selector(method: 'str', **kwargs) -> 'BandwidthSelector'
Maintained example examples/core/07_bandwidth_selectors.py

get_bandwidth_selector

get_bandwidth_selector(
    method: str, **kwargs
) -> BandwidthSelector

Create a bandwidth selector by method name.

Constructor parameters belong in kwargs. Search-time parameters such as bandwidth_range and distance_metric must be supplied to select().

Source code in src/pygwrx/core/bandwidth.py
def get_bandwidth_selector(method: str, **kwargs) -> BandwidthSelector:
    """Create a bandwidth selector by method name.

    Constructor parameters belong in ``kwargs``.  Search-time parameters such as
    ``bandwidth_range`` and ``distance_metric`` must be supplied to ``select()``.
    """
    if not isinstance(method, str):
        raise TypeError("method must be a string.")

    method_name = method.strip().lower()
    if method_name not in BANDWIDTH_SELECTORS:
        available = ", ".join(sorted(BANDWIDTH_SELECTORS))
        raise ValueError(
            f"Unknown bandwidth selection method: {method!r}. "
            f"Available methods: {available}."
        )

    if method_name in {"aic", "aicc"}:
        expected_corrected = method_name == "aicc"
        if "corrected" in kwargs:
            supplied = _validate_bool(kwargs.pop("corrected"), "corrected")
            if supplied != expected_corrected:
                raise ValueError(
                    f"method={method_name!r} conflicts with corrected={supplied}."
                )
        return AICSelector(corrected=expected_corrected, **kwargs)

    selector_class = BANDWIDTH_SELECTORS[method_name]
    return selector_class(**kwargs)

Runnable examples used on this page

examples/core/07_bandwidth_selectors.py
# SPDX-FileCopyrightText: 2026 Jinghao Hu
# SPDX-License-Identifier: MIT

"""Select bandwidths with CV, AIC/AICc, and BIC selectors."""

# Allow this script to run directly from any working directory.
import sys
from pathlib import Path

_PROJECT_ROOT = Path(__file__).resolve().parents[2]
_EXAMPLES_ROOT = _PROJECT_ROOT / "examples"
_SRC_ROOT = _PROJECT_ROOT / "src"
for _path in (_SRC_ROOT, _EXAMPLES_ROOT):
    if str(_path) not in sys.path:
        sys.path.insert(0, str(_path))

import numpy as np
from _common import spatial_regression

from pygwrx.core import (
    AICSelector,
    BandwidthSelector,
    BICSelector,
    CrossValidationSelector,
    gaussian_kernel,
    get_bandwidth_selector,
)

X, y, coords = spatial_regression(n=28, p=2)
Xa, ya, ca = X.to_numpy(), np.asarray(y), coords.to_numpy()
selectors = [
    CrossValidationSelector(n_intervals=5, adaptive=True, verbose=False),
    AICSelector(n_intervals=5, corrected=False, adaptive=True, verbose=False),
    AICSelector(n_intervals=5, corrected=True, adaptive=True, verbose=False),
    BICSelector(n_intervals=5, adaptive=True, verbose=False),
]
for selector in selectors:
    print(
        type(selector).__name__,
        selector.select(Xa, ya, ca, gaussian_kernel, bandwidth_range=(10, 18)),
    )
print("factory=", type(get_bandwidth_selector("aicc", adaptive=True)).__name__)
print("abstract_base=", BandwidthSelector)