Skip to content

42. Deep learning with PyTorch — Mini-project

The retention team of the subscription business runs every model through scikit-learn: a Pipeline with a ColumnTransformer, cross_val_score for evaluation and one predict_proba call in production (module 34). The lesson showed that a small PyTorch network ranks churners better than their logistic regression. But a bare nn.Module has no fit and no predict_proba, so it does not fit into their tools.

Your job: write TorchMLPClassifier, a scikit-learn estimator that trains a PyTorch MLP inside fit(). It must work in a Pipeline, survive clone() and cross_val_score, and save only tensors and plain values (no pickled classes), so that torch.load(..., weights_only=True) can read its file.

This project joins the three object-oriented layers of the course. The estimator follows the minilearn and scikit-learn conventions (hyperparameters in __init__, learned attributes ending in _, fit returns self). The network inside it is an nn.Module. The training loop, early stopping and the safe save from the lesson connect the two.

data/customers.csv: 5,000 subscription customers with 12 features and the target churned (19.26% churners). See the data dictionary for every column.

Use the split of module 34: drop customer_id and signup_date, then train_test_split(X, y, test_size=0.25, stratify=y, random_state=42). That gives 3,750 training customers and 1,250 test customers. The preprocessing is module 34’s ColumnTransformer: median imputation and scaling for the 8 numeric columns, one-hot encoding for the 4 text columns, 22 features in total.

  1. A class ChurnNet(nn.Module) that builds an MLP from n_features, a tuple of hidden sizes and a dropout rate, and returns one logit per row with shape (n,).
  2. A class TorchMLPClassifier(ClassifierMixin, BaseEstimator) whose __init__ takes only keyword hyperparameters with defaults and stores each one unchanged: hidden=(32, 16), dropout=0.2, lr=1e-3, weight_decay=0.01, batch_size=64, max_epochs=100, patience=5, validation_fraction=0.2, balanced=True and random_state=42.
  3. fit(X, y):
    • accepts NumPy arrays or DataFrames with numeric features and exactly two classes;
    • splits off a stratified validation set (validation_fraction, random_state);
    • trains ChurnNet with BCEWithLogitsLoss (with pos_weight = n_negative / n_positive when balanced=True), AdamW and a seeded, shuffled DataLoader;
    • stops early on the validation loss with patience, and restores the best weights;
    • sets classes_, n_features_in_, model_, history_ (validation loss per epoch), best_epoch_ and n_epochs_, and returns self.
  4. predict_proba(X) returns shape (n, 2), columns in the order of classes_. predict(X) returns labels from classes_ with a 0.5 threshold.
  5. Reproducibility: the same data and random_state give the same model. fit() must not change the global PyTorch random state of the caller. Call torch.set_num_threads(1) at the top of the module. Results can depend on the number of threads, and the default number differs between machines; one fixed thread gives the same additions in the same order everywhere. It also keeps parallel cross_val_score jobs from fighting over the CPU cores (oversubscription).
  6. save(path) writes the hyperparameters, classes_, n_features_in_, best_epoch_ and the state_dict with torch.save. A class method load(path) rebuilds a fitted estimator with torch.load(path, weights_only=True).
  7. A report that prints: the hold-out ROC-AUC of the PyTorch pipeline and of a logistic-regression pipeline, the 5-fold stratified cross-validated ROC-AUC of both on the training rows, and a check that the reloaded model predicts exactly like the original.
  1. Write the network. Build ChurnNet from the lesson’s ChurnMLP. Test it on a random batch of shape (4, 22): the output must have shape (4,).

  2. Write the constructor. List every hyperparameter as a keyword argument and store it as is. Do not validate or convert in __init__: scikit-learn’s clone() and get_params() rely on that rule (module 34). Print the estimator: it should show TorchMLPClassifier().

  3. Prepare the data in fit. Convert X to a float32 array, find classes_ with np.unique and encode the target as 0.0/1.0 for the second class. Split off the validation rows with stratify.

  4. Train with early stopping. Reuse the lesson’s loop: train one epoch, compute the validation loss in eval mode, keep a deep copy of the best state_dict, and stop after patience epochs without improvement. Restore the best weights at the end.

  5. Keep the global random state clean. Wrap the model creation and training in with torch.random.fork_rng(devices=[]): and call torch.manual_seed(self.random_state) inside it. fork_rng saves the global CPU generator and restores it when the block ends; devices=[] says that no GPU state needs saving.

  6. Predict. In predict_proba, use eval mode and torch.no_grad(), apply the sigmoid and stack 1 - p and p as two columns.

  7. Plug it into scikit-learn. Build Pipeline([("prep", preprocess), ("model", TorchMLPClassifier())]). Fit it on the training rows and score the test rows. Run cross_val_score with StratifiedKFold(5, shuffle=True, random_state=42) and scoring="roc_auc". Do the same for LogisticRegression(max_iter=1000).

  8. Save and load. Write save() and load(), save the fitted model to output/, load it into a new object and compare predict_proba on the test rows with np.array_equal.

A skeleton to start from:

torch_estimator.py (starter)
import copy
from typing import Self
import numpy as np
import torch
from sklearn.base import BaseEstimator, ClassifierMixin
from torch import nn
torch.set_num_threads(1)
class ChurnNet(nn.Module):
def __init__(self, n_features: int, hidden: tuple[int, ...], dropout: float) -> None:
super().__init__()
# TODO: Linear -> ReLU -> Dropout for each hidden size, then Linear(.., 1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
... # TODO: one logit per row, shape (n,)
class TorchMLPClassifier(ClassifierMixin, BaseEstimator):
def __init__(self, hidden=(32, 16), dropout=0.2) -> None: # TODO: add the rest
... # TODO: store each hyperparameter unchanged
def fit(self, X, y) -> Self:
... # TODO: classes_, validation split, training loop, early stopping
def predict_proba(self, X) -> np.ndarray:
... # TODO: eval mode, no_grad, sigmoid, two columns
def predict(self, X) -> np.ndarray:
... # TODO: threshold 0.5, map back to classes_
def save(self, path) -> None:
... # TODO: torch.save a dict of params, classes_, state_dict
@classmethod
def load(cls, path) -> "TorchMLPClassifier":
... # TODO: torch.load(path, weights_only=True) and rebuild
Criterion Points Full points when
ChurnNet 10 builds its layers from the hyperparameters; output shape (n,)
Estimator conventions 15 __init__ stores every hyperparameter unchanged; learned attributes end with _; fit returns self; clone() works
Training loop 20 zero_grad/backward/step; seeded DataLoader; train mode for training, eval mode and no_grad for validation
Early stopping 15 deep copy of the best weights; stops after patience bad epochs; best weights restored; history_ and best_epoch_ set
Prediction API 10 predict_proba has shape (n, 2) in classes_ order; predict returns original labels
Reproducibility 10 two fits give identical probabilities; the caller’s global RNG is unchanged
Save and load 10 the file holds only tensors and plain values (no pickled classes); weights_only=True; the reloaded model predicts exactly the same
Report 10 hold-out and cross-validated ROC-AUC for both models, with a one-sentence conclusion
  • Add a threshold hyperparameter to predict and choose it on the validation rows for a target recall of 0.75 (module 36).
  • Tune hidden, dropout and weight_decay with GridSearchCV on the pipeline (model__hidden, model__dropout, …). Keep the grid small: each fit trains a network.
  • Add a callbacks hyperparameter: a list of objects with an on_epoch_end(epoch, val_loss) method, as in the observer pattern of module 22. Use one to print a progress line every 5 epochs.
  • Compare with HistGradientBoostingClassifier from module 38 on the same folds, and with the fit time of each model.
  • Move the classes into a module churn_torch.py, write pytest tests for the requirements (module 14) and load the saved file from a separate script.
Reference solution

The network and the estimator:

torch_estimator.py
import copy
from pathlib import Path
from typing import Self
import numpy as np
import pandas as pd
import torch
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.model_selection import train_test_split
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
torch.set_num_threads(1) # same results on every machine, no oversubscription
class ChurnNet(nn.Module):
"""An MLP that returns one logit per row."""
def __init__(
self, n_features: int, hidden: tuple[int, ...], dropout: float
) -> None:
super().__init__()
layers: list[nn.Module] = []
size_in = n_features
for size_out in hidden:
layers += [nn.Linear(size_in, size_out), nn.ReLU(), nn.Dropout(dropout)]
size_in = size_out
layers.append(nn.Linear(size_in, 1))
self.net = nn.Sequential(*layers)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.net(x).squeeze(1)
class TorchMLPClassifier(ClassifierMixin, BaseEstimator):
"""A PyTorch MLP for binary classification with the scikit-learn API."""
def __init__(
self,
hidden: tuple[int, ...] = (32, 16),
dropout: float = 0.2,
lr: float = 1e-3,
weight_decay: float = 0.01,
batch_size: int = 64,
max_epochs: int = 100,
patience: int = 5,
validation_fraction: float = 0.2,
balanced: bool = True,
random_state: int = 42,
) -> None:
self.hidden = hidden
self.dropout = dropout
self.lr = lr
self.weight_decay = weight_decay
self.batch_size = batch_size
self.max_epochs = max_epochs
self.patience = patience
self.validation_fraction = validation_fraction
self.balanced = balanced
self.random_state = random_state
def fit(self, X, y) -> Self:
X = np.asarray(X, dtype=np.float32)
y = np.asarray(y)
self.classes_ = np.unique(y)
if len(self.classes_) != 2:
raise ValueError(f"expected 2 classes, got {len(self.classes_)}")
self.n_features_in_ = X.shape[1]
target = (y == self.classes_[1]).astype(np.float32)
parts = train_test_split(
X, target, test_size=self.validation_fraction, stratify=target,
random_state=self.random_state,
)
X_tr, X_va, y_tr, y_va = (torch.from_numpy(p) for p in parts)
with torch.random.fork_rng(devices=[]): # leave the caller's RNG alone
torch.manual_seed(self.random_state)
self.model_ = ChurnNet(
self.n_features_in_, tuple(self.hidden), self.dropout
)
n_pos, n_neg = (y_tr == 1).sum(), (y_tr == 0).sum()
pos_weight = n_neg / n_pos if self.balanced else None
loss_fn = nn.BCEWithLogitsLoss(pos_weight=pos_weight)
optimizer = torch.optim.AdamW(
self.model_.parameters(), lr=self.lr, weight_decay=self.weight_decay
)
loader = DataLoader(
TensorDataset(X_tr, y_tr), batch_size=self.batch_size, shuffle=True,
generator=torch.Generator().manual_seed(self.random_state),
)
self._train(loader, X_va, y_va, loss_fn, optimizer)
return self
def _train(self, loader, X_va, y_va, loss_fn, optimizer) -> None:
best_loss, best_state, bad_epochs = float("inf"), None, 0
self.history_: list[float] = []
for epoch in range(1, self.max_epochs + 1):
self.model_.train()
for xb, yb in loader:
optimizer.zero_grad()
loss_fn(self.model_(xb), yb).backward()
optimizer.step()
self.model_.eval()
with torch.no_grad():
val_loss = loss_fn(self.model_(X_va), y_va).item()
self.history_.append(val_loss)
if val_loss < best_loss:
best_loss, bad_epochs = val_loss, 0
best_state = copy.deepcopy(self.model_.state_dict())
self.best_epoch_ = epoch
else:
bad_epochs += 1
if bad_epochs >= self.patience:
break
self.n_epochs_ = epoch
self.model_.load_state_dict(best_state)
self.model_.eval()
def predict_proba(self, X) -> np.ndarray:
X = torch.from_numpy(np.asarray(X, dtype=np.float32))
self.model_.eval()
with torch.no_grad():
p = torch.sigmoid(self.model_(X)).numpy()
return np.column_stack([1 - p, p])
def predict(self, X) -> np.ndarray:
return self.classes_[(self.predict_proba(X)[:, 1] >= 0.5).astype(int)]
def save(self, path: str | Path) -> None:
torch.save({
"params": self.get_params(),
"classes": self.classes_.tolist(),
"n_features_in": self.n_features_in_,
"best_epoch": self.best_epoch_,
"state_dict": self.model_.state_dict(),
}, path)
@classmethod
def load(cls, path: str | Path) -> "TorchMLPClassifier":
ckpt = torch.load(path, weights_only=True)
est = cls(**ckpt["params"])
est.classes_ = np.array(ckpt["classes"])
est.n_features_in_ = ckpt["n_features_in"]
est.best_epoch_ = ckpt["best_epoch"]
est.model_ = ChurnNet(est.n_features_in_, tuple(est.hidden), est.dropout)
est.model_.load_state_dict(ckpt["state_dict"])
est.model_.eval()
return est

The training loop lives in a private helper, _train, so that fit reads as a list of steps. fork_rng saves the global generator before the block and restores it after, so seeding inside fit has no side effects. save stores only plain values and tensors: get_params() returns numbers, booleans and the hidden tuple, and classes_ becomes a list of ints.

First checks: conventions, a fit on the training rows and reproducibility.

from sklearn.base import clone
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
customers = pd.read_csv("data/customers.csv")
X = customers.drop(columns=["customer_id", "signup_date", "churned"])
y = customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
def make_preprocess() -> ColumnTransformer:
return ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
make_column_selector(dtype_include="number")),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False),
make_column_selector(dtype_include="str")),
])
torch_pipe = Pipeline([("prep", make_preprocess()), ("model", TorchMLPClassifier())])
print(torch_pipe.named_steps["model"])
print(clone(TorchMLPClassifier(hidden=(64, 32))))
torch.manual_seed(0)
state_before = torch.get_rng_state()
torch_pipe.fit(X_train, y_train)
print("global RNG unchanged:", torch.equal(state_before, torch.get_rng_state()))
model = torch_pipe.named_steps["model"]
print(f"epochs run {model.n_epochs_}, best epoch {model.best_epoch_},"
f" best val loss {min(model.history_):.4f}")
again = clone(torch_pipe).fit(X_train, y_train)
same = np.array_equal(again.predict_proba(X_test), torch_pipe.predict_proba(X_test))
print("refit gives the same probabilities:", same)
assert same
Output
TorchMLPClassifier()
TorchMLPClassifier(hidden=(64, 32))
global RNG unchanged: True
epochs run 22, best epoch 17, best val loss 0.7999
refit gives the same probabilities: True

print shows only the hyperparameters that differ from their defaults, as for every scikit-learn estimator: BaseEstimator provides this from your __init__ signature. clone works because __init__ stores the arguments unchanged. The global generator is the same before and after fit, and a second fit gives identical probabilities.

The report: hold-out and cross-validated ROC-AUC against logistic regression.

log_pipe = Pipeline([
("prep", make_preprocess()),
("model", LogisticRegression(max_iter=1000)),
]).fit(X_train, y_train)
torch_auc = roc_auc_score(y_test, torch_pipe.predict_proba(X_test)[:, 1])
log_auc = roc_auc_score(y_test, log_pipe.predict_proba(X_test)[:, 1])
print(f"hold-out ROC-AUC TorchMLP {torch_auc:.3f} logistic {log_auc:.3f}")
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
torch_cv = cross_val_score(torch_pipe, X_train, y_train, cv=cv, scoring="roc_auc")
log_cv = cross_val_score(log_pipe, X_train, y_train, cv=cv, scoring="roc_auc")
print("TorchMLP folds:", torch_cv.round(3))
print(f"5-fold ROC-AUC TorchMLP {torch_cv.mean():.3f} ± {torch_cv.std():.3f}"
f" logistic {log_cv.mean():.3f} ± {log_cv.std():.3f}")
gap = torch_cv - log_cv # same folds, so the differences are paired
print("per-fold gap:", gap.round(3), "| positive in every fold:", bool((gap > 0).all()))
print(torch_pipe.predict(X_test.head(5)), y_test.head(5).to_numpy())
assert torch_cv.mean() > log_cv.mean()
Output
hold-out ROC-AUC TorchMLP 0.828 logistic 0.813
TorchMLP folds: [0.823 0.823 0.824 0.83 0.815]
5-fold ROC-AUC TorchMLP 0.823 ± 0.005 logistic 0.813 ± 0.011
per-fold gap: [ 0.018 0.012 -0.002 0.006 0.019] | positive in every fold: False
[0 1 0 1 0] [0 1 0 0 1]

cross_val_score cloned the whole pipeline five times and called fit and predict_proba on each clone, exactly as it does for a built-in model. Both models use the same folds, so the per-fold differences are paired: each one compares the two models on exactly the same customers. The network is ahead in 4 of the 5 folds, by 0.6 to 1.9 points, and behind by 0.2 points in one. On average it gains 1.0 point in cross-validation and 1.5 points on the hold-out set: a modest gain that is fairly consistent, not guaranteed on every sample. predict returns the original labels 0 and 1.

Save the fitted network and load it back.

out_dir = Path("output")
out_dir.mkdir(exist_ok=True)
model.save(out_dir / "churn_torch.pt")
reloaded = TorchMLPClassifier.load(out_dir / "churn_torch.pt")
print(reloaded)
print(reloaded.classes_, reloaded.n_features_in_, reloaded.best_epoch_)
X_test_prep = torch_pipe.named_steps["prep"].transform(X_test)
identical = np.array_equal(reloaded.predict_proba(X_test_prep),
model.predict_proba(X_test_prep))
print("reloaded predicts identically:", identical)
assert identical
Output
TorchMLPClassifier()
[0 1] 22 17
reloaded predicts identically: True

The file holds only plain values and tensors, so weights_only=True loads it, and the rebuilt network predicts exactly as before. In production you would save the fitted preprocessing too: the ColumnTransformer with joblib (module 34) and the network with save(), or the whole pipeline with joblib if the estimator class lives in an importable module.

Conclusion: the PyTorch MLP fits into the scikit-learn tooling with no special cases, and it beats the logistic baseline by 1.5 points of ROC-AUC on the hold-out set and by 1.0 point on average in cross-validation. It is ahead in 4 of the 5 folds. Whether that gain is worth a slower, less interpretable model is a business decision; module 43 gives you the tools to explain it.