K-Nearest Neighbors helps us guess the label of new data by looking at the closest examples we already know.
K-Nearest Neighbors (KNN) in ML Python
from sklearn.neighbors import KNeighborsClassifier model = KNeighborsClassifier(n_neighbors=k) model.fit(X_train, y_train) predictions = model.predict(X_test)
n_neighbors is the number of closest points to look at.
You must fit the model with training data before predicting.
model = KNeighborsClassifier(n_neighbors=3)model = KNeighborsClassifier(n_neighbors=5, weights='distance')
model.fit(X_train, y_train) predictions = model.predict(X_test)
This program loads iris flower data, splits it, trains a KNN model with 3 neighbors, predicts flower types on test data, and prints predictions and accuracy.
from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score # Load example data iris = load_iris() X, y = iris.data, iris.target # Split data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # Create KNN model with 3 neighbors model = KNeighborsClassifier(n_neighbors=3) # Train the model model.fit(X_train, y_train) # Predict on test data predictions = model.predict(X_test) # Calculate accuracy accuracy = accuracy_score(y_test, predictions) print(f"Predictions: {predictions}") print(f"Accuracy: {accuracy:.2f}")
KNN works best with small to medium datasets because it compares new points to all training points.
Choosing the right number of neighbors (k) is important: too small can be noisy, too large can smooth out details.
Features should be scaled (like using normalization) for KNN to work well because it uses distance.
KNN predicts labels by looking at the closest known examples.
It's easy to use and needs no training time but can be slow with big data.
Choosing the number of neighbors and scaling data are key to good results.
Practice
Solution
Step 1: Understand the role of K in KNN
K represents how many nearest neighbors the algorithm looks at to decide the label for a new point.Step 2: Differentiate K from other terms
K is not about features, classes, or total samples but specifically the count of neighbors considered.Final Answer:
The number of closest data points used to predict the label -> Option AQuick Check:
K = number of neighbors [OK]
- Confusing K with number of features
- Thinking K is number of classes
- Assuming K is total data points
Solution
Step 1: Recall correct Python import syntax
In Python, the correct way to import a class from a module is 'from module import Class'.Step 2: Match with scikit-learn KNN import
The KNeighborsClassifier is inside sklearn.neighbors, so the correct import is 'from sklearn.neighbors import KNeighborsClassifier'.Final Answer:
from sklearn.neighbors import KNeighborsClassifier -> Option DQuick Check:
Correct import uses 'from ... import ...' [OK]
- Using 'import Class from module' which is invalid
- Trying to import directly from sklearn without neighbors
- Using dot notation in import statement
X = [[1, 2], [2, 3], [3, 4], [6, 7]]
y = ['A', 'A', 'B', 'B']
Solution
Step 1: Calculate distances from (3,3) to each training point
Distances: to (1,2) ≈ 2.24, to (2,3) = 1, to (3,4) = 1, to (6,7) ≈ 5Step 2: Find 3 nearest neighbors and their labels
Nearest neighbors: (2,3) 'A', (3,4) 'B', (1,2) 'A'. Labels are ['A', 'B', 'A'].Step 3: Determine majority label
Label 'A' appears twice, 'B' once, so predicted label is 'A'.Final Answer:
'A' -> Option BQuick Check:
Majority vote among 3 neighbors = 'A' [OK]
- Ignoring distance and picking random label
- Choosing label of closest single neighbor only
- Miscounting neighbors or labels
from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=3) knn.fit(X_train, y_train) preds = knn.predict(X_test) print(preds)
Assuming X_train and y_train are numpy arrays but y_train contains string labels.
Solution
Step 1: Check if KNN supports string labels
KNN in scikit-learn supports string labels for classification without error.Step 2: Verify other possible errors
Data scaling is recommended but not mandatory; n_neighbors=3 is valid if training samples ≥3.Final Answer:
No error, code runs fine with string labels -> Option CQuick Check:
KNN accepts string labels directly [OK]
- Assuming string labels cause errors
- Confusing scaling as mandatory
- Ignoring sample size for n_neighbors
Solution
Step 1: Understand distance calculation in KNN
KNN uses distance (like Euclidean) between points; features with larger scales affect distance more.Step 2: Explain effect of unscaled features
If features are not scaled, large-scale features (like income) dominate, making smaller-scale features (like age) ignored.Step 3: Importance of scaling
Scaling puts all features on similar scale so each contributes fairly to distance and prediction.Final Answer:
Scaling ensures all features contribute equally; without it, large-scale features dominate distance calculations -> Option AQuick Check:
Scale features to balance distances [OK]
- Thinking KNN auto-scales features
- Believing scaling changes labels
- Assuming scaling only affects speed
Ready to prove it?
Pass the test and this pattern moves unknown
