Metadata-Version: 2.4
Name: xtg
Version: 0.0.4
Summary: a map tool
Author: mjs
Author-email: mengjinsui@buaa.edu.cn
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: numpy
Requires-Dist: scipy
Requires-Dist: pysal
Requires-Dist: scikit-learn
Requires-Dist: pandas
Dynamic: author
Dynamic: author-email
Dynamic: description
Dynamic: description-content-type
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# 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)<br>ND `select_bw_aniso` (L-BFGS-B / Powell) |
| **诊断指标**                                           | `vif`（多重共线性） · `moran`（全局 Moran’s I）                                        |
| **评估指标**                                           | `rmse`、`pseudo_r2`、`aicc`                                                   |
| **核函数**                                            | 高斯 / 双二次 · 各向同性 + 各向异性 · 可扩展                                                |
| **稀疏权重矩阵**                                         | `core.weights.compute_weights` → SciPy CSR                                  |

---

## 依赖安装

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

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

---

## 快速上手

### 0 准备数据

```python
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

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

### 2 单带宽 GWR（自动搜索带宽）

```python
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（双带宽）

```python
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 自适应样本数 KNN-GWR

```python
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"])
```

---

## 空间诊断一键跑

```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 为你的研究或产品节省了时间，欢迎在论文 / 项目中引用：

```text
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 批量拟合**，敬请关注 ⭐。
