Skip to content
Visual explainer 3h 30m to learn 5 steps

Logistic regression, k-NN and decision trees for classification

Train three classifiers, read their predicted probabilities and choose a decision threshold that fits the task.

By Invicly Tech, , in AI and Machine Learning with Python. About 12 minutes to read.

Topic 9 of 34

In short

A classifier predicts a category, and most scikit-learn classifiers can also give a probability for each class through predict_proba. Logistic regression draws a linear boundary and outputs probabilities, k-nearest neighbours votes among the closest training rows, and a decision tree asks a series of yes or no questions. By default predict uses a 0.5 cut-off for binary problems, but the right threshold depends on what a false alarm and a missed case cost.

Think of it like this: The probability is a weather forecast and the threshold is your rule for carrying an umbrella; the forecast stays the same, but the rule depends on how much you hate getting wet.

Explained simply

Classification means predicting a category: spam or not spam, which of three plant species, will this customer leave or stay. With two categories it is called binary classification, and we usually call the interesting one the positive class, even when it is bad news like fraud.

Logistic regression adds up weighted features like linear regression, then squeezes the result into a number between 0 and 1. k-nearest neighbours looks at the k training rows most similar to the new one and lets them vote. A decision tree asks questions such as is income above 30,000, and follows the answers down to a leaf.

Most classifiers can give you a score for each class, not only a label. In scikit-learn that is predict_proba. A score of 0.8 for fraud means the model leans strongly towards fraud. The plain predict method turns that score into a label using a cut-off of 0.5 for two classes.

That cut-off is called the decision threshold, and you are allowed to move it. If missing a sick patient is far worse than a false alarm, you lower the threshold so the model flags more cases. You pick the threshold using validation data and the real costs, never the test set.

Press Play on a diagram to walk through it one step at a time.

CompareThree classifiers on the same data
Logistic regression
  • Linear boundary in feature space
  • Probabilities from a sigmoid
  • Coefficients are readable
  • Needs scaling for fair penalties
k-nearest neighbours
  • Stores the training data
  • Votes among the k closest rows
  • Distances need scaled features
  • Slow to predict on large data
Decision tree
  • Series of threshold questions
  • No scaling needed
  • Easy to draw and explain
  • Overfits if grown too deep
FlowFrom features to a decision
  1. 1
    Features

    One row describing a case

  2. 2
    Model

    Fitted classifier

  3. 3
    Probability

    predict_proba gives a score per class

  4. 4
    Threshold

    Compare the positive-class score to a cut-off

  5. 5
    Action

    Approve, review, alert or ignore

CycleThreshold tuning loop
  1. 1
    Score validation rows

    Get predict_proba for the positive class

  2. 2
    Try a threshold

    Turn scores into labels

  3. 3
    Count mistakes

    False positives and false negatives

  4. 4
    Apply costs

    Total cost at this threshold

  5. 5
    Move the threshold

    Keep the lowest-cost value

  6. Back to step 1

In depth

How logistic regression turns a sum into a probability

Logistic regression computes z, a weighted sum of the features plus an intercept, exactly like linear regression. It then applies the sigmoid function, 1 / (1 + e to the power minus z), which maps any number to the range 0 to 1. When z is 0 the score is 0.5, so the decision boundary at the default threshold is the set of points where the weighted sum is zero: a straight line in two dimensions, a flat plane in more.

A coefficient changes the log-odds of the positive class by that amount for one unit of the feature. In scikit-learn, LogisticRegression applies an L2 penalty by default with strength set by C, where smaller C means a stronger penalty. Because of that penalty, scaling the features matters here too. It is fitted by minimising log loss, which strongly punishes confident wrong answers.

  • Sigmoid maps any number to 0 to 1
  • Boundary is linear in the features
  • C is the inverse of penalty strength; default C = 1.0
  • Raise max_iter if you see a convergence warning

k-NN: distance is everything

k-NN does almost no work at fit time; it stores the training data. At predict time it measures the distance from the new row to every stored row, takes the k closest and reports the share of each class among them as the probability. The default in scikit-learn is k = 5 with Euclidean distance.

Distance adds up differences across features, so a feature measured in thousands will swamp one measured in fractions. Scale first. Small k gives jagged boundaries that follow noise; large k gives smooth boundaries that can miss real detail. Because it compares against many stored rows, prediction gets slow as data grows, and in many dimensions all points start to look equally far apart, which weakens the idea of a near neighbour.

CompareSmall k versus large k
k = 1
  • Copies the closest row
  • Training accuracy near 100 percent
  • Very sensitive to noisy labels
  • High variance
k = 15 to 50
  • Smooth boundary
  • Probabilities in finer steps
  • Can blur small groups
  • Higher bias, lower variance

Decision trees for classification

A classification tree picks, at each node, the feature and threshold that best separate the classes, measured by Gini impurity or entropy. It repeats this on each side until a stopping rule is met. A leaf predicts the class share among training rows that reached it, so predict_proba from a tree often gives a few repeated values, and a fully grown tree gives mostly 0 and 1.

Without limits a tree keeps splitting until every leaf is pure, which memorises the training data. Use max_depth, min_samples_leaf or cost-complexity pruning with ccp_alpha to stop it early. Trees need no scaling and handle mixed feature types well, and you can draw a shallow tree with plot_tree to explain it to non-specialists.

Choosing and tuning the decision threshold

The threshold turns scores into actions. Lower it and you catch more positives but raise more false alarms; raise it and you get fewer alarms but miss more positives. The right point depends on the cost of each mistake and on how many cases people can review.

Use a validation set or cross-validation to choose it. scikit-learn 1.5 added TunedThresholdClassifierCV, which searches for the threshold that maximises a chosen score using internal cross-validation, and FixedThresholdClassifier, which applies a threshold you set. You can also do it by hand: get validation probabilities, try thresholds from 0.05 to 0.95, compute your metric or cost at each, and keep the best. Then report results on the untouched test set using that fixed threshold.

  • Lower threshold: higher recall, lower precision
  • Higher threshold: higher precision, lower recall
  • TunedThresholdClassifierCV: added in scikit-learn 1.5
  • Fix the threshold before you touch the test set

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Fit logistic regression~40m
  2. 2
    Fit k-nearest neighbours with scaling~40m
  3. 3
    Fit a decision tree~40m
  4. 4
    Read predicted probabilities~40m
  5. 5
    Tune the decision threshold~40m

Key points

  • Fit all three models in pipelines so scaling is learned from training data only.
  • k-NN and penalised logistic regression are sensitive to feature scale; trees are not.
  • predict_proba gives scores between 0 and 1; whether they behave like true probabilities is a separate question called calibration.
  • The 0.5 threshold is a default, not a rule; choose the threshold on validation data from the costs of each mistake.
  • Report a baseline such as always predicting the most common class, especially when classes are imbalanced.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier

X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=0)
models = {"logreg": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
          "knn": make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=15)),
          "tree": DecisionTreeClassifier(max_depth=4, random_state=0)}
for name, m in models.items():
    print(name, m.fit(X_tr, y_tr).score(X_te, y_te), m.predict_proba(X_te[:1]))

score() reports accuracy for classifiers. The dataset ships with scikit-learn.

Same data, three models, honest comparison

You want to compare three classifiers on the breast cancer dataset. Step 1: split with stratify=y so both sets keep the same class balance. Step 2: add a DummyClassifier that always predicts the most frequent class; its accuracy is about 63 percent here, so anything below that is useless. Step 3: wrap logistic regression and k-NN in pipelines with StandardScaler. Step 4: use 5-fold cross-validation with log loss as well as accuracy, because log loss checks the probabilities, not just the labels. Expect logistic regression to do very well on this dataset, k-NN close behind and the single tree a little worse.

python
from sklearn.dummy import DummyClassifier
from sklearn.model_selection import cross_validate

models["dummy"] = DummyClassifier(strategy="most_frequent")
for name, m in models.items():
    r = cross_validate(m, X_tr, y_tr, cv=5,
                       scoring=["accuracy", "neg_log_loss"])
    print(f"{name:6s} acc {r['test_accuracy'].mean():.3f} "
          f"logloss {-r['test_neg_log_loss'].mean():.3f}")

Picking a threshold for a screening tool

A clinic wants to flag patients for a follow-up test. Missing a positive case is judged ten times worse than an unneeded follow-up. Step 1: hold out a validation set from the training data. Step 2: fit logistic regression on the rest and score the validation rows. Step 3: for each threshold, count false negatives and false positives and compute 10 times FN plus FP. Step 4: keep the threshold with the lowest cost; expect it to be well below 0.5. Step 5: apply that fixed threshold to the test set once and report recall and precision. The data here is a teaching dataset, not clinical advice.

python
import numpy as np
from sklearn.metrics import confusion_matrix

X_fit, X_val, y_fit, y_val = train_test_split(X_tr, y_tr, stratify=y_tr, random_state=1)
clf = models["logreg"].fit(X_fit, y_fit)
p = clf.predict_proba(X_val)[:, 1]
best = None
for t in np.arange(0.05, 0.96, 0.05):
    tn, fp, fn, tp = confusion_matrix(y_val, p >= t).ravel()
    cost = 10 * fn + fp
    if best is None or cost < best[1]:
        best = (t, cost)
print("threshold", round(best[0], 2), "cost", best[1])

Quick reference

  • predict_proba(X)[:, 1] gives the positive-class score for binary problems
  • predict uses a 0.5 cut-off on that score for binary classifiers
  • Scale features for k-NN and logistic regression; trees do not need it
  • LogisticRegression: smaller C means a stronger penalty
  • KNeighborsClassifier default n_neighbors = 5
  • Limit trees with max_depth, min_samples_leaf or ccp_alpha
  • Use stratify=y in train_test_split for classification
  • TunedThresholdClassifierCV picks a threshold by cross-validation (scikit-learn 1.5+)

Common mistakes

  • Running k-NN on unscaled data, so one feature with large numbers decides every distance.
  • Treating the 0.5 cut-off as fixed when missing a positive case costs far more than a false alarm.
  • Tuning the threshold on the test set, which makes the final score look better than it will be in use.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which classifier is least affected by changing one feature from grams to kilograms?

Question 2

2You lower the decision threshold from 0.5 to 0.3. What usually happens?

Question 3

3A k-NN model with k = 1 scores 100 percent on training data and 82 percent on test data. What is happening?

Question 4

4Why compare classifiers with log loss as well as accuracy?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Train a DecisionTreeClassifier with max_depth 3 on the iris dataset and print the predicted probabilities for the first five test rows.

  2. Exercise 2medium

    On the breast cancer data, compare k-NN with and without StandardScaler for k in 1, 5, 15 and 50 using 5-fold cross-validated accuracy.

  3. Exercise 3hard

    Use TunedThresholdClassifierCV to choose a threshold for logistic regression that maximises balanced accuracy, then compare test recall and precision with the default 0.5 model.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is logistic regression a regression or a classification model?
It is used for classification. The name comes from the fact that it fits a linear model to the log-odds of the class, then turns that into a probability.
How do I choose k for k-nearest neighbours?
Try several values with cross-validation on scaled data. Odd values avoid ties in binary problems, and values from about 5 to 50 are a common starting range.
Are predict_proba scores real probabilities?
Not always. Some models are over- or under-confident. Check with a calibration curve and calibrate if you need the scores to match real frequencies.
Why not always use 0.5 as the threshold?
Because mistakes rarely cost the same. The best threshold balances the cost of false alarms against the cost of missed cases.

Go deeper

ShareXLinkedInWhatsApp