ML Notes
Quick reference guide for ML interview prep with algorithms, formulas, time complexities, and key concepts.
A comprehensive quick reference for machine learning interviews. Print this out, memorize key concepts, and reference it when practicing.
Algorithm Complexity Cheatsheet
| Algorithm | Time Complexity | Space | Best For |
|---|---|---|---|
| Linear Regression | O(n*d) | O(d) | Small datasets, interpretability |
| Logistic Regression | O(n*d*i) | O(d) | Binary classification |
| K-Means | O(n*k*i*d) | O(n+k*d) | Clustering, unlabeled data |
| KNN | O(n*d) predict | O(n*d) | Non-linear boundaries |
| Decision Tree | O(n*d*log n) | O(log n) depth | Interpretability, non-linear |
| Random Forest | O(n*m*log n) | O(m*log n) | High accuracy, generalization |
| SVM | O(n²) to O(n³) | O(n) | Small-medium datasets |
| Gradient Boosting | O(n*m*i) | O(m) | Best performance, competitions |
| Neural Networks | O(n*h*i) | O(h) | Complex patterns, large data |
| K-NN Search | O(n*d) naive, O(log n) with tree | O(n*d) | Fast retrieval |
Key Metrics Reference
Classification Metrics
Regression Metrics
Clustering Metrics
| Silhouette Score | measures how similar object is to own cluster vs others |
| Range | -1 to 1 (higher is better) |
| Davies-Bouldin Index | ratio of within to between cluster distances |
| Range | 0 to ∞ (lower is better) |
| Inertia | sum of squared distances to nearest centroid (for K-Means) |
Model Selection Guide
When to Use Each Algorithm
| Problem | Algorithm | Reason |
|---|---|---|
| High-dimensional data | Linear models, SVM | Curse of dimensionality |
| Non-linear boundaries | Random Forest, Neural Nets | Can learn complex patterns |
| Imbalanced classification | XGBoost with scale_pos_weight | Handles class imbalance well |
| Large dataset (>1M rows) | Gradient Boosting, Neural Nets | Scalable training |
| Need interpretability | Linear models, Decision Trees | Easy to explain |
| Fast inference needed | Decision Trees, SVM | Low latency serving |
| Few features, many samples | Linear Regression | Simple is better |
| Many features, few samples | Regularized models (Ridge/Lasso) | Prevents overfitting |
Bias-Variance Tradeoff
| - Solution | more features, more complex model |
| - Symptoms | High training error |
| - Solution | regularization, more data, cross-validation |
| - Symptoms | Low training error, high test error |
Regularization Techniques
L1 Regularization (Lasso)
loss = MSE + λ * Σ|weights|
Effect: Feature selection (some weights → 0)
L2 Regularization (Ridge)
loss = MSE + λ * Σ(weights²)
Effect: Weight shrinkage, no feature elimination
Elastic Net
loss = MSE + λ1*Σ|w| + λ2*Σ(w²)
Effect: Combination of L1 and L2
Early Stopping
- Monitor validation loss during training
- Stop when validation loss increases
- Prevents overfitting without explicit penalty
Feature Engineering Checklist
| - StandardScaler | (x - mean) / std |
| - MinMaxScaler | (x - min) / (max - min) |
| - RobustScaler | (x - median) / IQR |
| - Polynomial features | x1*x2, x1², etc |
| - Ratio features | x1/x2 |
| - IQR method | remove if x < Q1 - 1.5*IQR |
| - Z-score | remove if |z| > 3 |
Cross-Validation Strategies
K-Fold Cross-Validation (most common)
- Split data into k folds
- Train on k-1 folds, test on 1
- Repeat k times
- Report mean ± std of scores
Stratified K-Fold
- Maintains class distribution in each fold
- Better for imbalanced datasets
Time Series Cross-Validation
- Walk-forward: train on past, test on future
- Respects temporal ordering
Leave-One-Out (LOO)
- Each sample is test set once
- Only for small datasets (computationally expensive)
Hyperparameter Tuning
Grid Search
- Test all combinations
- Exhaustive but slow
- Best for small parameter spaces
Random Search
- Sample random combinations
- Often as good as grid search
- Faster for large spaces
Bayesian Optimization
- Uses Gaussian processes
- Smart sampling based on previous results
- Most efficient for expensive functions
Common Hyperparameters by Algorithm
├── Linear Models: regularization strength (C, λ)
├── Trees: max_depth, min_samples_split, min_samples_leaf
├── Ensemble: n_estimators, learning_rate, max_depth
├── SVM: C (regularization), kernel type, kernel parameters
├── Neural Networks: layers, units, learning_rate, batch_size, epochs
└── Clustering: k (number of clusters), distance metric
Handling Class Imbalance
| ├── Oversampling | duplicate minority class |
| ├── Undersampling | reduce majority class |
| ├── SMOTE | generate synthetic minority samples |
| ├── Default threshold | 0.5 |
Data Preparation Workflow
Neural Network Basics
Forward Pass
z = w*x + b (linear transformation)
a = activation(z) (non-linearity)
output = w_out*a + b_out (output layer)
Backpropagation
∂L/∂w = ∂L/∂a * ∂a/∂z * ∂z/∂w (chain rule)
Weight Update (Gradient Descent)
w_new = w_old - learning_rate * ∂L/∂w
Common Activation Functions
├── ReLU: max(0, x) [hidden layers, default]
├── Sigmoid: 1/(1+e^-x) [binary classification]
├── Tanh: (e^x - e^-x)/(e^x + e^-x) [-1 to 1 range]
└── Softmax: e^x_i / Σ(e^x) [multi-class, output]
Optimizers
├── SGD: w = w - lr*gradient
├── Momentum: accumulate gradient history
├── Adam: adaptive learning rates per parameter
└── RMSprop: root mean square propagation
Model Evaluation Checklist
□ Training Curve Analysis
- Plot training vs validation loss
- Look for overfitting/underfitting
- Check if loss is decreasing
□ Cross-Validation
- Use stratified k-fold
- Report mean ± std of metrics
- Check if folds have similar performance
□ Class Balance Check
- For classification: check class distribution
- In train, validation, test sets
- Use stratified split if imbalanced
□ Feature Importance
- Identify which features matter
- Remove uninformative features
- Check for data leakage
□ Error Analysis
- Which samples does model get wrong?
- Any patterns in errors?
- Could indicate data quality issues
□ Robustness Testing
- Test on different data distributions
- Stress test with edge cases
- Check sensitivity to input perturbationsCommon Interview Mistakes to Avoid
| Mistake | Fix |
|---|---|
| Not splitting train/test before preprocessing | Apply preprocessing to each fold separately |
| Using accuracy for imbalanced data | Use precision, recall, F1, AUC-ROC |
| Tuning hyperparameters on test set | Use validation set for tuning |
| Not handling categorical variables | One-hot encode or label encode before modeling |
| Forgetting to scale features | Always scale for distance-based algorithms |
| No baseline model | Compare new model to simple baseline |
| Overfitting to small dataset | Use cross-validation, regularization |
| Ignoring data quality | Understand and clean data first |
| Not testing edge cases | Test with missing values, outliers, etc |
Quick Python Snippets
# Standard ML workflow
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
# 1. Load and split data
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# 2. Scale features
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 3. Train model
model = RandomForestClassifier(n_estimators=100, max_depth=10)
model.fit(X_train, y_train)
# 4. Evaluate
train_score = model.score(X_train, y_train)
test_score = model.score(X_test, y_test)
cv_scores = cross_val_score(model, X_train, y_train, cv=5)
print(f"Train: {train_score:.4f}")
print(f"Test: {test_score:.4f}")
print(f"CV: {cv_scores.mean():.4f} ± {cv_scores.std():.4f}")
print(classification_report(y_test, model.predict(X_test)))Summary
Memorize:
- Key algorithm complexities
- Metric formulas and when to use them
- Bias-variance tradeoff
- Common hyperparameters
- Data preparation workflow
Practice implementing algorithms from scratch to really understand them. Good luck with your interviews!
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Machine Learning Interview Cheatsheet.
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, interview, preparation, cheatsheet, machine learning interview cheatsheet
Related Machine Learning Topics