تخيل إنك واقف في منطقة جديدة ومش عارف ده حي راقي ولا شعبي:
"قولي مين جيرانك، أقولك إنت مين!" 😄
زي ما بتحسب المسافة على الخريطة!
قيمة K مهمة جداً!
صغير جداً
⚠️ حساس جداً للـ noise والـ outliers
متوازن ✓
✓ عادة اختيار كويس للبداية
كبير جداً
⚠️ هيختار الـ class الأكثر عموماً (underfitting)
💡 نصيحة:
Click to place unknown point
Click on the plot to place a point, then classify it.
function knn(data, query, k) {
// 1. Calculate distances
const distances = data.map(point => ({
label: point.label,
dist: Math.sqrt(
(point.x - query.x) ** 2 +
(point.y - query.y) ** 2
)
}));
// 2. Sort by distance
distances.sort((a, b) => a.dist - b.dist);
// 3. Get K nearest
const kNearest = distances.slice(0, k);
// 4. Vote!
const votes = {};
kNearest.forEach(n => {
votes[n.label] = (votes[n.label] || 0) + 1;
});
// Return majority vote
return Object.entries(votes)
.sort((a, b) => b[1] - a[1])[0][0];
}