Skip to main content

xtg · 扩展型地理加权回归工具箱

Python-ready GWR / MGWR / AGWR with bandwidth search, diagnostics & KNN-GWR.

xtg 致力于把 R 生态里的地理加权回归(GWR)全家桶完整迁移到 Python, 并补充了 自适应 KNN-GWR、自动带宽搜索、VIF / Moran’s I 诊断等常用功能。

功能 说明
OLS / GWR / SGWR / MGWR / AGWR 基准 → 单带宽 → 全局+局部 → 多带宽 → 双向各向异性
KNN-GWR 自适应样本数带宽,适合离散、非平稳数据
带宽搜索 1D select_bw_iso (自动 bounded)
ND select_bw_aniso (L-BFGS-B / Powell)
诊断指标 vif(多重共线性) · moran(全局 Moran’s I)
评估指标 rmse、pseudo_r2、aicc
核函数 高斯 / 双二次 · 各向同性 + 各向异性 · 可扩展
稀疏权重矩阵 core.weights.compute_weights → SciPy CSR

依赖安装

pip install xtg                       # 最新发布版
# or
pip install git+https://github.com/yourname/xtg.git  # 开发版

额外依赖:numpy · scipy · pandas · scikit-learn · pysal pip 会自动安装,若使用 KNN-GWR 不需额外包。


快速上手

0 准备数据

import pandas as pd, numpy as np
df = pd.read_csv("house_price_panel.csv")

y  = np.log1p(df["AUP"].values)                 # ← 建议对房价取 log
X  = df[["RRP", "AVPI"]].values                 # 共线性低的两列
coords = df[["lon", "lat"]].values
coords_std = (coords - coords.mean(0)) / coords.std(0)   # 标准化!

1 全局 OLS

from xtg import fit_ols
ols = fit_ols(X, y)
print("OLS RMSE", ols.rmse_, "R²≈", ols.pseudo_r2_)

2 单带宽 GWR(自动搜索带宽)

from xtg import fit_gwr, select_bw_iso

best_bw = select_bw_iso(
    lambda bw: fit_gwr(X, y, coords_std, bw=bw).aicc_,
    bounds=(0.5, 5)
)
gwr = fit_gwr(X, y, coords_std, bw=best_bw)
print("GWR RMSE", gwr.rmse_)

3 各向异性 AGWR(双带宽)

from xtg import fit_agwr, select_bw_aniso
best_bwx, best_bwy = select_bw_aniso(
    lambda b: fit_agwr(X, y, coords_std, bw=tuple(b)).aicc_,
    ndim=2,
    bounds=[(0.5, 5)]*2,
    bw_init=[2, 1.5],
)
agwr = fit_agwr(X, y, coords_std, bw=(best_bwx, best_bwy))
print("AGWR RMSE", agwr.rmse_)

4 列级双向带宽 PC-AGWR

from xtg.models.agwr_pc import fit_agwr_pc
from xtg import select_bw_aniso

p = X.shape[1]                     # 自变量数
def obj(bw_flat):
    bw_mat = bw_flat.reshape(p + 1, 2)    # (截距+每列, 2)
    return fit_agwr_pc(X, y, coords_std, bw_mat).aicc_

bw_opt = select_bw_aniso(
    obj,
    ndim=2*(p+1),
    bounds=[(0.5, 3)]*(2*(p+1)),
    bw_init=np.tile([1.5, 1.0], p+1)
)
bw_mat = bw_opt.reshape(p + 1, 2)
pc_agwr = fit_agwr_pc(X, y, coords_std, bw_mat)

print("PC-AGWR RMSE", pc_agwr.rmse_)
print("trace(S)   ", pc_agwr.trace_s_)

5 自适应样本数 KNN-GWR

每个系数都有自己的 (bw_xk, bw_yk),并自动计算帽子矩阵 trace(S) 以获得 精确 AICc。

from xtg.models.gwr_knn import fit_gwr_knn
gwr_knn = fit_gwr_knn(X, y, coords_std, k=20)
print("KNN-GWR RMSE", gwr_knn["rmse"])

6 与 R(spgwr) 完全对齐的带宽选择

from xtg import select_bw_iso, spgwr_cv_rmse, fit_gwr_hat
bw = select_bw_iso(lambda h: spgwr_cv_rmse(X, y, coords, h))
gwr = fit_gwr_hat(X, y, coords, bw)

---

## 空间诊断一键跑

```python
from xtg import vif, moran
print(vif(X, feature_names=["RRP", "AVPI"]))
mi = moran(y, coords=coords_std, k=8)
print(f"Moran's I = {mi['I']:.3f},  p = {mi['p_sim']:.3f}")

建议实践流程

  1. 坐标平面化 / 标准化 → 避免带宽量纲错配
  2. VIF < 10、Moran’s I 显著 → 才值得做局部模型
  3. 搜索带宽 → select_bw_iso / select_bw_aniso 支持 AICc / CV
  4. 比较 OLS ↔ GWR ↔ AGWR ↔ KNN-GWR,选择最小 RMSE 模型
  5. .predict(X_new, coords_new) → 直接做空间外插预测

引用

如果 xtg 为你的研究或产品节省了时间,欢迎在论文 / 项目中引用:

Meng, J. (2025). xtg: An Extended Toolkit for Geographically Weighted Regression in Python. 
https://pypi.org/project/xtg/

许可证

Apache 2.0 | 欢迎 PR / Issue!


本包仍在快速演进中:计划引入 自适应 bisquare KNN-GWR、 局部 ridge 稳定化 和 GPU 批量拟合,敬请关注 ⭐。

Metadata

Release files for xtg 0.0.7

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for xtg 0.0.7
File Size Uploaded Provenance Actions
xtg-0.0.7.tar.gz 23.8 kB Without provenance Details for xtg-0.0.7.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for xtg 0.0.7
File Interpreter ABI Platform Actions
xtg-0.0.7-py3-none-any.whl Python 3 none any Details for xtg-0.0.7-py3-none-any.whl

Total release size: 51.5 kB

Release files / xtg-0.0.7.tar.gz

Download URL xtg-0.0.7.tar.gz
Size 23.8 kB
Tags Source
SHA-256 checksum
How to use checksums
779b56112db464880bead92e0ffa94ee0fa46f5705ba3e17f2ba57bcc1fd3a42
BLAKE2b-256 checksum
How to use checksums
96228715e147c6398ea3ded95e93dd4371102715f8af9238dca47cac58d2a89f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.11.6

Release files / xtg-0.0.7-py3-none-any.whl

Download URL xtg-0.0.7-py3-none-any.whl
Size 27.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ef7eb3ab13e41e7e6c76a475bda237783ae8159f1f97fc2b05db4ab788398aed
BLAKE2b-256 checksum
How to use checksums
49af1b6e4842ca341b7ee60c70d4eb8a7ccb8ba4a062603050b875e35c5bd9cc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.11.6

Security for xtg 0.0.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page