Classification
A complete guide to Classification in Machine Learning: binary vs multi-class problems, decision boundaries, Logistic Regression, the Sigmoid function, and probability thresholding.
Imagine working at an airport luggage inspection station. As each suitcase passes through an automated scanner, you do not need to estimate the exact total value of everything packed inside. Instead, you have one specific decision to make: 'Does this bag contain prohibited items or not?' The answer falls into a discrete category: **Cleared** or **Flagged for Inspection**. Every suitcase is sorted into one of two paths. This is Classification. In machine learning, Classification is the task of predicting discrete category labels for new inputs based on patterns learned from historical data. It is the technology that keeps spam out of your inbox, unlocks your phone with facial recognition, screens diagnostic scans, and flags fraudulent transactions.
Definition
Classification is a supervised machine learning task where an algorithm learns to assign input data samples to one or more predefined categorical classes or labels based on learned decision boundaries.
Why It Matters
Most real-world decisions involve selecting between discrete choices rather than sliding along a continuous number scale: • Should a loan application be approved or denied? • Is an incoming email legitimate communication or spam? • Does a medical scan show signs of illness or a clean result? Classification provides a structured way to automate these operational choices quickly, consistently, and with measurable confidence scores.
How It Works
Here is how classification works, using Logistic Regression as the classic foundation: 1. Why Linear Regression Does Not Fit Classification: If you fit a straight line ($y = mx + b$) to predict binary probabilities (0 or 1), the line will naturally produce values below 0 or above 1. True probabilities must strictly remain between 0.0 (0%) and 1.0 (100%). 2. The Sigmoid Function: Logistic Regression resolves this by taking the linear equation ($z = \mathbf{w}^T \mathbf{x} + b$) and passing it through the S-shaped **Sigmoid Function**: $$\sigma(z) = \frac{1}{1 + e^{-z}}$$ • When $z$ is a large positive value, $\sigma(z)$ approaches 1.0. • When $z$ is a large negative value, $\sigma(z)$ approaches 0.0. • When $z = 0$, $\sigma(z) = 0.5$. The output is always a valid probability between 0 and 1. 3. Decision Boundaries and Thresholds: By default, classification models use a threshold of 0.5: • If predicted probability $\ge 0.5$, predict Class 1 (such as Positive or Flagged). • If predicted probability $< 0.5$, predict Class 0 (such as Negative or Cleared). In sensitive applications, teams adjust this cutoff. For example, in medical screening where missing a potential condition carries high risk, lowering the threshold to 0.2 helps prioritize Recall, catching more true cases even if it increases follow-up reviews. 4. Multi-Class Classification (The Softmax Function): When choosing among three or more mutually exclusive classes (such as Cat, Dog, or Bird), models use the **Softmax Function**. Softmax normalizes output scores so they represent a probability distribution where all class values sum to 1.0: $$P(y = c | \mathbf{x}) = \frac{e^{z_c}}{\sum_{j=1}^K e^{z_j}}$$ 5. Loss Function: Binary Cross-Entropy (Log Loss): Classification models are optimized using Cross-Entropy, which penalizes confident incorrect predictions more heavily than slight errors.
Classification Pipeline: From Features to Categorical Decision
Key Points
- Classification predicts discrete category labels rather than continuous numbers.
- Logistic Regression uses the Sigmoid function to transform linear scores into valid probabilities between 0 and 1.
- The Softmax function extends probability estimation to multi-class problems.
- Cross-Entropy Loss serves as the standard optimization cost function.
- The decision threshold (defaulting to 0.5) can be calibrated to emphasize either Precision or Recall.
Steps
Define the Classification Structure
Determine whether the task is Binary (two options), Multi-class (one of several choices), or Multi-label (a record can have several tags at once).
Evaluate Class Balance
Check for class imbalance. If 99% of samples belong to one class, standard accuracy can be misleading, making metrics like Precision, Recall, and F1-score essential.
Scale Features Appropriately
Standardize numerical features so gradient-based algorithms (like Logistic Regression and Neural Networks) train smoothly.
Train and Compare Models
Compare linear classifiers with tree-based models (such as Random Forest or Gradient Boosting) to balance training speed with accuracy.
Calibrate Decision Thresholds
Use Precision-Recall curves to select a decision threshold that matches your organization's risk tolerance.
Formula
Sigmoid Function (Logistic Curve):
\sigma(z) = \frac{1}{1 + e^{-z}} \in (0, 1)
Binary Cross-Entropy (Log Loss):
\mathcal{L}_{BCE} = -\frac{1}{N} \sum_{i=1}^N \left[ y_i \ln(\hat{p}_i) + (1 - y_i) \ln(1 - \hat{p}_i) \right]
Multinomial Softmax & Categorical Cross-Entropy:
P(y = c | \mathbf{x}) = \frac{e^{z_c}}{\sum_{j=1}^K e^{z_j}}, \quad \mathcal{L}_{CE} = -\frac{1}{N} \sum_{i=1}^N \sum_{k=1}^K y_{ik} \ln(\hat{p}_{ik})Examples
Binary Classification: Spam Detection
Input attributes include sender history, keyword frequencies, and link patterns. The model outputs a probability score of 0.94, categorizing the message as 'Spam'.
Multi-Class Classification: Document Tagging
An automated news engine processes article text and assigns the article to one of several categories: Politics, Technology, Business, or Sports, based on the highest probability score.
Real-World Examples
Medical Imaging Triage
Radiology departments use classification models to review screening scans, sorting cases into 'Normal' or 'Requires Review'. Setting a conservative threshold prioritizes Recall so that potential concerns are reliably presented to radiologists.
Online Content Moderation
Social platforms use multi-label classification to evaluate user posts, checking whether text or images trigger flags across multiple policies (such as spam, copyright, or safety guidelines) simultaneously.
Technical Examples
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
# 1. Generate imbalanced synthetic dataset (90% negative, 10% positive)
X, y = make_classification(n_samples=1000, n_features=5, weights=[0.9, 0.1], random_state=42)
# 2. Stratified Train-Test Split (preserves 90/10 ratio in both splits)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
# 3. Train Logistic Regression Model
clf = LogisticRegression()
clf.fit(X_train, y_train)
# 4. Predict raw probabilities for Class 1
probabilities = clf.predict_proba(X_test)[:, 1]
# 5. Compare Default Threshold (0.5) vs High-Recall Threshold (0.25)
default_preds = (probabilities >= 0.5).astype(int)
high_recall_preds = (probabilities >= 0.25).astype(int)
print("--- Default Threshold (0.5) Confusion Matrix ---")
print(confusion_matrix(y_test, default_preds))
print("\n--- High-Recall Threshold (0.25) Confusion Matrix ---")
print(confusion_matrix(y_test, high_recall_preds))
# Notice: False Negatives drop, catching more positive cases!Binary Classification vs Multi-Class Classification
| Aspect | Binary Classification | Multi-Class Classification |
|---|---|---|
| Number of Classes | Exactly 2 mutually exclusive classes ($y \in \{0, 1\}$) | 3 or more mutually exclusive classes ($y \in \{0, 1, 2, \dots, K\}$) |
| Output Activation | Sigmoid function: $\sigma(z) = \frac{1}{1 + e^{-z}}$ | Softmax function: outputs probabilities summing to 1.0 across all classes |
| Standard Cost Function | Binary Cross-Entropy (Log Loss) | Categorical Cross-Entropy |
| Decision Boundary | A single boundary separating feature space into two regions | Multiple intersecting boundaries partitioning space into several regions |
| Example Application | Spam vs. Inbox, Fraud vs. Legitimate, Positive vs. Negative | Classifying vehicle types, identifying animal species, language detection |
Decision Thresholds and Cost-Sensitive Classification
Handling Class Imbalance: Resampling and Focal Loss
Advantages
- Directly automates operational categorical decisions.
- Outputs calibrated probability scores to support flexible risk thresholds.
- Offers a wide variety of algorithms ranging from simple linear models to deep ensembles.
- Supported by clear, standardized evaluation tools like Confusion Matrices and ROC curves.
Limitations
- Requires careful evaluation when dealing with severe class imbalance.
- Forcing continuous real-world phenomena into rigid categories can discard helpful nuance.
- Incorrectly calibrated thresholds can lead to high false-alarm rates.
Interview Questions
Why is the Sigmoid function used in Logistic Regression rather than a simple step function?
A step function produces hard 0 or 1 outputs, but its mathematical derivative is zero everywhere (and undefined at 0). Without a usable derivative, gradient descent cannot calculate how to adjust parameters to reduce error. The Sigmoid function provides a smooth, continuous curve with non-zero derivatives everywhere, allowing gradient-based optimization while mapping any real input into a valid probability between 0 and 1.
If a model achieves 98% accuracy on a fraud detection task, is that sufficient evidence that it is performing well?
Not necessarily. In fraud detection, legitimate transactions often make up 99% of all data. A simple model that always predicts 'Legitimate' would achieve 99% accuracy while catching zero fraudulent transactions. You should evaluate Precision, Recall, F1-score, and Precision-Recall curves to confirm that the model effectively catches fraudulent cases without creating unmanageable numbers of false alarms.
Practice Questions
- Explain what probability output the Sigmoid function produces when $z = -2$, $z = 0$, and $z = 2$.
- A business finds that failing to detect a fraudulent order costs $1,000, while a false alarm costs $10 in customer verification friction. How should the team adjust the classification threshold?
