GTWR¶
This page documents 2 public symbols. Each entry includes its purpose, import path, full API docstring, and the maintained example that exercises it.
GTWR¶
Geographically and temporally weighted regression.
| Property | Value |
|---|---|
| Type | class |
| Import | from pygwrx.models import GTWR |
| Signature | GTWR(kernel: 'Union[str, Callable[[np.ndarray, float], np.ndarray]]' = 'bisquare', bandwidth: 'Union[float, int, str, None]' = 'cv', bandwidth_method: 'str' = 'cv', adaptive: 'bool' = False, bandwidth_range: 'Optional[Tuple[float, float]]' = None, lambda_st: 'Union[float, str]' = 0.05, lambda_range: 'Tuple[float, float]' = (0.0, 1.0), lambda_grid_size: 'int' = 11, ksi: 'float' = 0.0, distance_combination: 'str' = 'gwmodel', tau: 'float' = 1.0, causal: 'bool' = False, time_unit: 'str' = 'auto', optimization_method: 'str' = 'golden_section', search_grid_size: 'int' = 25, search_tol: 'float' = 1e-05, search_max_iter: 'int' = 100, fit_intercept: 'bool' = True, distance_metric: 'str' = 'euclidean', sigma2_v1: 'bool' = False, verbose: 'bool' = False) -> 'None' |
| Maintained example | examples/models/05_gtwr.py |
GTWR ¶
GTWR(
kernel: Union[
str, Callable[[ndarray, float], ndarray]
] = "bisquare",
bandwidth: Union[float, int, str, None] = "cv",
bandwidth_method: str = "cv",
adaptive: bool = False,
bandwidth_range: Optional[Tuple[float, float]] = None,
lambda_st: Union[float, str] = 0.05,
lambda_range: Tuple[float, float] = (0.0, 1.0),
lambda_grid_size: int = 11,
ksi: float = 0.0,
distance_combination: str = "gwmodel",
tau: float = 1.0,
causal: bool = False,
time_unit: str = "auto",
optimization_method: str = "golden_section",
search_grid_size: int = 25,
search_tol: float = 1e-05,
search_max_iter: int = 100,
fit_intercept: bool = True,
distance_metric: str = "euclidean",
sigma2_v1: bool = False,
verbose: bool = False,
)
Bases: BaseSpatiotemporalRegressor
Geographically and temporally weighted regression.
The default distance_combination="gwmodel" follows the generalized
spatiotemporal distance implemented by GWmodel::st.dist:
.. math::
d_{st} = \lambda d_s + (1-\lambda)d_t
+ 2\sqrt{\lambda(1-\lambda)d_s d_t}\cos(\xi).
GWmodel uses absolute temporal differences, so the standard default is
causal=False. With causal=True, observations later than the regression
time receive a very large temporal distance as an optional history-only
extension for leakage-safe forecasting.
distance_combination="euclidean" instead uses
:math:\sqrt{d_s^2 + \tau d_t^2} and is provided for transparent comparison
with the public Python gtwr package.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kernel
|
Union[str, Callable[[ndarray, float], ndarray]]
|
Kernel name or callable accepting |
'bisquare'
|
bandwidth
|
Union[float, int, str, None]
|
Numeric bandwidth or |
'cv'
|
bandwidth_method
|
str
|
Selection criterion used when |
'cv'
|
adaptive
|
bool
|
Interpret bandwidth as an integer nearest-neighbour count. |
False
|
bandwidth_range
|
Optional[Tuple[float, float]]
|
Optional lower and upper search bounds. |
None
|
lambda_st
|
Union[float, str]
|
GWmodel spatial-temporal balance in |
0.05
|
lambda_range
|
Tuple[float, float]
|
Search interval used only when |
(0.0, 1.0)
|
lambda_grid_size
|
int
|
Number of deterministic lambda candidates. |
11
|
ksi
|
float
|
GWmodel interaction angle in radians, constrained to |
0.0
|
distance_combination
|
str
|
|
'gwmodel'
|
tau
|
float
|
Non-negative temporal scale used by the Euclidean combination. |
1.0
|
causal
|
bool
|
Whether future observations should be temporally remote. The
default |
False
|
time_unit
|
str
|
Unit used to convert datetime-like times. |
'auto'
|
optimization_method
|
str
|
|
'golden_section'
|
search_grid_size
|
int
|
Number of fixed-bandwidth candidates for grid search. |
25
|
search_tol
|
float
|
Tolerance for continuous bandwidth optimization. |
1e-05
|
search_max_iter
|
int
|
Maximum continuous search iterations. |
100
|
fit_intercept
|
bool
|
Whether to include a local intercept. |
True
|
distance_metric
|
str
|
Spatial distance metric. |
'euclidean'
|
sigma2_v1
|
bool
|
Residual variance convention. |
False
|
verbose
|
bool
|
Whether to print selection and fitting progress. |
False
|
Attributes:
| Name | Type | Description |
|---|---|---|
bandwidth_ |
Selected fixed distance or adaptive neighbour count. |
|
lambda_st_ |
Fitted GWmodel balance parameter. |
|
tau_ |
Fitted Euclidean temporal scale. |
|
times_train_ |
Optional[ndarray]
|
Numeric training times in |
time_unit_ |
Optional[ndarray]
|
Resolved datetime unit or |
spatiotemporal_distance_matrix_ |
Optional[ndarray]
|
Training target-to-observation distances. |
coef_ |
Optional[ndarray]
|
Local slopes with shape |
intercept_ |
Optional[ndarray]
|
Local intercepts with shape |
fitted_values_ |
Optional[ndarray]
|
Fitted responses at calibration locations. |
diagnostics_ |
Optional[ndarray]
|
Gaussian GWR-style diagnostics based on smoother traces. |
Source code in src/pygwrx/models/gtwr.py
fit ¶
fit(
X: Union[ndarray, DataFrame],
y: Union[ndarray, Series],
coords: Union[ndarray, DataFrame],
times: object,
*,
compute_hat_matrix: bool = True,
compute_local_r2: bool = True,
compute_inference: bool = True,
compute_hat_matrix_flag: Optional[bool] = None,
verbose: Optional[bool] = None
) -> "GTWR"
Fit GTWR and return self.
Smoother traces are calculated even when the full hat matrix is not retained, preserving valid AICc, effective-parameter, influence, and residual-variance diagnostics.
Source code in src/pygwrx/models/gtwr.py
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 | |
predict ¶
predict(
X: Union[ndarray, DataFrame],
coords: Union[ndarray, DataFrame],
times: object,
) -> np.ndarray
Predict responses at new space-time locations.
Source code in src/pygwrx/models/gtwr.py
predict_result ¶
predict_result(
X: Union[ndarray, DataFrame],
coords: Union[ndarray, DataFrame],
times: object,
) -> GTWRPredictionResult
Return predictions, local parameters, and optional inference.
Source code in src/pygwrx/models/gtwr.py
get_local_parameters ¶
Return local parameters at arbitrary space-time locations.
Source code in src/pygwrx/models/gtwr.py
to_frame ¶
Return training-location estimates and diagnostics as a DataFrame.
Source code in src/pygwrx/models/gtwr.py
summary ¶
Return a stable text summary of the fitted GTWR model.
Source code in src/pygwrx/models/gtwr.py
GTWRPredictionResult¶
Rich prediction result returned by :meth:GTWR.predict_result.
| Property | Value |
|---|---|
| Type | class |
| Import | from pygwrx.models import GTWRPredictionResult |
| Signature | GTWRPredictionResult(predictions: 'np.ndarray', coef: 'np.ndarray', intercept: 'np.ndarray', coords: 'np.ndarray', times: 'np.ndarray', feature_names: 'Tuple[str, ...]', coef_standard_errors: 'Optional[np.ndarray]' = None, intercept_standard_errors: 'Optional[np.ndarray]' = None, coef_t_values: 'Optional[np.ndarray]' = None, intercept_t_values: 'Optional[np.ndarray]' = None) -> None |
| Maintained example | examples/models/05_gtwr.py |
GTWRPredictionResult
dataclass
¶
GTWRPredictionResult(
predictions: ndarray,
coef: ndarray,
intercept: ndarray,
coords: ndarray,
times: ndarray,
feature_names: Tuple[str, ...],
coef_standard_errors: Optional[ndarray] = None,
intercept_standard_errors: Optional[ndarray] = None,
coef_t_values: Optional[ndarray] = None,
intercept_t_values: Optional[ndarray] = None,
)
Rich prediction result returned by :meth:GTWR.predict_result.
to_frame ¶
Return prediction results as a pandas DataFrame.
Source code in src/pygwrx/models/gtwr.py
to_geodataframe ¶
Return prediction results as a point GeoDataFrame.
Source code in src/pygwrx/models/gtwr.py
Runnable examples used on this page¶
examples/models/05_gtwr.py
# SPDX-FileCopyrightText: 2026 Jinghao Hu
# SPDX-License-Identifier: MIT
"""Fit and predict with geographically and temporally weighted regression."""
# 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 print_model_result, temporal_regression
from pygwrx import GTWR, GTWRPredictionResult
X, y, coords, times = temporal_regression()
model = GTWR(kernel="bisquare", bandwidth=24, adaptive=True, lambda_st=0.3).fit(
X, y, coords, times
)
print_model_result(model)
print("score=", model.score(X, y, coords, times=times))
result = model.predict_result(X.iloc[:3], coords.iloc[:3], times[:3])
assert isinstance(result, GTWRPredictionResult)
print(result.to_frame())