Skip to main content

Machine Learning: from first principles to practice

Machine Learning Cheatsheet

A printable one-stop reference: the workflow, which algorithm to choose, the scikit-learn API, metrics, key hyperparameters and the mistakes that fool people most often. Print it with Ctrl/Cmd + P.

PDF / Print

Save or print this cheatsheet as PDF

Print-ready layout: open in one click and save as PDF from your browser, no account or email required.

Project workflow and checklist

It is a loop: each step can send you back to an earlier one.

  1. Frame the problem: what decision will the prediction change? Classification or regression? Which metric defines success?
  2. Get data and check it: size, missing values, label quality, and whether it represents the cases you will meet later.
  3. Split FIRST (train/test, stratify for classification, by time for forecasting) and touch the test set only once at the end.
  4. Build a baseline (mean, most frequent class) so every score has a reference point.
  5. Put preprocessing and model in one Pipeline; fit everything on training data only.
  6. Choose and tune with cross-validation, never with the test set.
  7. Evaluate once on the test set with a metric that matches the goal; inspect errors, not just the score.
  8. Deploy, monitor for drift, and retrain when performance decays.

Which algorithm should I choose?

Start simple. A linear or logistic model with good features is a strong baseline that is easy to explain.

AlgorithmTaskNeeds scalingExplainableWatch out for
Linear regressionRegressionFor GD / regularised variantsYesOnly straight-line relationships; sensitive to outliers.
Ridge / LassoRegressionYesYesPick alpha by validation; Lasso can drop features, Ridge only shrinks.
Logistic regressionClassificationYes (with regularisation)YesLinear decision boundary; tune the threshold, not just 0.5.
k-nearest neighboursBothYes, essentialSomewhatSlow on large data; hurt by irrelevant features; choose k by CV.
Naive BayesClassificationNoYesAssumes independent features; probabilities are often over-confident.
Decision treeBothNoYes (if shallow)Overfits easily: limit max_depth or min_samples_leaf.
Random forestBothNoPartlyStrong default; bigger and slower; feature importances can mislead.
Gradient boostingBothNoPartlyOften the most accurate on tables; needs tuning and care against overfitting.
Support vector machineBothYesNoSlow on very large data; kernel and C need tuning.
k-meansClusteringYesSomewhatYou must choose k; assumes round, similar-sized clusters.
DBSCANClusteringYesSomewhatFinds arbitrary shapes and isolates noise; sensitive to eps and min_samples.
PCADimensionality reductionYesYesLinear compression into orthogonal components; misses non-linear manifolds.
Multilayer perceptron (MLP)BothYes, essentialNo (black box)Can learn complex non-linear functions; requires scaling and regularisation.

scikit-learn essentials

Every estimator follows the same small interface.

  • The estimator pattern

    model = LogisticRegression()
    model.fit(X_train, y_train)
    model.predict(X_test)
    model.score(X_test, y_test)

    X is always 2-D: (n_samples, n_features). Use x.reshape(-1, 1) for a single feature.

  • Split

    from sklearn.model_selection import train_test_split
    X_tr, X_te, y_tr, y_te = train_test_split(
        X, y, test_size=0.2, random_state=0, stratify=y)
  • Pipeline (no leakage)

    from sklearn.pipeline import make_pipeline
    from sklearn.preprocessing import StandardScaler
    pipe = make_pipeline(StandardScaler(), LogisticRegression())
    pipe.fit(X_tr, y_tr)

    Transformers use fit_transform on training data and transform on new data.

  • Cross-validation

    from sklearn.model_selection import cross_val_score
    scores = cross_val_score(pipe, X, y, cv=5)
    print(scores.mean(), scores.std())
  • Probabilities and threshold

    p = model.predict_proba(X_te)[:, 1]
    pred = (p >= 0.3).astype(int)
  • Learned attributes end with _

    model.coef_      # weights
    model.intercept_ # bias
  • Save and load pipelines

    import joblib
    joblib.dump(pipe, "model.joblib")
    loaded = joblib.load("model.joblib")

    Pickle files execute arbitrary bytecode on load; load only trusted models in production.

Metrics at a glance

MetricFormulaIn wordsUse when
MAEmean(|y − ŷ|)Average size of the error, in target unitsYou want the typical error
RMSEsqrt(mean((y − ŷ)²))Like MAE but punishes large errors moreBig mistakes are especially costly
R²1 − Σ(y − ŷ)² / Σ(y − ȳ)²Share of variance explained; 0 = no better than the meanComparing against the mean baseline
Accuracy(TP + TN) / allHow often it is rightBalanced classes only
PrecisionTP / (TP + FP)Of the flagged cases, how many are realFalse alarms are costly
RecallTP / (TP + FN)Of the real cases, how many were foundMisses are costly
F12PR / (P + R)Harmonic mean of precision and recallImbalanced classes, both matter
ROC AUCarea under TPR vs FPRChance a random positive outranks a random negativeComparing models over all thresholds

numpy and pandas essentials

  • Arrays

    a = np.array([[1, 2, 3], [4, 5, 6]])
    a.shape          # (2, 3)
    a.reshape(-1, 1) # a column
    a.mean(axis=0)   # one value per column
  • Select

    a[:, -2:]       # last two columns
    a[a > 3]        # boolean mask
    a - a.mean(axis=0)  # broadcasting
  • Seeds and stats

    rng = np.random.default_rng(0)
    rng.normal(size=3)
    np.corrcoef(x, y)[0, 1]
    np.median(x); x.std()
  • DataFrames

    df[df["price"] > 200]
    df.groupby("city")["price"].mean()
    df["price"].describe()
    df.to_numpy()
  • Linear algebra

    a @ b             # matrix product
    np.dot(u, v)      # dot product
    np.linalg.norm(u) # length

Key hyperparameters and typical ranges

ModelParameterTypical rangeEffect
Ridge / Lassoalpha0.001 … 100 (log scale)Higher = simpler model, risk of underfitting
Logistic regressionC0.01 … 100 (log scale)Inverse of regularisation: higher C = weaker penalty
kNNn_neighbors1 … 25, oddSmall = jagged boundary (overfit), large = smooth (underfit)
Decision treemax_depth2 … 10Deeper = more flexible, more overfitting
Random forestn_estimators100 … 500More trees = more stable, slower
Gradient boostinglearning_rate0.01 … 0.3Smaller needs more rounds but generalises better
SVMC, gamma0.1 … 100 (log scale)Margin softness and kernel width
k-meansn_clusters2 … 10Number of groups, chosen with elbow or silhouette
PCAn_components2 … min(n, p)Dimension target or variance ratio (e.g. 0.95)
DBSCANeps, min_sampleseps > 0, min_samples ≥ 3Neighborhood radius and core point density threshold
MLPhidden_layer_sizes, alpha(32,), (64, 32), alpha 1e-4 … 1Layer capacity and L2 regularisation penalty

Common mistakes and how to avoid them

MistakeWhy it hurtsFix
Scaling before splittingTest rows influence the training statistics (leakage)Split first; fit scalers inside a Pipeline
A feature built from the targetLooks brilliant, useless in productionKeep only what is known at prediction time
Tuning on the test setThe test score becomes optimisticTune with cross-validation; use the test set once
Judging only by accuracyImbalanced classes hide a useless modelUse a baseline, precision, recall, F1 or AUC
Random split on time seriesThe model trains on the futureSplit by time: train on the past, test on the future
Unscaled features with kNN / SVM / regularisationLarge-range features dominateStandardise inside the pipeline
No fixed random_stateResults change on every runSet seeds so experiments are comparable
Permutation importance on train setOverfitted models look artificially importantAlways evaluate permutation importance on a held-out test set
Unchecked pickle filesArbitrary code execution on deserializeUse joblib/pickle only with trusted internal artifacts
Ignoring concept and data driftModel performance silently degrades in productionMonitor feature distributions and prediction outputs continuously

Glossary

TermMeaning
SampleOne row of data: one example.
FeatureAn input column used to predict.
Label / targetThe value we want to predict.
ParameterA number the model learns (weights, intercept).
HyperparameterA setting you choose before training (alpha, k, depth).
LossA number that says how wrong the model is; training minimises it.
OverfittingGreat on training data, poor on new data: the model memorised noise.
UnderfittingPoor even on training data: the model is too simple.
GeneralisationPerformance on data the model has never seen.
Data leakageInformation from outside the training data slipping into training.
BaselineA trivial model that every real model must beat.
ThresholdThe probability above which a sample is predicted positive.
InertiaSum of squared distances from samples to their closest cluster centre in k-means.
EigenvectorA direction preserved under linear transformation up to scaling; principal axes in PCA.
BackpropagationAlgorithm computing gradients of the loss with respect to all network weights via the chain rule.
Concept driftA change in the statistical relationship between features and target over time.
Disparate impactRatio of favourable outcome rates between an unprivileged and a privileged demographic group.