Machine Learning: dai principi fondamentali alla pratica
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.
Salva o stampa questo cheatsheet in PDF
Versione ottimizzata per la stampa: aprila con un clic e salva come PDF dal browser, senza account né email.
Project workflow and checklist
It is a loop: each step can send you back to an earlier one.
- Frame the problem: what decision will the prediction change? Classification or regression? Which metric defines success?
- Get data and check it: size, missing values, label quality, and whether it represents the cases you will meet later.
- Split FIRST (train/test, stratify for classification, by time for forecasting) and touch the test set only once at the end.
- Build a baseline (mean, most frequent class) so every score has a reference point.
- Put preprocessing and model in one Pipeline; fit everything on training data only.
- Choose and tune with cross-validation, never with the test set.
- Evaluate once on the test set with a metric that matches the goal; inspect errors, not just the score.
- 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.
| Algorithm | Task | Needs scaling | Explainable | Watch out for |
|---|---|---|---|---|
| Linear regression | Regression | For GD / regularised variants | Yes | Only straight-line relationships; sensitive to outliers. |
| Ridge / Lasso | Regression | Yes | Yes | Pick alpha by validation; Lasso can drop features, Ridge only shrinks. |
| Logistic regression | Classification | Yes (with regularisation) | Yes | Linear decision boundary; tune the threshold, not just 0.5. |
| k-nearest neighbours | Both | Yes, essential | Somewhat | Slow on large data; hurt by irrelevant features; choose k by CV. |
| Naive Bayes | Classification | No | Yes | Assumes independent features; probabilities are often over-confident. |
| Decision tree | Both | No | Yes (if shallow) | Overfits easily: limit max_depth or min_samples_leaf. |
| Random forest | Both | No | Partly | Strong default; bigger and slower; feature importances can mislead. |
| Gradient boosting | Both | No | Partly | Often the most accurate on tables; needs tuning and care against overfitting. |
| Support vector machine | Both | Yes | No | Slow on very large data; kernel and C need tuning. |
| k-means | Clustering | Yes | Somewhat | You must choose k; assumes round, similar-sized clusters. |
| DBSCAN | Clustering | Yes | Somewhat | Finds arbitrary shapes and isolates noise; sensitive to eps and min_samples. |
| PCA | Dimensionality reduction | Yes | Yes | Linear compression into orthogonal components; misses non-linear manifolds. |
| Multilayer perceptron (MLP) | Both | Yes, essential | No (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_ # biasSave 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
| Metric | Formula | In words | Use when |
|---|---|---|---|
| MAE | mean(|y − ŷ|) | Average size of the error, in target units | You want the typical error |
| RMSE | sqrt(mean((y − ŷ)²)) | Like MAE but punishes large errors more | Big mistakes are especially costly |
| R² | 1 − Σ(y − ŷ)² / Σ(y − ȳ)² | Share of variance explained; 0 = no better than the mean | Comparing against the mean baseline |
| Accuracy | (TP + TN) / all | How often it is right | Balanced classes only |
| Precision | TP / (TP + FP) | Of the flagged cases, how many are real | False alarms are costly |
| Recall | TP / (TP + FN) | Of the real cases, how many were found | Misses are costly |
| F1 | 2PR / (P + R) | Harmonic mean of precision and recall | Imbalanced classes, both matter |
| ROC AUC | area under TPR vs FPR | Chance a random positive outranks a random negative | Comparing 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 columnSelect
a[:, -2:] # last two columns a[a > 3] # boolean mask a - a.mean(axis=0) # broadcastingSeeds 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
| Model | Parameter | Typical range | Effect |
|---|---|---|---|
| Ridge / Lasso | alpha | 0.001 … 100 (log scale) | Higher = simpler model, risk of underfitting |
| Logistic regression | C | 0.01 … 100 (log scale) | Inverse of regularisation: higher C = weaker penalty |
| kNN | n_neighbors | 1 … 25, odd | Small = jagged boundary (overfit), large = smooth (underfit) |
| Decision tree | max_depth | 2 … 10 | Deeper = more flexible, more overfitting |
| Random forest | n_estimators | 100 … 500 | More trees = more stable, slower |
| Gradient boosting | learning_rate | 0.01 … 0.3 | Smaller needs more rounds but generalises better |
| SVM | C, gamma | 0.1 … 100 (log scale) | Margin softness and kernel width |
| k-means | n_clusters | 2 … 10 | Number of groups, chosen with elbow or silhouette |
| PCA | n_components | 2 … min(n, p) | Dimension target or variance ratio (e.g. 0.95) |
| DBSCAN | eps, min_samples | eps > 0, min_samples ≥ 3 | Neighborhood radius and core point density threshold |
| MLP | hidden_layer_sizes, alpha | (32,), (64, 32), alpha 1e-4 … 1 | Layer capacity and L2 regularisation penalty |
Common mistakes and how to avoid them
| Mistake | Why it hurts | Fix |
|---|---|---|
| Scaling before splitting | Test rows influence the training statistics (leakage) | Split first; fit scalers inside a Pipeline |
| A feature built from the target | Looks brilliant, useless in production | Keep only what is known at prediction time |
| Tuning on the test set | The test score becomes optimistic | Tune with cross-validation; use the test set once |
| Judging only by accuracy | Imbalanced classes hide a useless model | Use a baseline, precision, recall, F1 or AUC |
| Random split on time series | The model trains on the future | Split by time: train on the past, test on the future |
| Unscaled features with kNN / SVM / regularisation | Large-range features dominate | Standardise inside the pipeline |
| No fixed random_state | Results change on every run | Set seeds so experiments are comparable |
| Permutation importance on train set | Overfitted models look artificially important | Always evaluate permutation importance on a held-out test set |
| Unchecked pickle files | Arbitrary code execution on deserialize | Use joblib/pickle only with trusted internal artifacts |
| Ignoring concept and data drift | Model performance silently degrades in production | Monitor feature distributions and prediction outputs continuously |
Glossary
| Term | Meaning |
|---|---|
| Sample | One row of data: one example. |
| Feature | An input column used to predict. |
| Label / target | The value we want to predict. |
| Parameter | A number the model learns (weights, intercept). |
| Hyperparameter | A setting you choose before training (alpha, k, depth). |
| Loss | A number that says how wrong the model is; training minimises it. |
| Overfitting | Great on training data, poor on new data: the model memorised noise. |
| Underfitting | Poor even on training data: the model is too simple. |
| Generalisation | Performance on data the model has never seen. |
| Data leakage | Information from outside the training data slipping into training. |
| Baseline | A trivial model that every real model must beat. |
| Threshold | The probability above which a sample is predicted positive. |
| Inertia | Sum of squared distances from samples to their closest cluster centre in k-means. |
| Eigenvector | A direction preserved under linear transformation up to scaling; principal axes in PCA. |
| Backpropagation | Algorithm computing gradients of the loss with respect to all network weights via the chain rule. |
| Concept drift | A change in the statistical relationship between features and target over time. |
| Disparate impact | Ratio of favourable outcome rates between an unprivileged and a privileged demographic group. |