Machine Learning Fundamentals with scikit-learn

Lesson 3 of 8

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

Pythonshares state with other Python blocks
  • 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 k closest points in the training data (by distance) and takes a majority vote among their labels. n_neighbors=5 is 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) then predict(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.

📝 Classification Quiz

Passing score: 70%
  1. 1.How does k-NN classify a new data point?

  2. 2.n_neighbors is a hyperparameter you choose before training, not something the model learns on its own.

  3. 3.____ predicts a category (like a species or spam/not-spam), as opposed to regression, which predicts a number.