LearnPy Hub
Machine LearningAdvancedLesson 31 of 32

ML Project: Classification

1Level 1 · BasicsBasics

In the scikit-learn lesson you met fit, predict, a train/test split and accuracy. Real projects need more than that: the data arrives messy, some values are missing, some columns are words instead of numbers, and you have to pick a model and prove it works. This lesson walks you through a complete classification project from the raw file to a prediction for a brand-new example, in seven numbered steps. Every step has a runnable example, and at the end the whole project fits in one cell.

The first run downloads pandas, scikit-learn and Matplotlib into your browser, so give it up to a minute. After that each example runs in a few seconds.

The seven steps

A classification project predicts a category (a class): pass or fail, cancer or not, which species. Almost every project follows the same route:

StepWhat you doMain tools
1. LoadGet the data into a DataFrame and tidy the column namesload_breast_cancer(as_frame=True), pd.read_csv
2. Explore (EDA)Check size, types, gaps, ranges and the class balanceshape, info(), describe(), isnull(), value_counts()
3. PreprocessPlan how to fill gaps, turn words into numbers and scaleSimpleImputer, OneHotEncoder, StandardScaler, ColumnTransformer, Pipeline
4. SplitSeparate features from the target, then hide a test settrain_test_split
5. FitTrain one or more models on the training setLogisticRegression, KNeighborsClassifier, DecisionTreeClassifier, RandomForestClassifier
6. EvaluateMeasure on the test set and compare models fairlyconfusion_matrix, classification_report, cross_val_score
7. PredictUse the chosen model on new examplespredict, predict_proba

We use two datasets. The breast cancer dataset comes with scikit-learn: 569 tumours, 30 measurements each, and a label saying whether the tumour is malignant (cancer) or benign (not cancer). The second is a small, deliberately messy student results file with gaps and text columns, so you can practise cleaning.

Step 1: load the data

Bundled datasets load straight into pandas with as_frame=True. The features go into data.data (a DataFrame) and the answers into data.target (a Series):

from sklearn.datasets import load_breast_cancer

data = load_breast_cancer(as_frame=True)
df = data.frame                 # features + a "target" column
print(data.target_names)        # ['malignant' 'benign'] means 0 and 1

Your own data usually comes as a CSV file. pd.read_csv("file.csv") reads it; in these examples we put the CSV text in a string and read it with io.StringIO, which pandas treats exactly like a file. Real files are messy, so tidy them as you load:

  • Column names with spaces, capitals or symbols (" Study Hours ", "Attendance %") are hard to type. Clean them once: df.columns = df.columns.str.strip().str.lower(), then rename the awkward ones.
  • Missing markers such as "N/A", "-" or "?" should become real missing values: pd.read_csv(..., na_values=["N/A", "-", "?"]). Otherwise a number column is read as text.
  • Inconsistent text such as "cse" and "CSE " should be made identical with .str.strip().str.upper().
  • ID columns (a roll number) carry no pattern; drop them before modelling.

Step 2: explore the data (EDA)

The EDA lesson covers this in depth. For a classification project, check at least these:

CheckCodeWhy it matters
Sizedf.shapeTiny data means noisy scores; many columns means you may need to pick features
Typesdf.info()Text columns need encoding; numbers stored as text need fixing
Rangesdf.describe()Very different ranges mean you should scale; impossible values are errors
Gapsdf.isnull().sum()Most models crash on missing values, so you must fill or drop them
Class balancey.value_counts(normalize=True)With 90% of one class, accuracy alone is misleading

The baseline is the accuracy you'd get by always guessing the most common class. In the breast cancer data 63% of tumours are benign, so a "model" that always says benign scores 0.63. Your model must clearly beat its baseline to be worth anything.

Step 3: preprocessing and cleaning

Models only understand complete tables of numbers. Preprocessing turns raw columns into that form. scikit-learn gives you a tool for each job:

ProblemToolWhat it does
Missing numbersSimpleImputer(strategy="median")Fills each gap with the column's median
Missing categoriesSimpleImputer(strategy="most_frequent")Fills each gap with the most common value
Category features (dept, gender)OneHotEncoderMakes one 0/1 column per category: dept_CSE, dept_EEE, ...
Text target (Pass/Fail)LabelEncoderTurns the classes into 0, 1, 2, ... (alphabetical)
Different rangesStandardScalerShifts and stretches each column to mean 0 and standard deviation 1

Why one-hot and not just CSE=0, EEE=1, BBA=2? Because numbers suggest an order and a distance: the model would think BBA is "twice" EEE. One-hot columns carry no fake order. LabelEncoder is fine for the target, because the model treats target classes as names, not amounts. Use OneHotEncoder(handle_unknown="ignore") so a category the model never saw (a new department) doesn't crash it.

Which models need scaling? KNN measures distances and logistic regression adds up weighted features, so a column in the thousands drowns one between 0 and 1: scale for them. Decision trees and random forests only ask "is this value above a threshold?", so scaling makes no difference to them, but it does no harm.

Fit on the training data only

Every preprocessing tool has fit (learn something: the median, the categories, the mean and spread) and transform (apply it). If you fit the imputer or scaler on the whole dataset, information from the test rows leaks into training, and your test score comes out a little too good. This is called data leakage. The rule: split first, fit preprocessing on the training set only, then transform both sets.

Doing that by hand is easy to get wrong, so we join everything into one object:

  • A Pipeline chains steps: Pipeline([("impute", SimpleImputer()), ("scale", StandardScaler())]). Calling fit on it fits each step in order; predict runs the same steps on new data.
  • A ColumnTransformer sends different columns to different steps: number columns to impute + scale, category columns to impute + one-hot.
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline

prep = ColumnTransformer([
    ("num", Pipeline([("impute", SimpleImputer(strategy="median")),
                      ("scale", StandardScaler())]), num_cols),
    ("cat", Pipeline([("impute", SimpleImputer(strategy="most_frequent")),
                      ("onehot", OneHotEncoder(handle_unknown="ignore"))]), cat_cols),
])
model = Pipeline([("prep", prep), ("clf", LogisticRegression())])
model.fit(X_train, y_train)     # every step learns from the training rows only

Now the whole recipe, from raw columns to prediction, is one model. That's also what makes cross-validation in step 6 leak-free.

Step 4: split the data

First separate the features X (every column you predict from) from the target y (the column you predict). Never leave the target inside X, or the model just copies the answer.

X = df.drop(columns=["result"])
y = df["result"]
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y)
ArgumentMeaning
test_size=0.2Keep 20% of rows for the test; 0.2 to 0.3 is usual
random_state=42The same shuffle every run, so results can be repeated
stratify=yKeep the same class shares in both parts; important when a class is rare

Notice the order: you plan the preprocessing in step 3, but it is only fitted in step 5, on the training rows.

Step 5: fit the models

Don't bet on one model. Try a few different kinds; they all use the same fit/predict methods, so it costs one line each:

ModelHow it decidesNeeds scaling?Good to know
LogisticRegressionAdds up weighted features and turns the total into a probabilityYesFast, a strong simple baseline, easy to explain
KNeighborsClassifierVotes among the k nearest training examplesYesNo real training; slow to predict on huge data
DecisionTreeClassifierA flowchart of yes/no questionsNoEasy to read, but overfits unless you limit max_depth
RandomForestClassifierMany trees on random samples vote togetherNoUsually accurate with little tuning; harder to explain

After fit, a model gives two kinds of answer. predict(X) returns the class for each row. predict_proba(X) returns the probability of each class: one column per class, in the order of model.classes_, each row adding up to 1. predict simply picks the class with the highest probability (for two classes, above 0.5).

Step 6: evaluate the model

For two classes, choose which one is positive (the one you're hunting for: malignant, fail, fraud). The confusion matrix then has four cells:

Predicted negativePredicted positive
Actually negativeTN (true negative)FP (false positive: a false alarm)
Actually positiveFN (false negative: a miss)TP (true positive)
MetricFormulaQuestion it answers
Accuracy(TP + TN) / allWhat share of all predictions was right?
PrecisionTP / (TP + FP)When it says positive, how often is it right?
RecallTP / (TP + FN)Of the real positives, how many did it find?
F1 score2 × P × R / (P + R)One number balancing precision and recall

Which matters most depends on the cost of each mistake. Missing a cancer (a false negative) is far worse than an extra check-up (a false positive), so a cancer screen wants high recall. A spam filter that bins real email (false positives) is annoying, so it wants high precision.

classification_report(y_test, pred) prints precision, recall and F1 for every class, plus support (how many test rows of that class), the macro avg (plain average over classes) and the weighted avg (average weighted by support).

Comparing models fairly

  • Cross-validation: cross_val_score(model, X_train, y_train, cv=5) trains and scores five times on different folds of the training data. The mean is steadier than one test score, and the spread (standard deviation) shows how much luck is involved.
  • Overfitting check: compare the training score with the test score. A model at 1.00 on training but 0.92 on test has memorised details. A small gap is normal; a big one means simplify (lower max_depth, larger k) or get more data.
  • One table: put every model's train score, cross-validation mean and test score side by side in a DataFrame, and pick the simplest model that scores near the top.

Use the test set to confirm your final choice, not to choose between dozens of options; otherwise you slowly tune to the test set and it stops being "unseen".

Step 7: predict a new sample

A new example must have the same columns, with the same names, as the training features. Build it as a one-row DataFrame and pass it to the fitted pipeline, which fills gaps, encodes and scales it exactly as it did for the training data:

new = pd.DataFrame([{"dept": "CSE", "gender": "F", "hours": 6,
                     "attendance": 78, "prev_gpa": 2.9}])
model.predict(new)          # the class
model.predict_proba(new)    # how sure the model is

If you used LabelEncoder on the target, le.inverse_transform(...) turns 0/1 back into "Fail"/"Pass". Report the probability too: "Pass, 86% sure" is far more useful than "Pass". In a real app you would save the fitted pipeline with joblib.dump(model, "model.joblib") and load it later, so you don't retrain every time.

Key points: follow the seven steps: load, explore, preprocess, split, fit, evaluate, predict; tidy names and missing markers as you load; check the class balance and the baseline; impute gaps, one-hot encode category features, scale for distance and linear models; split first and fit all preprocessing on the training data only, which a Pipeline with a ColumnTransformer does for you; compare several models with cross-validation and a train-vs-test check; judge with precision, recall and F1, not accuracy alone; predict new samples from a DataFrame with the same columns.

Try it yourselfExample 1: Step 1: load a bundled dataset into a DataFrame

as_frame=True gives pandas objects instead of plain arrays. The target is 0 for malignant and 1 for benign; we add a readable label column so the table is easy to read.

example_1.py
Output appears here

Example 2: Step 1: load a messy CSV and tidy it

The names have spaces, capitals and a % sign, the departments are written three ways, and "N/A" marks a gap. na_values turns N/A into a real missing value, so attendance is read as numbers.

example_2.py
Output appears here

Example 3: Step 2: explore before you model

Size, types, ranges, gaps and the class balance. The ranges differ hugely (area in the hundreds, smoothness below 1), so we'll scale. The baseline is 0.627: always guessing benign. The chart shows that malignant tumours tend to be larger.

example_3.py
Output appears here

Example 4: Step 3: the preprocessing tools one at a time

Each tool learns something with fit and applies it with transform; fit_transform does both. Look at what each one produced: the filled gaps, the 0/1 columns, the 0/1 target and the scaled numbers.

example_4.py
Output appears here

Example 5: Step 3: join the steps with ColumnTransformer and Pipeline

Number columns are filled and scaled, category columns are filled and one-hot encoded, all in one object. It is fitted on the training rows only; the test rows are just transformed with what it learned there.

example_5.py
Output appears here

Example 6: Step 4: separate X and y, then split

We make malignant the positive class (1), because it's the one we're hunting for. stratify keeps the 37% malignant share almost the same in both parts.

example_6.py
Output appears here

Example 7: Step 5: fit four models, then predict and predict_proba

Logistic regression and KNN get a scaler in front; the trees don't need one. predict_proba shows how sure each model is: the second column is the chance of class 1 (malignant).

example_7.py
Output appears here

Example 8: Step 6: confusion matrix, precision, recall and F1

Precision, recall and F1 are worked out by hand from the four cells and then checked against scikit-learn. The report shows the same numbers for both classes.

example_8.py
Output appears here

Example 9: Step 6: compare models in one table

For each model: the training score, the 5-fold cross-validation mean and spread on the training data, the test score, and the train-test gap. The unlimited tree is perfect on its training data but has the lowest test score and the biggest gap: it has overfitted. The forest is also perfect on training, but averaging many trees keeps its test score high.

example_9.py
Output appears here

Example 10: Step 7: predict new students

The fitted pipeline cleans the new rows exactly like the training rows: the missing hours is filled with the training median, and the unknown department "MATH" is ignored instead of crashing. inverse_transform turns 0/1 back into words.

example_10.py
Output appears here

Example 11: The whole project in one cell

300 made-up students with gaps and a text column, from loading to a prediction. Change the data, the models or the new student and run it again; this cell is a template for your own projects.

example_11.py
Output appears here

2Level 2 · IntermediateTuning with GridSearchCV, ROC-AUC and the decision threshold

Tuning hyperparameters with GridSearchCV

A hyperparameter is a setting you choose before training, such as n_neighbors for KNN or max_depth for a tree. Instead of trying values by hand, GridSearchCV tries every combination in a grid, scores each one with cross-validation on the training set, and keeps the best:

grid = GridSearchCV(pipe, {"knn__n_neighbors": [3, 5, 7, 9, 15],
                           "knn__weights": ["uniform", "distance"]}, cv=5)
grid.fit(X_train, y_train)
grid.best_params_, grid.best_score_
grid.score(X_test, y_test)      # the refitted best model, on the test set

With a pipeline, name a parameter as stepname__parameter (two underscores). The grid above has 5 × 2 = 10 combinations, and with cv=5 that's 50 fits, so keep grids small. The test set stays untouched until the very end. Pass scoring="f1" or scoring="recall" to tune for the metric you care about instead of accuracy.

ROC curve and AUC

predict labels a row positive when its probability is above 0.5. That 0.5 is a threshold, and you can move it. The ROC curve (receiver operating characteristic) shows every threshold at once: the true positive rate (recall) against the false positive rate (the share of negatives wrongly flagged). A perfect model hugs the top-left corner; random guessing is the diagonal.

The AUC (area under the curve) sums the curve up in one number: 1.0 is perfect and 0.5 is a coin toss. A nice way to read it: the AUC is the chance that a randomly picked positive gets a higher probability than a randomly picked negative. Compute it from probabilities, not labels: roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]). Because it doesn't depend on one threshold, AUC is handy for comparing models.

Choosing your own threshold

Lowering the threshold flags more rows as positive: recall goes up and precision goes down. Raising it does the opposite. For a cancer screen you might accept more false alarms to miss fewer cancers:

proba = model.predict_proba(X_test)[:, 1]
pred = (proba >= 0.3).astype(int)     # flag anything above 30%

Pick the threshold using the training data or cross-validation, not by peeking at the test set.

Example 12: Tuning KNN with GridSearchCV

Ten combinations are each scored with 5-fold cross-validation on the training data. The best settings are refitted on all training rows and only then checked on the test set.

example_12.py
Output appears here

Example 13: ROC curves and AUC

Both models are scored from their probabilities. The logistic regression curve hugs the top-left corner (AUC near 1); the shallow tree only has a few distinct probabilities, so its curve is blocky and its AUC lower.

example_13.py
Output appears here

Example 14: Moving the decision threshold

The same model and the same probabilities, read with different thresholds. As the threshold falls, more tumours are flagged, fewer cancers are missed and there are more false alarms.

example_14.py
Output appears here

3Level 3 · AdvancedImbalanced classes and feature importance

When one class is rare

Fraud, rare diseases and machine faults are imbalanced problems: the class you care about may be 5% of the rows or less. A model can then reach 95% accuracy by ignoring that class completely. Signs of trouble: high accuracy but low recall for the rare class in classification_report.

What helps:

FixHow
Split with stratify=ySo the rare class appears in both training and test sets
Better metricsRecall, precision and F1 for the rare class; balanced_accuracy_score (the average of the recalls of each class); ROC-AUC
class_weight="balanced"Makes each mistake on a rare-class row count more during training, in proportion to how rare it is. Supported by LogisticRegression, DecisionTreeClassifier, RandomForestClassifier and others
Move the thresholdFlag the rare class at a lower probability, as in the intermediate stage
Tune for the right metricGridSearchCV(..., scoring="f1") or scoring="recall"

class_weight="balanced" usually trades some precision for a lot more recall on the rare class. Whether that's a good deal depends on what a miss costs compared with a false alarm.

Which features matter?

Knowing why a model decides helps you trust it, explain it and spot leakage. Three common views:

  • Tree importances: forest.feature_importances_ says how much each feature reduced impurity across the trees. Quick, but it can overrate features with many distinct values.
  • Logistic regression coefficients: model.coef_. On scaled features, a bigger absolute value means more influence; the sign says which class the feature pushes towards.
  • Permutation importance: permutation_importance(model, X_test, y_test) shuffles one column at a time and measures how much the test score drops. It works for any model and is measured on unseen data, so it's the most honest of the three.

Correlated features share their importance: if two columns carry the same information, shuffling one barely hurts because the other still holds it. So a low importance doesn't always mean a useless feature.

Example 15: An imbalanced problem and class_weight

Only about 5% of the rows are class 1. The plain model looks great on accuracy but misses many of the rare cases. class_weight="balanced" finds far more of them, at the cost of some false alarms; balanced accuracy shows the improvement that plain accuracy hides.

example_15.py
Output appears here

Example 16: Feature importance three ways

The forest's importances, the logistic regression coefficients (on scaled features) and permutation importance on the test set. The forest and permutation importance agree that the "worst" concave points and size measurements matter most. The coefficients rank features differently, because many of these columns are strongly correlated and the linear model spreads the weight among them. The chart shows the permutation importances.

example_16.py
Output appears here

Example 17: Putting it together: tune for F1 on imbalanced data

GridSearchCV tries class_weight and the forest's max_depth together, scoring each combination by F1 on the rare class, then reports the winner on the test set with ROC-AUC and a full report.

example_17.py
Output appears here
Common mistakeFitting the scaler or imputer before splitting, for example X = StandardScaler().fit_transform(X) and then train_test_split(X, y). The scaler has already seen the test rows, so the test score is slightly too optimistic, and in real projects the leak can be much bigger. Split first, then put every preprocessing step inside a Pipeline and call fit only on X_train. A second classic slip: forgetting to drop the target (or a column computed from it) from X, which gives a "perfect" model that's useless on new data.
Exercise · predict the output

1 is the positive class. What does this print (precision, then recall)?

from sklearn.metrics import precision_score, recall_score
y_true = [1, 1, 1, 0, 0, 0]
y_pred = [1, 1, 1, 1, 0, 0]
print(precision_score(y_true, y_pred), recall_score(y_true, y_pred))
Quick quiz · 9 questions
1. What is the correct order of a classification project?
2. A "dept" feature has the values CSE, EEE and BBA. What's the best way to give it to a logistic regression model?
3. Why must you fit the StandardScaler on the training set only?
4. What does stratify=y do in train_test_split?
5. Which pair of models benefits most from scaling the features?
6. A model scores 1.00 on the training set and 0.85 on the test set. What's the most likely problem?
7. In a cancer screening model, which metric should be high so that few real cancers are missed?
8. What does model.predict_proba(X) return for a two-class problem?
9. 90% of the rows are "Pass". What accuracy does a model that always predicts "Pass" get (the baseline)?
Ready to practice ml project: classification?

Graded problems for this topic are coming soon.

Practice this topic →
Python ML Project: Classification · LearnPy Hub