ML Notes
Deep dive into supervised learning covering classification, regression, common algorithms, training process, and practical Python implementations with sklearn.
Supervised learning is the most common and practical form of machine learning. The name comes from the idea of a "supervisor" providing correct answers during training — like a teacher grading homework so the student can learn from mistakes.
How Supervised Learning Works
| Training | ────► | Algorithm | ────► | Trained |
|---|---|---|---|---|
| Data (X, y) | Model | |||
| New Input | ────► | Trained | ────► | Prediction |
| (X_new) | Model | (y_pred) |
The Mathematical Framework
Given a dataset of n examples: {(x₁, y₁), (x₂, y₂), ..., (xₙ, yₙ)}
The goal is to learn a function f such that: f(x) ≈ y
The model minimizes a loss function that measures prediction errors:
Classification vs Regression
| Aspect | Classification | Regression |
|---|---|---|
| Output type | Discrete categories | Continuous values |
| Example | Is this email spam? | What will the house cost? |
| Loss function | Cross-entropy, Hinge | MSE, MAE |
| Metrics | Accuracy, F1, AUC | R², RMSE, MAE |
| Algorithms | SVM, Decision Tree, KNN | Linear Regression, SVR |
Common Supervised Algorithms
For Classification
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
# Load dataset
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
data.data, data.target, test_size=0.2, random_state=42
)
# Compare multiple classifiers
classifiers = {
"Logistic Regression": LogisticRegression(max_iter=10000),
"Decision Tree": DecisionTreeClassifier(random_state=42),
"Random Forest": RandomForestClassifier(random_state=42),
"SVM": SVC(random_state=42),
"KNN": KNeighborsClassifier(),
}
print("Algorithm Comparison on Breast Cancer Dataset:")
print("-" * 50)
for name, clf in classifiers.items():
scores = cross_val_score(clf, X_train, y_train, cv=5)
print(f"{name:25s}: {scores.mean():.4f} (+/- {scores.std():.4f})")For Regression
The Training Process Step by Step
Feature Importance in Supervised Learning
Understanding which features matter most helps you build better models:
Challenges in Supervised Learning
- Overfitting: Model memorizes training data
- Underfitting: Model too simple to learn patterns
- Class imbalance: Unequal distribution of labels
- Label noise: Incorrect labels in training data
- Feature selection: Choosing the right input variables
Handling Class Imbalance
from sklearn.utils.class_weight import compute_class_weight
from sklearn.ensemble import RandomForestClassifier
import numpy as np
# When classes are imbalanced (e.g., 95% negative, 5% positive)
class_weights = compute_class_weight('balanced', classes=np.unique(y_train), y=y_train)
weight_dict = dict(zip(np.unique(y_train), class_weights))
# Use class weights in the model
model = RandomForestClassifier(
class_weight='balanced', # Automatically handles imbalance
random_state=42
)
model.fit(X_train, y_train)
print(f"Class weights applied: {weight_dict}")Interview Questions
- What makes a problem suitable for supervised learning?
You need labeled data with clear input-output pairs, a well-defined prediction task, and enough training examples for the model to learn generalizable patterns.
- How do you handle a dataset with 1 million rows but only 100 labeled?
Use semi-supervised learning, active learning (query uncertain samples for labeling), transfer learning from a related task, or self-training where the model labels confident predictions.
- What's the difference between parametric and non-parametric supervised models?
Parametric models (linear regression, logistic regression) have a fixed number of parameters regardless of data size. Non-parametric models (KNN, decision trees) grow in complexity with more data.
- How do you choose between classification algorithms?
Consider dataset size, feature types, interpretability needs, training time constraints, and whether you need probability outputs. Start simple (logistic regression) and increase complexity only if needed.
- What is the curse of dimensionality in supervised learning?
As features increase, the data becomes sparse in high-dimensional space, distances become less meaningful, and you need exponentially more data to maintain the same density.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Supervised Learning.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Machine Learning topic.
Search Terms
machine-learning, machine learning, machine, learning, fundamentals, supervised, supervised learning
Related Machine Learning Topics