Urban Spatial Econometric Analysis · 도시 공간계량 분석
파이썬과 GIS 기반 도시정책 평가용 공간계량 모형 Spatial econometric models for urban policy evaluation using Python and GIS
개요 · Overview
도시 데이터(주택가격·범죄율·인프라 품질)는 인접 지역 간 공간 자기상관을 갖습니다. 이를 무시한 전통적 회귀모형은 편향된 계수와 잘못된 정책 결론을 낳습니다. 본 저장소는 공간 가중행렬 구축부터 SLM·SEM·SDM·GWR 추정, 직접·간접효과 분해, 출판용 표 생성까지 완결된 공간계량 파이프라인을 제공합니다.
Urban data — property values, crime rates, infrastructure quality — exhibits spatial autocorrelation across neighboring areas. Traditional regression that ignores this yields biased coefficients and invalid policy recommendations. This repository implements a complete spatial econometric pipeline: spatial weight matrices, Moran/LISA/LM diagnostics, OLS/SLM/SEM/SDM/GWR estimation, LeSage–Pace impacts, and publication-ready tables.
문제와 접근 · Problem & Approach
- 공간 가중행렬 / Spatial Weight Matrix — Queen·Rook 인접성, K-최근접, 거리, 커널 (
weights.py) - 공간 시차 모형 / Spatial Lag Model (SLM) — 내생적 공간 상호작용 포착
- 공간 오차 모형 / Spatial Error Model (SEM) — 공간 상관 잔차 보정
- 공간 더빈 모형 / Spatial Durbin Model (SDM) — 시차·오차 효과 결합
- 지리가중회귀 / Geographically Weighted Regression (GWR) — 국지적 계수 추정
- 진단 / Diagnostics — Moran's I, Geary's C, LISA, LM/Robust LM, VIF, Chow (
diagnostics.py)
빠른 예시 · Example
import uspatial as u
gdf = u.load_example("columbus") # libpysal 동봉 데이터, 네트워크 불필요
w = u.build_weights(gdf, method="queen")
# 1) OLS → LM/Robust LM 진단 → 모형 추천 (Anselin & Florax 1995 규칙)
selection = u.select_model(gdf, "CRIME", ["INC", "HOVAL"], w)
print(selection.recommendation) # → 'SLM'
print(selection.diagnostics.to_frame())
# 2) 추천 모형 적합 + 직접·간접·총 효과 (LeSage & Pace 2009)
slm = selection.fit(gdf, "CRIME", ["INC", "HOVAL"], w)
print(slm.summary())
print(u.impacts_decomposition(slm, draws=1000)) # 시뮬레이션 표준오차 포함
구현 현황 · Implementation Status
| 기능 | 함수 | 상태 |
|---|---|---|
| 공간가중행렬 5종 (queen·rook·knn·distance·kernel) | build_weights |
✅ |
| OLS + 공간 진단 | SpatialModel(method="OLS") |
✅ |
| SLM · SEM · SDM (최대우도) | method="SLM"/"SEM"/"SDM" |
✅ |
| GWR (AICc 대역폭, mgwr) | method="GWR" |
✅ |
| 직접·간접·총효과 (LeSage & Pace) | impacts_decomposition |
✅ |
| Moran's I · Geary's C · LISA | morans_i, gearys_c, local_moran |
✅ |
| LM/Robust LM · LM-WX · 잔차 Moran | lm_diagnostics, residual_moran |
✅ |
| VIF · 구조 안정성 Chow 검정 | variance_inflation_factor, spatial_chow_test |
✅ |
| 모형 비교(ΔAIC) · 모형 선택 | compare_models, select_model |
✅ |
| 출판용 표 (Markdown·LaTeX) | reporting.py |
✅ |
| 명령줄 인터페이스 | python -m uspatial |
✅ |
| 시각화 (단계구분도·LISA·GWR 계수 지도) | visualization.py |
✅ |
| 한국 KOSIS·NSDI 실데이터 연결 | — | 🗺 로드맵 |
정확성 검증 · Validation (Columbus, queen 행표준화)
| 모형 | 상수 | INC | HOVAL | 공간계수 | logL | AIC |
|---|---|---|---|---|---|---|
| OLS (Anselin 1988) | 68.619 | −1.597 | −0.274 | — | −187.377 | 380.754 |
| SLM | 45.603 | −1.049 | −0.266 | ρ = 0.423 | −182.674 | 373.348 |
| SEM | 60.280 | −0.957 | −0.305 | λ = 0.547 | −183.749 | 373.499 |
| SDM | 44.320 | −0.920 | −0.297 | ρ = 0.403 | −181.639 | 375.279 |
위 계수는 Anselin (1988) 공표값과 일치합니다. LM 진단은 LM-Lag p = 0.003, LM-Error p = 0.023, Robust LM-Lag p = 0.053, Robust LM-Error p = 0.83 으로 SLM을 추천합니다. 전체 흐름과 지도는 노트북에 실행 결과와 함께 있습니다.
추가 회귀 검증은 합성 격자 자료로 수행합니다: 참값 복원(SLM ρ=0.6→0.61, SEM λ=0.5→0.39, SDM θ_x1=0.8→1.02), 총효과 항등식(행표준화 W에서 β/(1−ρ)), LM 규칙 4분기 판별, 체커보드 음의 자기상관 등.
기술 스택 · Tech Stack
- Core: Python 3.11+, PySAL (libpysal, spreg, esda), GeoPandas, statsmodels
- GWR: mgwr (선택 의존성,
pip install "uspatial[gwr]") - Visualization: Matplotlib, mapclassify
프로젝트 구조 · Repository Structure
urban-spatial-analysis/
├── src/uspatial/
│ ├── weights.py # 공간 가중행렬 (W) 구축
│ ├── models.py # OLS·SLM·SEM·SDM·GWR, 모형 비교, 효과 분해, 모형 선택
│ ├── diagnostics.py # Moran's I · Geary's C · LISA · LM/Robust LM · VIF · Chow
│ ├── reporting.py # 출판용 계수표(Markdown/LaTeX)·모형 비교표
│ ├── cli.py # `python -m uspatial` (examples/diagnose/estimate/compare)
│ ├── data.py # 데이터 로딩·전처리
│ └── visualization.py # Choropleth · 군집 지도 · GWR 계수 지도
├── notebooks/
│ └── 01_columbus_full_analysis.ipynb # 전체 분석 워크플로(Columbus 예제)
├── tests/ # 단위·회귀 테스트 (Columbus 기준값 + 합성 격자 회귀)
├── legacy/ # 패키지 이전 초안 (동작하지 않음, 참고용 — git 이력 보존)
├── data/README.md # 데이터 출처 및 다운로드 안내
├── docs/ARCHITECTURE.md # 설계·방법론 문서
├── pyproject.toml # 패키징·ruff·pytest 설정
├── CONTRIBUTING.md
├── requirements.txt
└── LICENSE
빠른 시작 · Quick Start
git clone https://github.com/DongsooJung/urban-spatial-analysis.git
cd urban-spatial-analysis
pip install -e ".[gwr,dev]" # 또는 pip install -r requirements.txt
jupyter notebook notebooks/01_columbus_full_analysis.ipynb
라이브러리로 쓰기
from uspatial import build_weights, select_model, impacts_decomposition
w = build_weights(gdf, method="queen") # 행 표준화된 Queen W
# 1) OLS → LM/Robust LM 진단 → 모형 추천 (Anselin & Florax 1995 규칙)
selection = select_model(gdf, "log_price", ["inc", "dist_cbd"], w)
print(selection.recommendation) # 'OLS' | 'SLM' | 'SEM' | 'SDM'
print(selection.diagnostics.to_frame()) # LM 4종 통계량·p값
# 2) 추천 모형 적합 + 직접·간접·총 효과 (LeSage & Pace 2009)
sem = selection.fit(gdf, "log_price", ["inc", "dist_cbd"], w)
print(sem.summary())
print(impacts_decomposition(sem, draws=1000)) # 시뮬레이션 표준오차 포함
명령줄로 쓰기
python -m uspatial examples
python -m uspatial diagnose --data tracts.csv --y log_price --x inc,dist_cbd --coords lon,lat --knn 6
python -m uspatial estimate --data tracts.csv --y log_price --x inc,dist_cbd \
--coords lon,lat --knn 6 --method SEM --format markdown
python -m uspatial compare --data tracts.csv --y log_price --x inc,dist_cbd \
--coords lon,lat --knn 6 --methods OLS,SLM,SEM --json
테스트
pytest -q # 합성 격자 기반: 참값 복원력·효과 분해 항등식·LM 규칙 + Columbus 공표값
ruff check src tests
연구 맥락 · Research Context
서울대학교 건설환경공학부(스마트도시공학) 박사과정 연구를 지원하며, 군 공항 이전 영향 분석과 대중교통중심개발(TOD) 평가 등 도시정책 평가에 적용됩니다.
This work supports doctoral research at Seoul National University, Department of Civil & Environmental Engineering (Smart City Engineering), applied to urban policy evaluation including military airport relocation impact analysis and transit-oriented development assessment.
참고문헌 · References
- Anselin, L. (1988). Spatial Econometrics: Methods and Models. Springer.
- LeSage, J. & Pace, R.K. (2009). Introduction to Spatial Econometrics. CRC Press.
- Anselin, L., Bera, A. K., Florax, R., & Yoon, M. J. (1996). Simple diagnostic tests for spatial dependence. Regional Science and Urban Economics, 26(1), 77–104.
- Anselin, L. (1995). Local indicators of spatial association — LISA. Geographical Analysis, 27(2), 93–115.
- Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2002). Geographically Weighted Regression. Wiley.
- Rey, S.J. & Anselin, L. (2010). PySAL: A Python Library of Spatial Analytical Methods.
라이선스 · License
MIT License — 자세한 내용은 LICENSE 참조.
저자 · Author
정동수 (Dongsoo Jung) — 서울대학교 박사과정 · 스마트도시공학 GitHub @DongsooJung
Metadata
Release files for uspatial 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| uspatial-0.2.0.tar.gz | 53.1 kB | With provenance | Details for uspatial-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| uspatial-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for uspatial-0.2.0-py3-none-any.whl |
Total release size: 92.1 kB
Release files / uspatial-0.2.0.tar.gz
| Download URL | uspatial-0.2.0.tar.gz |
|---|---|
| Size | 53.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
271d35214a7075c77b1c365fc475533f00d19f5c0e80b484999ae1abf2e2ec52
|
|
BLAKE2b-256 checksum How to use checksums |
11d7cc695c307ac34b3d120c162d0b9a948e15eaaac91eab49848a1e45d20940
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 6, 2026.
Transparency logRelease files / uspatial-0.2.0-py3-none-any.whl
| Download URL | uspatial-0.2.0-py3-none-any.whl |
|---|---|
| Size | 39.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a93f7fa3f2e7bebd996d1ab692b615e4d068d5c22a22899b3a27461a2933e4be
|
|
BLAKE2b-256 checksum How to use checksums |
36961ccdde2507144cfbb294d3f0c8daf536691e73d68f31039cc4a860707b3b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 6, 2026.
Transparency logSecurity for uspatial 0.2.0
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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for uspatial-0.2.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 6, 2026.
Transparency logA 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.