GWGLM¶
This page documents 2 public symbols. Each entry includes its purpose, import path, full API docstring, and the maintained example that exercises it.
GWGLM¶
Geographically weighted generalized linear model.
| Property | Value |
|---|---|
| Type | class |
| Import | from pygwrx.models import GWGLM |
| Signature | GWGLM(family: 'FamilyName' = 'gaussian', kernel: 'KernelLike' = 'bisquare', bandwidth: 'BandwidthLike' = 'cv', bandwidth_method: 'str' = 'aicc', adaptive: 'bool' = False, bandwidth_range: 'Optional[Tuple[float, float]]' = None, optimization_method: 'str' = 'golden_section', max_iter: 'int' = 100, tol: 'float' = 1e-06, fit_intercept: 'bool' = True, distance_metric: 'str' = 'euclidean', sigma2_v1: 'bool' = True, verbose: 'bool' = False) -> 'None' |
| Maintained example | examples/models/06_gwglm.py |
GWGLM ¶
GWGLM(
family: FamilyName = "gaussian",
kernel: KernelLike = "bisquare",
bandwidth: BandwidthLike = "cv",
bandwidth_method: str = "aicc",
adaptive: bool = False,
bandwidth_range: Optional[Tuple[float, float]] = None,
optimization_method: str = "golden_section",
max_iter: int = 100,
tol: float = 1e-06,
fit_intercept: bool = True,
distance_metric: str = "euclidean",
sigma2_v1: bool = True,
verbose: bool = False,
)
Bases: GWR
Geographically weighted generalized linear model.
The estimator supports three canonical families:
"gaussian"with an identity link;"poisson"with a log link and optional exposure or log-offset;"binomial"for Bernoulli responses with a logit link.
Poisson and Binomial models are fitted independently at each regression location by local iteratively weighted least squares (IWLS). Spatial kernel weights and GLM working weights are multiplied inside each local fit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
family
|
FamilyName
|
Response distribution. Supported values are |
'gaussian'
|
kernel
|
KernelLike
|
Spatial kernel name or callable. |
'bisquare'
|
bandwidth
|
BandwidthLike
|
Numeric bandwidth or automatic-selection criterion. A fixed bandwidth is a distance; an adaptive bandwidth is a neighbour count. |
'cv'
|
bandwidth_method
|
str
|
Selection criterion used when |
'aicc'
|
adaptive
|
bool
|
Whether the bandwidth represents nearest-neighbour count. |
False
|
bandwidth_range
|
Optional[Tuple[float, float]]
|
Optional lower and upper search bounds. |
None
|
optimization_method
|
str
|
|
'golden_section'
|
max_iter
|
int
|
Maximum IWLS iterations per local model. |
100
|
tol
|
float
|
IWLS convergence tolerance. |
1e-06
|
fit_intercept
|
bool
|
Whether to include a local intercept. |
True
|
distance_metric
|
str
|
Distance metric used by the spatial kernel. |
'euclidean'
|
sigma2_v1
|
bool
|
Gaussian residual-variance convention inherited from GWR. |
True
|
verbose
|
bool
|
Whether to print fitting and bandwidth-search progress. |
False
|
Attributes:
| Name | Type | Description |
|---|---|---|
family_ |
Normalized fitted family name. |
|
bandwidth_ |
Selected or user-specified bandwidth. |
|
coef_ |
Local slope coefficients. |
|
intercept_ |
Local intercepts. |
|
fitted_values_ |
Fitted conditional means. |
|
linear_predictor_ |
Fitted values on the link scale. |
|
residuals_ |
Response residuals |
|
deviance_residuals_ |
Signed deviance residuals. |
|
pearson_residuals_ |
Pearson residuals. |
|
parameter_standard_errors_ |
Local parameter standard errors. |
|
parameter_z_values_ |
Local Wald z statistics for non-Gaussian models. |
|
iteration_counts_ |
Number of IWLS iterations at each location. |
|
converged_ |
Whether every local IWLS fit converged. |
|
exposure_train_ |
Poisson exposure used during fitting. |
Notes
offset in :meth:fit and :meth:predict is an additive offset on
the linear-predictor scale. For Poisson models it is equivalent to
log(exposure). Supply at most one of exposure and offset.
Grouped-binomial responses are intentionally not accepted. The current
Binomial implementation is Bernoulli only and requires values in
{0, 1}.
References
Nakaya, T., Fotheringham, A. S., Brunsdon, C., and Charlton, M. (2005). Geographically weighted Poisson regression for disease association mapping. Statistics in Medicine, 24, 2695-2717.
Oshan, T. M., Li, Z., Kang, W., Wolf, L. J., and Fotheringham, A. S. (2019). mgwr: A Python implementation of multiscale geographically weighted regression for investigating process spatial heterogeneity and scale. ISPRS International Journal of Geo-Information, 8, 269.
Source code in src/pygwrx/models/glm_gwr.py
fit ¶
fit(
X: ArrayLike,
y: ArrayLike,
coords: ArrayLike,
*,
exposure: Optional[object] = None,
offset: Optional[object] = None,
compute_hat_matrix: bool = False,
compute_inference: bool = True,
compute_local_r2: bool = True
) -> "GWGLM"
Fit the geographically weighted generalized linear model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ArrayLike
|
Predictor matrix with shape |
required |
y
|
ArrayLike
|
Response vector. Poisson values must be non-negative; Binomial
values must be Bernoulli outcomes in |
required |
coords
|
ArrayLike
|
Spatial coordinates with shape |
required |
exposure
|
Optional[object]
|
Positive Poisson exposure. Scalar values are broadcast. |
None
|
offset
|
Optional[object]
|
Poisson log-exposure offset. Supply at most one of exposure and offset. |
None
|
compute_hat_matrix
|
bool
|
Whether to retain the full local smoother matrix. |
False
|
compute_inference
|
bool
|
Whether to compute local standard errors and Wald statistics. Non-Gaussian diagnostics still retain trace statistics. |
True
|
compute_local_r2
|
bool
|
Gaussian-only option forwarded to standard GWR. |
True
|
Returns:
| Type | Description |
|---|---|
'GWGLM'
|
The fitted estimator. |
Source code in src/pygwrx/models/glm_gwr.py
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 | |
predict ¶
predict(
X: ArrayLike,
coords: ArrayLike,
*,
exposure: Optional[object] = None,
offset: Optional[object] = None
) -> np.ndarray
Predict conditional means at target locations.
Source code in src/pygwrx/models/glm_gwr.py
predict_result ¶
predict_result(
X: ArrayLike,
coords: ArrayLike,
*,
exposure: Optional[object] = None,
offset: Optional[object] = None
) -> Union[GWGLMPredictionResult, GWRPredictionResult]
Return predictions, local parameters, and optional inference results.
Source code in src/pygwrx/models/glm_gwr.py
score ¶
score(
X: ArrayLike,
y: ArrayLike,
coords: ArrayLike,
*,
exposure: Optional[object] = None,
offset: Optional[object] = None
) -> float
Return R² for Gaussian models or deviance explained otherwise.
Source code in src/pygwrx/models/glm_gwr.py
to_frame ¶
Return training-location parameters and GLM diagnostics.
Source code in src/pygwrx/models/glm_gwr.py
summary ¶
Return a stable text summary of GWGLM results.
Source code in src/pygwrx/models/glm_gwr.py
GWGLMPredictionResult¶
Rich prediction result returned by :meth:GWGLM.predict_result.
| Property | Value |
|---|---|
| Type | class |
| Import | from pygwrx.models import GWGLMPredictionResult |
| Signature | GWGLMPredictionResult(predictions: 'np.ndarray', linear_predictor: 'np.ndarray', coef: 'np.ndarray', intercept: 'np.ndarray', coords: 'np.ndarray', feature_names: 'Tuple[str, ...]', family: 'str', exposure: 'Optional[np.ndarray]' = None, coef_standard_errors: 'Optional[np.ndarray]' = None, intercept_standard_errors: 'Optional[np.ndarray]' = None, coef_z_values: 'Optional[np.ndarray]' = None, intercept_z_values: 'Optional[np.ndarray]' = None) -> None |
| Maintained example | examples/models/06_gwglm.py |
GWGLMPredictionResult
dataclass
¶
GWGLMPredictionResult(
predictions: ndarray,
linear_predictor: ndarray,
coef: ndarray,
intercept: ndarray,
coords: ndarray,
feature_names: Tuple[str, ...],
family: str,
exposure: Optional[ndarray] = None,
coef_standard_errors: Optional[ndarray] = None,
intercept_standard_errors: Optional[ndarray] = None,
coef_z_values: Optional[ndarray] = None,
intercept_z_values: Optional[ndarray] = None,
)
Rich prediction result returned by :meth:GWGLM.predict_result.
to_frame ¶
Return prediction results as a pandas DataFrame.
Source code in src/pygwrx/models/glm_gwr.py
to_geodataframe ¶
Return prediction results as a point GeoDataFrame.
Source code in src/pygwrx/models/glm_gwr.py
Runnable examples used on this page¶
examples/models/06_gwglm.py
# SPDX-FileCopyrightText: 2026 Jinghao Hu
# SPDX-License-Identifier: MIT
"""Fit Gaussian, binomial, and Poisson GWGLM families."""
# 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 count_regression, print_model_result, spatial_regression
from pygwrx import GWGLM, GWGLMPredictionResult
X, y, coords = spatial_regression(p=2)
gaussian = GWGLM(family="gaussian", bandwidth=24, adaptive=True).fit(X, y, coords)
print_model_result(gaussian)
binary = (y > np.median(y)).astype(int)
binomial = GWGLM(family="binomial", bandwidth=24, adaptive=True).fit(X, binary, coords)
binomial_result = binomial.predict_result(X.iloc[:3], coords.iloc[:3])
assert isinstance(binomial_result, GWGLMPredictionResult)
print(binomial_result.to_frame())
Xc, counts, coordsc, exposure = count_regression()
poisson = GWGLM(family="poisson", bandwidth=24, adaptive=True).fit(
Xc, counts, coordsc, exposure=exposure
)
print(
"poisson means=",
poisson.predict(Xc.iloc[:3], coordsc.iloc[:3], exposure=exposure[:3]),
)