@wenmin-wu/tabular-haversine-knn-candidate-generation
BGenerates geographically proximate candidate pairs for entity matching using KNN with haversine distance, optionally partitioned by country.
Install
agr install @wenmin-wu/tabular-haversine-knn-candidate-generation --target claudeWrites 1 file into .claude/skills/, pinned to git-7198235d.
- .claude/skills/tabular-haversine-knn-candidate-generation/SKILL.md
Document
name: tabular-haversine-knn-candidate-generation description: > Generates geographically proximate candidate pairs for entity matching using KNN with haversine distance, optionally partitioned by country.
Haversine KNN Candidate Generation
Overview
Entity matching at scale requires a candidate generation step — comparing all N^2 pairs is infeasible. For location-based entities (POIs, stores, addresses), KNN with haversine distance finds the K geographically closest candidates per record. Partitioning by country/region reduces the search space further and prevents cross-continent false matches. The resulting candidate pairs are then scored by a downstream classifier.
Quick Start
import numpy as np
from sklearn.neighbors import NearestNeighbors
def generate_geo_candidates(df, n_neighbors=20, partition_col="country"):
"""Generate candidate pairs using haversine KNN per partition."""
all_candidates = []
for group, group_df in df.groupby(partition_col):
group_df = group_df.reset_index(drop=True)
coords = np.deg2rad(group_df[["latitude", "longitude"]].values)
knn = NearestNeighbors(
n_neighbors=min(len(group_df), n_neighbors),
metric="haversine", n_jobs=-1
)
knn.fit(coords)
dists, indices = knn.kneighbors(coords)
for i in range(len(group_df)):
for j in range(1, len(indices[i])): # skip self-match
all_candidates.append({
"id": group_df.iloc[i]["id"],
"match_id": group_df.iloc[indices[i][j]]["id"],
"geo_dist": dists[i][j] * 6371, # km
"neighbor_rank": j,
})
return pd.DataFrame(all_candidates)
candidates = generate_geo_candidates(df, n_neighbors=20)
Workflow
- Convert lat/lon to radians (required by haversine metric)
- Partition data by country or region to reduce search space
- Fit KNN with haversine metric per partition
- Extract K nearest neighbors and distances for each record
- Build candidate pair DataFrame with distance and rank features
Key Decisions
- n_neighbors: 10-50 typical; higher recall but more pairs to classify
- Partitioning: By country prevents cross-region false matches; skip for global matching
- Distance unit: Haversine returns radians; multiply by 6371 for kilometers
- Dual index: Combine geo KNN with text-based KNN for higher recall
References
Trustgrade B
- passBody integrity
Whether the stored document is plausibly the kind of file the artifact declares, rather than something fetched by mistake.
- passType matchnot applicable to this artifact type
Whether the artifact is really the kind of thing its metadata claims it is.
- passFreshness
How long since the source repository was last pushed to.
- passPrompt injection
Scans the artifact's own text for instructions aimed at your agent rather than at you.
- warnLicenseno SPDX license detected
Whether the source repository declares an SPDX license permissive enough to redistribute.
How the grade is calculated
Each check contributes 0 points when it passes, 1 when it warns, and 2 when it fails. The total maps to a letter:
- Aevery check passed
- Bone warning
- Ctwo warnings
- Dprompt injection or body integrity failed, or three warnings
- Fone of those failed, and something else is wrong
These are automated hygiene checks, not a security audit, and not a dependency or vulnerability scan. A grade of A means nothing was flagged — not that the artifact is safe.
Versions
git-7198235de5d72026-07-31