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.
Dataset
Section titled “Dataset”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.
Requirements
Section titled “Requirements”- A class
ChurnNet(nn.Module)that builds an MLP fromn_features, a tuple of hidden sizes and a dropout rate, and returns one logit per row with shape(n,). - 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=Trueandrandom_state=42. 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
ChurnNetwithBCEWithLogitsLoss(withpos_weight = n_negative / n_positivewhenbalanced=True),AdamWand a seeded, shuffledDataLoader; - 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_andn_epochs_, and returnsself.
predict_proba(X)returns shape(n, 2), columns in the order ofclasses_.predict(X)returns labels fromclasses_with a 0.5 threshold.- Reproducibility: the same data and
random_stategive the same model.fit()must not change the global PyTorch random state of the caller. Calltorch.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 parallelcross_val_scorejobs from fighting over the CPU cores (oversubscription). save(path)writes the hyperparameters,classes_,n_features_in_,best_epoch_and thestate_dictwithtorch.save. A class methodload(path)rebuilds a fitted estimator withtorch.load(path, weights_only=True).- 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.
Step plan
Section titled “Step plan”-
Write the network. Build
ChurnNetfrom the lesson’sChurnMLP. Test it on a random batch of shape(4, 22): the output must have shape(4,). -
Write the constructor. List every hyperparameter as a keyword argument and store it as is. Do not validate or convert in
__init__: scikit-learn’sclone()andget_params()rely on that rule (module 34). Print the estimator: it should showTorchMLPClassifier(). -
Prepare the data in
fit. ConvertXto a float32 array, findclasses_withnp.uniqueand encode the target as 0.0/1.0 for the second class. Split off the validation rows withstratify. -
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 afterpatienceepochs without improvement. Restore the best weights at the end. -
Keep the global random state clean. Wrap the model creation and training in
with torch.random.fork_rng(devices=[]):and calltorch.manual_seed(self.random_state)inside it.fork_rngsaves the global CPU generator and restores it when the block ends;devices=[]says that no GPU state needs saving. -
Predict. In
predict_proba, use eval mode andtorch.no_grad(), apply the sigmoid and stack1 - pandpas two columns. -
Plug it into scikit-learn. Build
Pipeline([("prep", preprocess), ("model", TorchMLPClassifier())]). Fit it on the training rows and score the test rows. Runcross_val_scorewithStratifiedKFold(5, shuffle=True, random_state=42)andscoring="roc_auc". Do the same forLogisticRegression(max_iter=1000). -
Save and load. Write
save()andload(), save the fitted model tooutput/, load it into a new object and comparepredict_probaon the test rows withnp.array_equal.
A skeleton to start from:
import copyfrom typing import Self
import numpy as npimport torchfrom sklearn.base import BaseEstimator, ClassifierMixinfrom 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 rebuildRubric
Section titled “Rubric”| 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 |
Stretch goals
Section titled “Stretch goals”- Add a
thresholdhyperparameter topredictand choose it on the validation rows for a target recall of 0.75 (module 36). - Tune
hidden,dropoutandweight_decaywithGridSearchCVon the pipeline (model__hidden,model__dropout, …). Keep the grid small: each fit trains a network. - Add a
callbackshyperparameter: a list of objects with anon_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
HistGradientBoostingClassifierfrom 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
Section titled “Reference solution”Reference solution
The network and the estimator:
import copyfrom pathlib import Pathfrom typing import Self
import numpy as npimport pandas as pdimport torchfrom sklearn.base import BaseEstimator, ClassifierMixinfrom sklearn.model_selection import train_test_splitfrom torch import nnfrom 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 estThe 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 clonefrom sklearn.compose import ColumnTransformer, make_column_selectorfrom sklearn.impute import SimpleImputerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import StratifiedKFold, cross_val_scorefrom sklearn.pipeline import Pipeline, make_pipelinefrom 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 sameTorchMLPClassifier()TorchMLPClassifier(hidden=(64, 32))global RNG unchanged: Trueepochs run 22, best epoch 17, best val loss 0.7999refit gives the same probabilities: Trueprint 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 pairedprint("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()hold-out ROC-AUC TorchMLP 0.828 logistic 0.813TorchMLP folds: [0.823 0.823 0.824 0.83 0.815]5-fold ROC-AUC TorchMLP 0.823 ± 0.005 logistic 0.813 ± 0.011per-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 identicalTorchMLPClassifier()[0 1] 22 17reloaded predicts identically: TrueThe 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.