Skip to content

Weight diagnostics

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

Conceptual guide

WeightComponents

Named weight matrices exposed by a fitted model.

Property Value
Type class
Import from pygwrx.diagnostics import WeightComponents
Signature WeightComponents(components: 'Mapping[str, np.ndarray]', combined_name: 'Optional[str]') -> None
Maintained example examples/diagnostics/04_weight_diagnostics.py

WeightComponents dataclass

WeightComponents(
    components: Mapping[str, ndarray],
    combined_name: Optional[str],
)

Named weight matrices exposed by a fitted model.

combined property

combined: Optional[ndarray]

Return the combined matrix when one is available.

focus_weight_components

Return one row from every stored weight component.

Property Value
Type function
Import from pygwrx.diagnostics import focus_weight_components
Signature focus_weight_components(model: 'Any', focus: 'int') -> 'Dict[str, np.ndarray]'
Maintained example examples/diagnostics/04_weight_diagnostics.py

focus_weight_components

focus_weight_components(
    model: Any, focus: int
) -> Dict[str, np.ndarray]

Return one row from every stored weight component.

Source code in src/pygwrx/diagnostics/weights.py
def focus_weight_components(model: Any, focus: int) -> Dict[str, np.ndarray]:
    """Return one row from every stored weight component."""
    collection = weight_components(model)
    if not isinstance(focus, (int, np.integer)) or isinstance(focus, (bool, np.bool_)):
        raise TypeError("focus must be an integer row index.")
    index = int(focus)
    row_count = next(iter(collection.components.values())).shape[0]
    if index < 0 or index >= row_count:
        raise IndexError(f"focus must be in [0, {row_count - 1}].")
    output = {}
    for name, matrix in collection.components.items():
        if matrix.shape[0] != row_count:
            raise ValueError("Stored weight matrices have inconsistent row counts.")
        output[name] = matrix[index].copy()
    return output

weight_components

Collect stored weight matrices using stable semantic names.

Property Value
Type function
Import from pygwrx.diagnostics import weight_components
Signature weight_components(model: 'Any') -> 'WeightComponents'
Maintained example examples/diagnostics/04_weight_diagnostics.py

weight_components

weight_components(model: Any) -> WeightComponents

Collect stored weight matrices using stable semantic names.

Source code in src/pygwrx/diagnostics/weights.py
def weight_components(model: Any) -> WeightComponents:
    """Collect stored weight matrices using stable semantic names."""
    require_fitted(model)
    candidates = (
        ("spatial", "spatial_weights_"),
        ("temporal", "temporal_weights_"),
        ("spatiotemporal", "spatiotemporal_weights_"),
        ("similarity", "similarity_weights_"),
        ("combined", "combined_weights_"),
        ("weights", "weights_"),
    )
    components: Dict[str, np.ndarray] = {}
    for label, attribute in candidates:
        value = getattr(model, attribute, None)
        if value is None:
            continue
        array = np.asarray(value, dtype=float)
        if array.ndim != 2 or 0 in array.shape:
            continue
        if not np.all(np.isfinite(array)) or np.any(array < 0.0):
            raise ValueError(f"{attribute} must be a finite non-negative matrix.")
        components[label] = array
    if not components:
        raise ValueError(
            f"{model.__class__.__name__} does not store weight matrices. Refit with store_weights=True when supported."
        )
    combined_name = None
    for name in ("combined", "weights", "spatiotemporal", "spatial"):
        if name in components:
            combined_name = name
            break
    return WeightComponents(components=components, combined_name=combined_name)

Runnable examples used on this page

examples/diagnostics/04_weight_diagnostics.py
# SPDX-FileCopyrightText: 2026 Jinghao Hu
# SPDX-License-Identifier: MIT

"""Inspect spatial, similarity, temporal, and combined weight components."""

# 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))

from _common import spatial_regression, temporal_regression

from pygwrx import SGTWR, SGWR
from pygwrx.diagnostics import (
    WeightComponents,
    focus_weight_components,
    weight_components,
)

X, y, coords = spatial_regression(n=40, p=2)
sgwr = SGWR(bandwidth=20, adaptive=True, alpha=0.45, store_weights=True).fit(
    X, y, coords
)
components = weight_components(sgwr)
assert isinstance(components, WeightComponents)
print("sgwr_components=", sorted(components.components))
print("sgwr_focus=", {k: v[:5] for k, v in focus_weight_components(sgwr, 3).items()})

Xt, yt, coordst, times = temporal_regression(n=40, p=2)
sgtwr = SGTWR(
    spatial_bandwidth=20,
    temporal_bandwidth=2.0,
    adaptive=True,
    alpha=0.5,
    store_weights=True,
).fit(Xt, yt, coordst, times)
print("sgtwr_components=", sorted(weight_components(sgtwr).components))