Custom distance metrics
Define custom distance/similarity metrics for DBSCAN clustering with sklearn, using weighted Euclidean distances.From its SKILL.md
npx -y skills add cxcscmu/SkillLearnBench --skill custom-distance-metricsAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
SKILL.md
1.3 KB, 273 tokens by cl100k_base, as published. Nobody here has run it
Custom Distance Metrics for DBSCAN
Overview
DBSCAN in sklearn supports custom distance metrics via metric='precomputed' (pass a distance matrix) or metric=callable with the pairwise distance function.
Approach: Precomputed Distance Matrix
For small-to-medium datasets per image, computing a full pairwise distance matrix is efficient:
from sklearn.cluster import DBSCAN
from scipy.spatial.distance import pdist, squareform
import numpy as np
def weighted_euclidean(points, w):
"""Compute pairwise weighted Euclidean distance.
d(a,b) = sqrt((w*dx)^2 + ((2-w)*dy)^2)
"""
scaled = points * [w, 2 - w]
return squareform(pdist(scaled, metric='euclidean'))
# Usage
dist_matrix = weighted_euclidean(points_xy, shape_weight)
db = DBSCAN(eps=epsilon, min_samples=min_samples, metric='precomputed')
labels = db.fit_predict(dist_matrix)
Key Points
pdist+squareformis faster than looping over pairs- Scale the coordinates before computing standard Euclidean = same as custom weighted metric
- When w=1, this equals standard Euclidean distance
- Cluster centroids are computed from original (unscaled) coordinates
What ships with it
Read from the repository
Just SKILL.md. No reference files, no scripts.