Weighted KNN
Distance-weighted voting: Closer neighbors have more influence
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(
n_neighbors=5,
weights='distance', # Instead of 'uniform'
metric='euclidean'
)Benefits:
- Reduces impact of distant neighbors
- Better for variable density data
- Can use larger k values
KNN for Outlier Detection
KNN can detect anomalies based on distance to neighbors:
Method:
- For each point, calculate distance to k-th nearest neighbor
- Points with large k-distances are outliers
- Threshold based on percentile or standard deviations
Applications:
- Anomaly Detection
- Novelty detection
- Quality control