Classification with Decision Trees and k-NN
Classification means predicting a category (which species? spam or not?) rather than a number. This lesson compares two classic, intuitive classifiers on the same data, and shows off scikit-learn's consistent API in action.
Two very different ideas, one shared interface
- A decision tree learns a sequence of yes/no questions ("is petal length < 2.5cm?") that splits the data into increasingly pure groups, similar in spirit to a flowchart you might design by hand, except the tree figures out which questions to ask and in what order.
- k-NN (k-nearest neighbors) works completely differently: to classify a new point, it finds the
kclosest points in the training data (by distance) and takes a majority vote among their labels.n_neighbors=5is a hyperparameter, a setting you choose before training, not something the model learns on its own. - Despite radically different internal logic, both models are trained and used identically:
fit(X_train, y_train)thenpredict(X_test). This consistency is exactly why scikit-learn is so easy to experiment with, swapping one model for another is often a one-line change.
accuracy_score
accuracy_score(y_true, y_pred) simply computes the fraction of predictions that matched the actual label, 0.0 (nothing right) to 1.0 (everything right). It's the simplest possible evaluation metric, and, as you'll see in a later lesson, sometimes a misleading one.
TIP
Try changing n_neighbors to 1 or 15 and re-running, k-NN's accuracy will change, a small preview of hyperparameter tuning, covered properly in the Overfitting and Cross-Validation lesson.