Chapter 3: Classification
Learn to predict discrete categories with machine learning. Master logistic regression for binary classification, understand the sigmoid function and cross-entropy loss, extend to multiclass problems with softmax, and use feature engineering to handle non-linear patterns.
Chapter Overview
Classification is the task of predicting which category an input belongs to. Unlike regression which outputs continuous values, classification outputs discrete class labels: spam or not spam, cat or dog or bird, malignant or benign.
The foundational algorithm is logistic regression, which despite its name is a classification method. It works by computing a linear combination of features, then passing the result through the sigmoid function to produce a probability between 0 and 1. If this probability exceeds a threshold (typically 0.5), we predict the positive class.
The key to understanding logistic regression is the loss function. We can't use mean squared error because sigmoid creates a non-convex loss surface. Instead, we use cross-entropy (log loss), which heavily penalizes confident wrong predictions and creates a smooth, convex optimization landscape.
The decision boundary in logistic regression is a hyperplane—the set of points where the predicted probability equals 0.5. Points on one side are classified as positive, points on the other as negative. This boundary is linear in the original feature space, but we can create non-linear boundaries through feature engineering.
For problems with more than two classes, we extend to multiclass classification using techniques like one-vs-rest (train K binary classifiers) or softmax regression (directly model probabilities for all K classes).
This chapter covers:
- Binary Classification: The sigmoid function, decision thresholds, and linear decision boundaries
- Logistic Regression: Maximum likelihood, cross-entropy loss, and why it works
- Multiclass: One-vs-rest, one-vs-one, and softmax approaches
- Naive Bayes: A probabilistic classifier based on Bayes' theorem
- Class Imbalance: Handling datasets where classes have very different frequencies
- Feature Engineering: Polynomial features and transformations to handle non-linear patterns
Chapter Roadmap
Click any topic to jump in
Binary Classification
The core task — separate inputs into two classes using sigmoid probabilities and decision thresholds.
Discriminative vs. generative classifiers for binary problems
Logistic Regression
The workhorse classifier — maximum likelihood estimation with cross-entropy loss and linear decision boundaries.
Naive Bayes
A probabilistic approach using Bayes' theorem with conditional independence — fast, interpretable, strong baseline.
Multiclass Classification
Extend binary methods to K classes with one-vs-rest, one-vs-one, or softmax regression.
Handling imbalanced data and engineering better features
Class Imbalance
Handle skewed class distributions with resampling, class weights, threshold tuning, and proper metrics.
Feature Engineering
Transform raw inputs into informative features — encoding, scaling, selection, and dimensionality reduction.
Binary classification assigns inputs to one of two classes. The goal is to find a decision boundary that separates the classes.
Key Challenge: We need probabilities, not raw scores. The sigmoid function maps any value to (0, 1).
In this topic
Classification vs Regression
Regression: continuous output (price, temperature). Classification: discrete categories (yes/no, A/B/C). Classification can output probabilities or hard labels.
Regression models — a continuous conditional expectation. Classification models for discrete — a probability distribution over categories. Using MSE for classification creates a loss surface with flat regions (gradient ) where the sigmoid saturates, stalling gradient descent. Cross-entropy fixes this because has gradient , which remains large even when is near 0 or 1.
Predict house price vs predict if house sells within 30 days. Which is regression, which is classification?
Sigmoid Function
Maps any real number to (0, 1). Output is interpreted as P(y=1|x). Derivative: σ'(z) = σ(z)(1-σ(z)), which is nice for gradient computation.
The sigmoid maps . Its derivative is , which peaks at (value ) and vanishes exponentially as . The sigmoid is the canonical link function for Bernoulli-distributed responses in generalized linear models. It arises naturally from the log-odds: if (a linear function of features), then solving for gives exactly the sigmoid. The inverse is the logit function: .
Calculate σ(0) and σ(2).
Sigmoid Properties
σ(0) = 0.5, σ(+∞) → 1, σ(-∞) → 0. Symmetric: σ(-z) = 1 - σ(z). Saturates at extremes (gradients become small).
The symmetry means the sigmoid is symmetric about the point . This implies that if the linear score flips sign, the predicted probability for class 1 and class 0 swap. Saturation at the extremes ( for and for ) means the function is approximately linear only in a narrow band around where . Outside this band, changes in barely affect the output.
If σ(z) = 0.73, what is σ(-z)?
Decision Threshold
Default threshold t=0.5, but adjust based on costs. Lower t = more positive predictions (higher recall, lower precision).
The decision rule if is equivalent to if (the logit of ). At , the boundary is . Lowering to 0.1 shifts the boundary to , dramatically expanding the positive prediction region. The optimal threshold minimizes expected cost: , where and are the costs of false positives and false negatives respectively.
Probabilities: [0.3, 0.6, 0.45, 0.8]. Predictions at t=0.5? At t=0.4?
Linear Decision Boundary
The boundary where P(y=1) = P(y=0) = 0.5. A hyperplane in feature space. Points on one side are class 1, other side class 0.
The decision boundary is a hyperplane in with normal vector . The signed distance from any point to this hyperplane is , which is proportional to the log-odds. Points farther from the boundary have higher confidence. The margin (distance between the nearest points of each class and the boundary) determines how robust the classifier is to small perturbations in the input.
Boundary: 2x₁ + 3x₂ - 6 = 0. Is point (1, 2) class 0 or 1?
Threshold Tuning
Use precision-recall tradeoff. Medical diagnosis: lower threshold (catch more disease, accept false alarms). Spam filter: higher threshold (avoid false spam labels).
The ROC curve plots true positive rate against false positive rate as the threshold varies from 0 to 1. The area under this curve (AUC) measures discrimination ability independent of threshold. The precision-recall curve is more informative for imbalanced data: precision and recall directly reflect performance on the minority class. The score summarizes the tradeoff as a single number.
Cancer detection: missing cancer costs 1K. How to set threshold?
Theory Exercise
Problem:
A medical test has P(positive|disease) = 0.95 and P(positive|healthy) = 0.05. If 1% of people have the disease, what is P(disease|positive)?
Hints:
- This is Bayes' theorem
- P(disease) = 0.01, P(healthy) = 0.99
- Calculate P(positive) using total probability
Coding Exercise
Problem:
Implement the sigmoid function in numpy, fit a LogisticRegression on the breast cancer dataset, then sweep the decision threshold from 0.5 down to 0.3 and report how precision and recall trade off.
Hints:
- sigmoid(z) = 1 / (1 + np.exp(-z)); verify sigmoid(0)==0.5.
- Use clf.predict_proba(X_test)[:, 1] to get positive-class probabilities, then apply (probs >= t).astype(int) for each threshold t.
- Use precision_score and recall_score from sklearn.metrics and observe that lowering the threshold raises recall but lowers precision.
Related Problems on PixelBank
Logistic regression uses maximum likelihood estimation to find the best weights. Unlike linear regression's MSE, we use cross-entropy loss.
Why not MSE? With sigmoid output, MSE creates a non-convex loss surface with many local minima.
In this topic
Logistic Model
Probability of positive class is sigmoid of linear combination of features. This is a discriminative model (models P(y|x) directly).
The model is a discriminative classifier — it directly models the posterior without modeling the joint distribution . The weight vector is perpendicular to the decision boundary, and is the signed distance from the origin to the boundary. Each weight represents the change in log-odds per unit change in feature : .
w=[0.5, -0.3], b=0.1, x=[2, 1]. What's P(y=1)?
Cross-Entropy Loss
Also called log loss or binary cross-entropy. Penalizes confident wrong predictions heavily (-log(0.01) >> -log(0.5)).
The loss is derived from the negative log-likelihood of the Bernoulli distribution. For , the loss is , which goes to infinity as (confident wrong prediction). The loss surface is convex in when the model is , guaranteeing a unique global minimum. Information-theoretically, cross-entropy measures the expected number of bits needed to encode events from distribution using a code optimized for distribution .
True y=1, model predicts ŷ=0.9 vs ŷ=0.1. Compare losses.
MLE Connection
Cross-entropy is equivalent to Maximum Likelihood Estimation. Minimizing CE = maximizing likelihood of observed labels under the model.
Maximum likelihood seeks . Taking the log and negating converts the product to a sum and max to min: , which is exactly cross-entropy. This means minimizing cross-entropy is equivalent to finding the parameters that make the observed labels most probable under the model. The MLE has desirable statistical properties: it is consistent (converges to true parameters as ) and asymptotically efficient (lowest variance among unbiased estimators).
3 samples: (y=1,ŷ=0.8), (y=0,ŷ=0.3), (y=1,ŷ=0.6). What's the likelihood?
Gradient for Logistic Regression
Surprisingly similar to linear regression gradient! The difference is ŷ is sigmoid output. Gradient is error × feature.
The gradient has the same form as linear regression's gradient — the sigmoid's derivative cancels neatly with the log in cross-entropy. This is not a coincidence: both are members of the exponential family, and the gradient of the negative log-likelihood always takes the form . This elegant form means the same gradient descent code works for both linear and logistic regression with only the loss function changed.
Sample: x=[1,2], y=1, ŷ=0.7. What's the gradient for w?
Odds and Log-Odds
Logistic regression models the log-odds (logit) as a linear function of features. Weights have interpretable odds ratio meaning.
The odds ratio is the exponential of the linear predictor. The log-odds (logit) is linear in the features, which is why logistic regression is a linear classifier despite having a nonlinear output. A unit increase in multiplies the odds by : if , the odds double (). This multiplicative interpretation makes logistic regression highly interpretable in domains like medicine and social science.
P(y=1) = 0.8. What are the odds? What are the log-odds?
Regularized Logistic Regression
Add L2 penalty to prevent overfitting. In sklearn, C = 1/λ (inverse regularization). Smaller C = more regularization.
Adding L2 penalty gives . The penalty prevents weights from growing to infinity when classes are perfectly separable — without regularization, the optimizer keeps increasing to make the sigmoid steeper, approaching a hard step function. Regularization caps this growth, maintaining a smooth probability transition and better generalization. In scikit-learn, the parameter inverts the convention: larger means less regularization.
sklearn C=0.1 vs C=10. Which has more regularization?
Weight Interpretation
For feature j: exp(wⱼ) is the odds ratio. If wⱼ = 0.7, one unit increase in xⱼ multiplies odds by exp(0.7) ≈ 2. Only valid after standardizing features.
For a binary feature , the weight equals the log odds-ratio: . For a continuous feature, represents the change in log-odds per unit increase. After standardization, the magnitude indicates relative feature importance. Confidence intervals for can be computed from the Fisher information matrix , giving .
Weight for 'years of experience' = 0.3. Current odds = 2:1. What happens if experience increases by 1?
Theory Exercise
Problem:
Why does logistic regression use cross-entropy loss instead of MSE? What would happen if we used MSE?
Hints:
- Think about the gradient when sigmoid output is near 0 or 1
- Consider the shape of the loss surface
- What about confident wrong predictions?
Coding Exercise
Problem:
Implement binary cross-entropy loss in numpy and verify it decreases as predicted probabilities move toward the true labels. Then fit a LogisticRegression and interpret one coefficient as a change in log-odds.
Hints:
- BCE = -mean(y*log(p) + (1-y)*log(1-p)); clip p to [eps, 1-eps] to avoid log(0).
- Compare BCE for predictions that are far from the labels vs close to them; the closer set should have lower loss.
- A LogisticRegression coefficient is the change in log-odds per unit increase of that (standardized) feature; exp(coef) is the odds ratio.
Related Problems on PixelBank
When we have more than two classes, we extend binary classification using strategies like One-vs-Rest (OvR) or softmax regression.
Key insight: Many binary classifiers can be combined to solve multiclass problems.
In this topic
One-vs-Rest (OvR)
Train K binary classifiers. Each separates one class from all others. Predict class with highest confidence. Simple but can be imbalanced.
OvR trains binary classifiers , each treating class as positive and all others as negative. Prediction assigns the class with the highest score: . Training cost is times a single binary classifier. The key limitation: each classifier sees a different class imbalance (1 class vs. ), which biases probability estimates. Platt scaling (fitting a sigmoid on the scores) can calibrate the outputs, but fundamentally the classifiers are not jointly optimized.
3 classes (A,B,C). Classifiers output: P(A vs rest)=0.6, P(B vs rest)=0.3, P(C vs rest)=0.8. Prediction?
One-vs-One (OvO)
classifiers
Train a classifier for each pair of classes. Use voting to predict. More classifiers but each sees balanced classes. Better for SVMs.
OvO trains classifiers, one per class pair. Prediction uses majority voting: each classifier casts a vote, and the class with the most votes wins. For , this means 45 classifiers, but each trains on only 2 classes (smaller subsets). OvO is preferred for kernel methods like SVMs where training cost is superlinear in — training 45 small classifiers is faster than 10 large ones. The drawback: prediction time grows as since every classifier must be evaluated.
4 classes. OvO: A beats B, A beats C, A beats D, B beats C, B beats D, C beats D. Prediction?
Softmax (Multinomial)
Direct multiclass extension. Outputs probability distribution over all K classes. Sum to 1. Requires z scores for all classes.
Softmax converts raw scores into a probability distribution: where . This requires weight parameters (a weight vector per class). The softmax function is the multi-class generalization of the sigmoid: for , softmax reduces to sigmoid. The temperature parameter controls confidence: — as , the distribution becomes one-hot; as , it becomes uniform.
z = [2, 1, 0] for 3 classes. Calculate softmax probabilities.
Softmax Properties
Invariant to adding constant to all zₖ. Softmax temperature: divide z by T. T→0: argmax, T→∞: uniform. Used in distillation.
Softmax is invariant to constant shifts: for any scalar . This is exploited for numerical stability by subtracting before exponentiating, preventing overflow. The Jacobian has the same form as the sigmoid derivative when . Softmax outputs are calibrated probabilities only when trained with cross-entropy loss — otherwise the outputs may be overconfident or underconfident and require temperature scaling.
z=[3,1]. Softmax at T=1? At T=0.5?
Cross-Entropy (Multiclass)
Sum over samples and classes. Only the true class contributes (y=1 for true class). Equivalent to negative log-likelihood.
The multiclass cross-entropy loss uses one-hot encoded labels where if sample belongs to class . This simplifies to where is the true class. The gradient has the same elegant form as the binary case. Cross-entropy is the KL divergence between the true label distribution and the model's predicted distribution, plus the entropy of the true distribution (which is constant).
True class=B. Predicted: P(A)=0.1, P(B)=0.7, P(C)=0.2. Cross-entropy loss?
Multiclass vs Multilabel
Multiclass: exactly one label per sample (mutually exclusive). Multilabel: multiple labels possible (e.g., image tags). Different problem setups.
Multiclass: each sample belongs to exactly one of mutually exclusive classes — outputs sum to 1 via softmax. Multilabel: each sample can belong to multiple classes simultaneously — each output is an independent sigmoid producing independent probabilities. The loss for multilabel is the sum of binary cross-entropies. A photo can be tagged "cat" AND "outdoor" (multilabel) but a tumor can only be "benign" OR "malignant" (multiclass). The distinction determines the output activation (softmax vs. independent sigmoids) and loss function.
Classify animal photo: (a) cat/dog/bird, (b) cute/scary/fluffy. Which is multiclass vs multilabel?
Theory Exercise
Problem:
You have a 5-class classification problem. Compare OvR vs OvO: how many classifiers are needed? When might you prefer each?
Hints:
- OvR: one classifier per class
- OvO: one classifier per pair
- Think about training data balance
Coding Exercise
Problem:
Implement a numerically-stable softmax in numpy (subtract the row max), verify each output row sums to 1, then fit a LogisticRegression on the iris dataset (multinomial is the default).
Hints:
- Subtract the per-row max before np.exp to prevent overflow: exp(z - z.max(axis=1, keepdims=True)).
- Normalize by the row sum with keepdims=True so broadcasting works; check np.allclose(rows.sum(axis=1), 1).
- Fit LogisticRegression(max_iter=...) directly on iris X, y — do NOT pass multi_class= (deprecated).
Related Problems on PixelBank
Naive Bayes is a probabilistic classifier based on Bayes' theorem with the "naive" assumption that features are conditionally independent given the class. Despite this simplification, it works surprisingly well for text classification and other domains.
In this topic
Bayes' Theorem
Posterior = (Likelihood × Prior) / Evidence. We want to find the class y that maximizes the posterior.
Bayes' theorem inverts the direction of conditioning. The prior encodes class frequency in the training data. The likelihood captures the distribution of features within each class. The evidence is a normalizing constant. Since we only need , we can ignore and compare numerators directly. This makes Naive Bayes a generative classifier — it models the joint rather than the posterior directly.
P(spam)=0.3, P('free'|spam)=0.8, P('free'|not spam)=0.1. Email contains 'free'. P(spam|'free')?
Naive Independence Assumption
Assume features are conditionally independent given the class. Drastically simplifies computation. Often violated but still works well!
The "naive" assumption factorizes the joint likelihood into a product of marginals. This reduces the number of parameters from (full joint) to (marginals), making estimation feasible with limited data. The assumption is almost always violated in practice — features like "word A" and "word B" co-occur in spam emails. Despite this, Naive Bayes often works well because classification only requires getting the ranking of correct, not the exact probabilities. The decision boundary is still correct even when probability estimates are poorly calibrated.
Spam email: P('free'|spam)=0.8, P('money'|spam)=0.7. What's P('free','money'|spam) under naive assumption?
Classification Rule
Predict class with highest posterior. P(x) is same for all classes, so we ignore it. Take log to avoid numerical underflow.
The decision rule avoids computing the denominator . In practice, we work with log-probabilities: to avoid numerical underflow from multiplying many small probabilities. The decision boundary is linear in the log-probability space: defines a hyperplane when the class-conditional distributions are Gaussian with equal covariance.
P(A)×P(x|A)=0.0002, P(B)×P(x|B)=0.00015. Prediction? Why use log?
Gaussian Naive Bayes
For continuous features, assume Gaussian distribution per class. Learn mean and variance for each feature-class combination.
Assumes — each feature follows a Gaussian distribution within each class, with class-specific mean and variance . This requires estimating parameters ( and for each feature-class pair). The log-likelihood for feature given class is . The decision boundary between classes depends on the quadratic vs. terms.
Height|Male: μ=175, σ=10. Height|Female: μ=162, σ=8. Person is 170cm. Which is more likely?
Multinomial Naive Bayes
For count data (word counts in text). P(xⱼ|y) is proportional to frequency of feature j in class y. The standard for text classification.
For text classification with word counts, where is the probability of word appearing in class . Given a document with word counts for vocabulary of size , the likelihood is . Parameters are estimated by counting: . This is the maximum likelihood estimate for the multinomial distribution.
In spam corpus: 'free' appears 500 times out of 10,000 words. P('free'|spam)?
Laplace Smoothing
Add α (usually 1) to all counts to handle unseen features. Without smoothing, one zero probability makes entire product zero.
Adding a pseudocount to every word-class count: where is vocabulary size. Without smoothing, a word never seen in class gives , zeroing out the entire posterior regardless of other features. With (Laplace), unseen words get probability instead of 0. This is equivalent to placing a uniform Dirichlet prior on the multinomial parameters — a Bayesian approach where the prior regularizes the maximum likelihood estimate.
Word 'cryptocurrency' never seen in training. Without smoothing, P('cryptocurrency'|spam)=0. Problem?
Theory Exercise
Problem:
Why does Naive Bayes work well for spam detection even though the independence assumption is violated (words like 'Nigerian' and 'prince' are correlated)?
Hints:
- Think about what we're actually trying to do
- We need ranking, not exact probabilities
- Consider the bias-variance tradeoff
Coding Exercise
Problem:
Fit a GaussianNB on the continuous iris features and report accuracy. Then, on small integer count data, show how the Laplace smoothing parameter alpha in MultinomialNB changes the predicted class probabilities.
Hints:
- GaussianNB assumes each feature is Gaussian per class — fit it directly on iris X, y.
- Build a tiny MultinomialNB count matrix with some zero counts so smoothing matters.
- Compare predict_proba with a small alpha (e.g. 1e-10, near no smoothing) vs alpha=1.0 (Laplace); larger alpha pulls probabilities toward uniform.
Related Problems on PixelBank
Many real-world classification problems have imbalanced classes—fraud detection (0.1% fraud), disease diagnosis (rare diseases), anomaly detection. Standard algorithms struggle because they optimize accuracy, which is misleading when classes are imbalanced.
In this topic
The Problem
If 99% of samples are negative, predicting all negative gives 99% accuracy! But we care about finding the rare positives. Accuracy is misleading.
With class ratio 1:100, a model predicting the majority class always achieves 99% accuracy but 0% recall on the minority class. The loss function is dominated by the majority class: , and since , the gradient points almost entirely toward minimizing majority class errors. The decision threshold at is miscalibrated — the model's estimated is biased toward the prior , so even samples that are truly positive often get probabilities below 0.5.
Fraud detection: 9,900 legit, 100 fraud. Model predicts ALL legit. Accuracy?
Resampling: Oversampling
Duplicate minority class samples or generate synthetic ones (SMOTE). Risk: overfitting to minority class. SMOTE creates new points along lines between minority neighbors.
Random oversampling duplicates minority class examples, creating a balanced training set. SMOTE (Synthetic Minority Over-sampling TEchnique) generates synthetic examples by interpolating between nearest neighbors: where . This expands the minority class region in feature space rather than just duplicating points. The risk is generating noisy synthetic points in overlapping regions between classes, which can blur the decision boundary.
100 fraud, 9900 legit. Apply SMOTE to make 5000 fraud. How?
Resampling: Undersampling
Remove majority class samples. Risk: losing information. Random undersampling or informed methods (Tomek links, ENN). Fast but may discard useful data.
Random undersampling discards majority class examples to match minority count. This is simple but throws away potentially useful data — if the minority class has 100 samples, we keep only 100 of 10,000 majority samples. Informed undersampling methods like Tomek Links remove majority samples that are nearest neighbors of minority samples (cleaning the boundary region). Ensemble approaches like EasyEnsemble train multiple classifiers on different random subsets of the majority class, then combine predictions via voting.
100 fraud, 9900 legit. Random undersample to 100 legit. Issue?
Class Weights
Weight loss by inverse class frequency. Minority class errors count more. Built into sklearn: class_weight='balanced'. Simple and effective.
Weighted loss assigns weight to class , so each class contributes equally to the total loss regardless of size. With 100:1 ratio, minority samples get weight 100. This is equivalent to oversampling without actually duplicating data. In scikit-learn, class_weight='balanced' computes . The gradient for a minority sample becomes 100 larger, forcing the model to pay attention to minority class errors during optimization.
100 fraud, 9900 legit (n=10000, K=2). What are balanced class weights?
Threshold Adjustment
Lower decision threshold to catch more positives. Trade precision for recall. Tune threshold on validation set using F1 or domain-specific metric.
Even with balanced training, the default threshold of 0.5 may not be optimal. For imbalanced problems, the optimal threshold is often lower than 0.5 because we want to catch more minority class instances. The precision-recall curve directly shows the tradeoff for each threshold. The optimal threshold can be selected to maximize score: , where weighs recall higher (appropriate when missing positives is costly).
At t=0.5: precision=80%, recall=20%. At t=0.2: precision=30%, recall=85%. Which for fraud?
Metrics for Imbalanced Data
Precision, Recall, F1-score, AUC-ROC, AUC-PR. Precision-Recall AUC is better than ROC-AUC for highly imbalanced data. Never use accuracy alone!
Accuracy is misleading for imbalanced data — always predict majority class for 99% accuracy with 0% minority recall. Better metrics: precision (of those predicted positive, how many are correct), recall (of those actually positive, how many did we find), and (harmonic mean — low if either is low). Matthews Correlation Coefficient uses all four confusion matrix entries and ranges from -1 to +1.
1% positive rate. Model A: ROC-AUC=0.95. Model B: ROC-AUC=0.93, PR-AUC=0.60 vs 0.40. Which is better?
Theory Exercise
Problem:
A fraud detection model has: 99.5% accuracy, 40% precision, 80% recall. Is this a good model? What do these metrics tell you?
Hints:
- Think about what precision and recall mean
- Consider the base rate of fraud
- Calculate how many false positives vs true positives
Coding Exercise
Problem:
Use make_classification with weights=[0.95, 0.05] to build an imbalanced dataset. Show that high accuracy is misleading versus a majority-class baseline, then retrain LogisticRegression with class_weight='balanced' and report the improvement in minority recall and F1.
Hints:
- Pass weights=[0.95, 0.05] to make_classification and use stratify=y in the split.
- Compare model accuracy to the trivial baseline of always predicting the majority class (~0.95).
- Refit with class_weight='balanced' and compare recall_score / f1_score on the minority class.
Related Problems on PixelBank
Sometimes data isn't linearly separable in the original feature space. Feature engineering creates new features that make patterns easier to learn.
Key idea: Transform features to a space where classes become linearly separable.
In this topic
Polynomial Features
Add powers and interactions of original features. Allows learning non-linear boundaries in the original space.
Adding polynomial terms and interaction terms enables linear classifiers to learn nonlinear decision boundaries. The decision boundary is linear in the transformed space but nonlinear in the original space . For example, defines a circle or ellipse in space. The number of degree- features for inputs is , which grows rapidly.
XOR problem: (0,0)→0, (1,1)→0, (0,1)→1, (1,0)→1. Not linearly separable. Add x₁x₂. Now?
Feature Scaling
Standardize features to zero mean, unit variance. Essential for gradient descent convergence and regularization fairness.
Gradient-based optimizers converge faster when features have similar scales. Standardization () centers at zero with unit variance; normalization () maps to . For logistic regression, unscaled features cause the loss landscape to have elongated contours — gradient descent zigzags instead of heading straight to the minimum. Distance-based methods (KNN, SVM) are particularly sensitive: a feature ranging 0-1000 will dominate Euclidean distance over a feature ranging 0-1.
Age: μ=35, σ=10. Person age=55. Standardized value?
One-Hot Encoding
Convert categorical features to binary columns. 'Color: [Red, Blue, Green]' → 3 binary features. Drop one to avoid multicollinearity (dummy variable trap).
Converts a categorical variable with levels into binary columns: category maps to a vector with 1 in position and 0 elsewhere. For linear models, use columns (drop one as reference) to avoid perfect multicollinearity with the intercept — the dropped category's effect is absorbed into the intercept. One-hot encoding preserves the categorical nature: the model can learn a different coefficient for each level. The cost is dimensionality — a feature with 1000 categories adds 999 dimensions.
City: [NYC, LA, Chicago]. One-hot encode 'LA'. Why drop one column?
Label Encoding
Map categories to integers (0, 1, 2, ...). Only for ordinal categories or tree-based models. Implies false ordering for nominal categories.
Maps each category to an integer: . This implicitly assumes an ordinal relationship (dog is "between" cat and bird), which is incorrect for nominal categories. For tree-based models (decision trees, random forests), label encoding works fine because splits like can isolate any subset of categories. For linear models, the imposed ordering introduces spurious linear relationships — always use one-hot encoding for nominal features with linear classifiers.
Size: [S, M, L] → [0, 1, 2]. Color: [Red, Blue, Green] → [0, 1, 2]. Which encoding is valid?
Target Encoding
Replace category with mean of target for that category. Powerful but risk of data leakage. Use with cross-validation or smoothing.
Replaces each category level with the mean of the target variable for that level: . This reduces a high-cardinality feature (e.g., zip code with 40,000 levels) to a single numeric column while preserving predictive information. The risk is target leakage: the encoding uses values from the training set, which can overfit — rare categories with few samples get noisy estimates. Regularization strategies include adding noise, using leave-one-out encoding (exclude the current sample's ), or Bayesian shrinkage toward the global mean.
City NYC: 80% churn rate (40 samples). City Smalltown: 90% churn (2 samples). Target encode both?
Feature Selection: Filter Methods
Select features independently of model. Correlation with target, mutual information, chi-squared. Fast but ignores feature interactions.
Filter methods rank features by statistical association with the target, independent of the model. Common scores: mutual information (captures nonlinear dependencies), chi-squared (for categorical features), and ANOVA F-statistic (ratio of between-group to within-group variance). Filter methods are fast () but evaluate features independently — they miss redundant features and informative feature combinations.
100 features. Correlation with target: X₁=0.8, X₂=0.7, X₃=0.01. Keep which?
Feature Selection: Wrapper Methods
Evaluate feature subsets by training model. Forward selection, backward elimination, RFE. More accurate but computationally expensive.
Wrapper methods evaluate feature subsets by training and testing the actual model. Forward selection starts with zero features and greedily adds the best one at each step ( model fits). Backward elimination starts with all features and removes the least useful ( fits). Exhaustive search over all subsets is optimal but intractable for . Recursive Feature Elimination (RFE) trains the model, ranks features by importance (e.g., weight magnitude), removes the weakest, and repeats — a practical approximation to backward elimination.
Forward selection: start empty. Add features one by one, keeping best. 50 features, want 5. How many models trained?
Dimensionality Reduction
PCA, LDA, or autoencoders to create new features from combinations of original ones. Reduces overfitting, speeds up training.
PCA finds directions of maximum variance: the first principal component captures the most variance, and subsequent components are orthogonal. The eigenvalues of the covariance matrix measure variance along each component. Retaining components that explain 95% of total variance () is a common heuristic. Unlike feature selection, PCA creates new features that are linear combinations of originals, making interpretation harder but often capturing more information in fewer dimensions.
100 correlated features. PCA keeps 95% variance with 10 components. Trade-off?
Theory Exercise
Problem:
You have a classification problem with 10,000 samples and 500 features. You suspect many features are irrelevant. What preprocessing steps would you take?
Hints:
- Consider feature selection methods
- Think about regularization
- What about feature correlations?
Coding Exercise
Problem:
Build a scikit-learn Pipeline that standardizes features before LogisticRegression (preventing leakage via cross-validation), and compare its cross-validated accuracy against a SelectKBest filter that keeps only the top features.
Hints:
- Wrap StandardScaler and LogisticRegression in a Pipeline so scaling is fit only on training folds inside cross_val_score.
- Run cross_val_score on the full-feature pipeline to get a leakage-free baseline.
- Insert SelectKBest(f_classif, k=...) between the scaler and classifier to do filter-based feature selection and compare scores.