К основному содержанию
скилл CX Codex

spatial-statistics — скилл для Claude Code

Скилл для пространственного анализа: проверяет кластеризацию, горячие точки и зависимость в геоданных, а потом помогает с диагностикой регрессии.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add muend/geoai-skills --skill spatial-statistics -a claude-code
Открыть на GitHub

Что делает spatial-statistics

Скилл добавляет агенту дисциплину пространственной статистики. Работа начинается с выбора весов W: матрица соседства Queen/Rook для полигонов, K-ближайшие соседи для точек, дистанционный диапазон или ядро. Веса задаются по смыслу задачи, и к ним прилагается проверка на альтернативной матрице — иначе результат нечем подкрепить.

Дальше идёт связка «глобальное → локальное»: сначала Moran's I с перестановочным тестом, затем LISA и Getis-Ord Gi* с поправкой на множественные сравнения. Для явлений с населением скилл требует считать не абсолютные числа, а rates, и сглаживать их эмпирическим Байесом в мелких единицах. Для регрессии сначала OLS с LM-диагностикой, и только по её итогам выбирается SAR, SEM или GWR/MGWR через mgwr. В каждом итоговом отчёте остаётся остаточный Moran's I.

Код опирается на libpysal, esda, spreg и pointpats — их нужно поставить заранее. Что важнее: скилл прямо говорит, что обычная статистика молча завышает значимость на пространственных данных, поэтому без весов и диагностики остатков выводы делать не даст.

Какие задачи решает

  • Проверить, есть ли вообще кластеризация в географических данных, а не только на глаз
  • Найти горячие и холодные точки по интенсивности и отделить их от кластеров схожих значений
  • Выбрать тип пространственных весов и показать, что выводы держатся на альтернативной матрице
  • Разобраться, где нужна пространственная лаговая или ошибка-модель, а где хватает OLS
  • Проверить остаточную автокорреляцию после регрессии и не принять её за чистый результат

Примеры запросов агенту

  • Проверь мои данные по районам на пространственную кластеризацию: построй веса Queen и посчитай Moran's I
  • Сделай LISA-карту преступности с поправкой на множественные сравнения и объясни, какие кластеры значимы
  • Сравни OLS и пространственную лаговую модель для price, покажи LM-диагностику и остаточный Moran's I

Как установить spatial-statistics

1Через Skills CLI (Vercel)

npx skills add muend/geoai-skills --skill spatial-statistics -a claude-code

2Вручную: положить файлы

~/.claude/skills/spatial-statistics/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/spatial-statistics/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о spatial-statistics

Как установить spatial-statistics в Claude Code?

Выполните npx skills add muend/geoai-skills --skill spatial-statistics -a claude-code. После этого файл скилла лежит по пути ~/.claude/skills/spatial-statistics/SKILL.md.

Что делает spatial-statistics?

Ведёт агента по пространственному анализу: веса, глобальные и локальные тесты, затем выбор регрессионной модели и проверка остатков. В конце требует отчёт с оговорками про MAUP и чувствительность к весам.

Какие библиотеки нужны для работы скилла?

В примерах используются libpysal для весов, esda для Moran's I и LISA, spreg для регрессии, pointpats для точечных паттернов и mgwr для GWR/MGWR. Все они ставятся отдельно.

Исходный текст

SKILL.md · MIT
---
name: spatial-statistics
description: >-
  Always invoke before testing a geographic pattern for clustering, hotspots,
  dependence, or explanatory regression, even when aggregation or ordinary
  OLS is proposed as routine. Covers Moran's I, LISA, Getis-Ord Gi*, weights,
  MAUP and scale sensitivity for areas/grids, residual dependence, and
  spatial lag/error/GWR/MGWR models. Use ML standards for predictive
  evaluation and geostatistics for continuous surfaces from sparse samples.
license: MIT
metadata:
  author: Muhammed Enes Duran
---

# Spatial Statistics

Purpose: answer "is it clustered, where, and why" with defensible inference.
The core discipline: spatial data violates independence assumptions, so
standard statistics silently overstate significance — every analysis here
starts with weights design and ends with residual diagnostics.

## Spatial weights (W) — the analysis IS the weights

Every result downstream depends on W; choose it for substantive reasons and
run a sensitivity check with one alternative:

| Weights | Use when |
|---|---|
| Queen/Rook contiguity | Irregular polygons (admin units, parcels) |
| K-nearest neighbors | Points; islands present (contiguity leaves them unconnected) |
| Distance band | Physical process with known range |
| Kernel (distance-decayed) | Smooth influence, GWR-style local models |

```python
from libpysal.weights import Queen

w = Queen.from_dataframe(gdf, use_index=True)
print(f"islands: {w.islands}")   # unconnected units break stats — fix or document
w.transform = "r"                # row-standardize (default for Moran/lag models)
```

Always report: weights type, parameters, number of islands, and whether
results survive an alternative W.

## Global → local workflow

1. **Global Moran's I** (`esda.Moran`, permutation inference ≥999) —
   answers "any clustering at all?" Report I, p_sim, and the permutation
   distribution, not the analytical p.
2. **LISA / local Moran** (`esda.Moran_Local`) — maps WHERE: High-High,
   Low-Low clusters, High-Low/Low-High outliers. Correct for multiple
   testing (FDR at minimum) before coloring a map — uncorrected LISA maps
   overstate clusters and this is the field's most common abuse.
3. **Getis-Ord Gi\*** (`esda.G_Local`, star=True) — hot/cold spots of
   intensity (a distinct question from Moran clusters — Gi* finds
   concentrations of high values, LISA finds similarity structure).
4. Rates, not counts, for population-based phenomena; use Empirical Bayes
   smoothing (`esda.smoothing`) for small-population units before any of
   the above — raw rates in sparse units are noise.

## Point patterns

- Separate first-order intensity (density varies) from second-order
  interaction (points attract/repel) — KDE describes the former, Ripley's
  K/L (`pointpats`) tests the latter.
- Always test against an inhomogeneous null when the study area has obvious
  density gradients (population, roads); CSR against a city is a strawman.
- KDE bandwidth drives the story: report it, justify it (Silverman/CV), and
  show one alternative.

## Spatial regression decision path

Run OLS first, then diagnose — never start with a spatial model:

```python
from spreg import OLS
ols = OLS(y, X, w=w, spat_diag=True, moran=True, name_y="price", name_x=xnames)
```

Decision (Anselin's rule via LM tests): LM-Lag significant & LM-Error not →
**spatial lag (SAR)**; reverse → **spatial error (SEM)**; both → compare
robust LM versions; neither → OLS stands (report that as a finding).
Interpretation caveats: in SAR, coefficients are NOT marginal effects —
report direct/indirect (spillover) effects. In SEM, spatial structure is
nuisance correlation, no spillover story allowed.

**GWR/MGWR** (`mgwr`): when relationships plausibly vary over space.
Bandwidth by AICc search; map local coefficients WITH local t-values masked
for insignificance; MGWR when predictors operate at different scales.
GWR is exploratory — resist causal language on local coefficients.

## Inference honesty

- Permutation p-values over analytical ones wherever available.
- Multiple testing: n local tests = n units; FDR-correct.
- MAUP (modifiable areal unit problem): results can flip with unit
  aggregation — if the aggregation level is a choice, test one alternative
  and disclose.
- Spatial autocorrelation in residuals after modeling = model still wrong;
  report residual Moran's I for every final model.
- Correlation ≠ causation applies doubly here: spatially confounded
  variables (everything correlates with "distance to coast") demand
  explicit identification strategies before causal claims.

## Reporting template

```
## Spatial analysis: <question>
- Units & n, variable(s), rate smoothing: <...>
- W: <type/params>, islands: <n>, sensitivity W: <type>
- Global: Moran's I = <> (p_perm = <>)
- Local: <k> significant clusters after FDR; map attached
- Model: <OLS/SAR/SEM/GWR> chosen because <LM diagnostics>
- Residual Moran's I: <> — <interpretation>
- Caveats: MAUP, W-sensitivity, causal limits
```

## Execution contract

- **Workflow:** define inferential question and unit; inspect distributions and rates; construct and justify spatial weights; run global before local tests; fit models if needed; diagnose residual dependence; report uncertainty.
- **Decision rules:** use spatial statistics for dependence and inference, geostatistics for interpolating sampled continuous surfaces, and predictive ML when out-of-sample prediction is the primary goal.
- **Verification protocol:** test alternative weights and aggregation, use valid permutation or model inference, correct local multiplicity, inspect residual Moran's I, and distinguish association from causation.
- **Failure modes:** withhold inferential claims for arbitrary weights, islands ignored, unstable MAUP results, uncorrected multiple tests, residual autocorrelation, or unsupported causal language.
- **Deliverables:** analysis-ready variables, weights specification, global and local results, corrected significance, diagnostic maps, model and residual checks, sensitivity analysis, and caveats.
- **Source freshness:** consult [the authoritative source registry](references/authoritative-sources.md) before applying version-sensitive statistical APIs or defaults.

© Muhammed Enes Duran · MIT · muend/geoai-skills

Похожие скиллы

Все скиллы по теме «Данные и базы» →
xlsx официальный anthropics Работает с табличными файлами: создаёт, читает, правит и преобразует книги. Подходит, когда итогом должен стать файл Excel или другой табличный формат. 187 223установок google-agents-cli-observability официальный Google Помогает настроить трассировку и сбор данных о работе ИИ-агентов, включая агентов на ADK. Пригодится, когда нужно разбирать выполнение запросов или наблюдать за агентом после развёртывания. CX Codex +1 511 300установок caveman-evidence-review JuliusBrussee Скилл читает данные Caveman Cloud о расходах LLM, трассах и маршрутизации. Подходит для проверки того, куда уходит бюджет проекта. CX Codex +1 104 500установок migration JuliusBrussee Скилл задаёт правила безопасных миграций схем, данных и API с обязательным откатом. Пригодится при изменениях, где нельзя терять данные или ломать совместимость. CX Codex +1 103 900установок performance-optimization addyosmani Скилл для агентов ИИ-кодинга: сначала замеряет, потом чинит узкое место — от Core Web Vitals до N+1 запросов и индексов в базе. CX Codex +1 65 200установок supabase официальный supabase Скилл помогает настраивать базу данных, аутентификацию и RLS в Supabase без скрытых дыр в безопасности. CX Codex GP ChatGPT 8установок

Из того же набора6

point-cloud-lidar Скилл для работы с LAS, LAZ и COPC: классификация земли, DTM/DSM/CHM, метрики леса и зданий, вертикальные датумы. Нужен, когда на входе сырое облако точек. CX Codex +1 ★ 35звёзд репо ml-experiment-standards Заставляет агента проверять утечки, выбирать сплиты и метрики до обучения модели. Пригодится, когда результат нужно воспроизвести, а не просто получить цифру. CX Codex +1 ★ 35звёзд репо geostatistics-interpolation Скилл для пространственной интерполяции: строит поверхность по редким замерам и отдельно считает карту неопределённости. Полезен, когда нужно оценить значения между станциями, скважинами или зондированиями. CX Codex +1 ★ 35звёзд репо geo-data-engineering Помогает агенту собрать геоданные из OSM, STAC или Overture, привести их в рабочий вид и не потерять строки по дороге. CX Codex +1 ★ 35звёзд репо arcgis-pro-automation Скилл для управления локальными проектами ArcGIS Pro и ArcPy через arcgis-mcp-bridge: геообработка, проекции, растры, сети, экспорт компоновок. CX Codex +1 ★ 35звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой