Using DJINN with scikit-learn

DJINN_Regressor and DJINN_Classifier are scikit-learn estimators. They take DataFrames, fit into a Pipeline, and work with cross_val_score, GridSearchCV, clone and pickling.

[1]:
import os

import joblib
import numpy as np
import pandas as pd
from sklearn.base import clone
from sklearn.compose import ColumnTransformer
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import HistGradientBoostingRegressor, RandomForestRegressor
from sklearn.model_selection import GridSearchCV, KFold, cross_val_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, QuantileTransformer

from djinn import DJINN_Regressor

DataFrames

The California housing data as a DataFrame, cut down to 2,000 rows.

[2]:
df = fetch_california_housing(as_frame=True).frame.sample(2000, random_state=0)
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
X_train.head()
[2]:
MedInc HouseAge AveRooms AveBedrms Population AveOccup Latitude Longitude
11947 4.6327 34.0 5.552817 0.957746 880.0 3.098592 33.93 -117.44
4658 1.9923 42.0 2.917103 1.032286 3480.0 3.036649 34.05 -118.32
4790 1.8783 45.0 4.445333 1.064000 928.0 2.474667 34.02 -118.33
6409 6.1536 37.0 6.838906 1.094225 989.0 3.006079 34.12 -118.02
13095 2.0901 27.0 4.060000 1.131111 852.0 1.893333 38.56 -121.37

Setting the learning rate and epochs skips the hyperparameter search, which matters here because cross-validation and grid search fit the model many times.

[3]:
model = DJINN_Regressor(
    n_trees=3,
    max_tree_depth=6,
    learning_rate=0.005,
    epochs=200,
    random_state=0,
)
model.fit(X_train, y_train)
print(model.feature_names_in_)
print(f"R2: {model.score(X_test, y_test):.3f}")
['MedInc' 'HouseAge' 'AveRooms' 'AveBedrms' 'Population' 'AveOccup'
 'Latitude' 'Longitude']
R2: 0.723

Parameters, clone and set_params

All the settings live in the constructor, so get_params(), set_params() and clone() work as usual. clone() copies the settings but not the trained networks.

[4]:
model.get_params()
[4]:
{'batch_size': None,
 'device': 'cpu',
 'dropout_keep_prob': 1.0,
 'epochs': 200,
 'learning_rate': 0.005,
 'max_tree_depth': 6,
 'n_trees': 3,
 'random_state': 0,
 'verbose': 0,
 'weight_decay': 1e-08}
[5]:
bigger = clone(model).set_params(n_trees=5)
bigger
[5]:
DJINN_Regressor(epochs=200, learning_rate=0.005, max_tree_depth=6, n_trees=5,
                random_state=0)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

Cross-validation

cross_val_score clones the model for each fold. Here DJINN is compared with a random forest and gradient boosting on the same three folds.

[6]:
%%time
cv = KFold(n_splits=3, shuffle=True, random_state=0)
candidates = {
    "DJINN": model,
    "Random forest": RandomForestRegressor(random_state=0),
    "Gradient boosting": HistGradientBoostingRegressor(random_state=0),
}
for name, estimator in candidates.items():
    scores = cross_val_score(estimator, X, y, cv=cv)
    print(f"{name:<18} R2 per fold: {np.round(scores, 3)}")
DJINN              R2 per fold: [  0.716   0.679 -16.027]
Random forest      R2 per fold: [0.719 0.723 0.775]
Gradient boosting  R2 per fold: [0.777 0.772 0.826]
CPU times: user 10min 44s, sys: 59.3 s, total: 11min 44s
Wall time: 1min 4s

DJINN does well on two folds and very badly on the third. The reason is a few extreme values. AveOccup, the average number of people per household, is around 3 for most rows but over 1,000 for one of them:

[7]:
X["AveOccup"].describe()
[7]:
count    2000.000000
mean        3.543134
std        27.749121
min         1.161290
25%         2.426789
50%         2.807675
75%         3.268466
max      1243.333333
Name: AveOccup, dtype: float64

DJINN scales each input to [0, 1] using the training data’s minimum and maximum. When that row lands in the test fold, its AveOccup is far outside anything the networks saw, and like any ReLU network they extrapolate in a straight line, giving a nonsense prediction. Tree models don’t have this problem because their predictions can’t go past the training targets.

Pipelines

DJINN doesn’t need standardized inputs, but it does need inputs without extreme outliers. A QuantileTransformer in front of it maps each feature to its rank in the training data, which takes care of both. Because it’s in a pipeline, it’s refit on the training part of each fold.

[8]:
%%time
pipe = make_pipeline(QuantileTransformer(n_quantiles=500, random_state=0), clone(model))
scores = cross_val_score(pipe, X, y, cv=cv)
print(f"DJINN with quantiles R2 per fold: {np.round(scores, 3)}")
print(f"Mean: {scores.mean():.3f}")
DJINN with quantiles R2 per fold: [0.747 0.737 0.797]
Mean: 0.760
CPU times: user 9min 45s, sys: 52.1 s, total: 10min 37s
Wall time: 55.5 s

With the quantile transform, DJINN beats the random forest on every fold here, though gradient boosting is still ahead on this dataset.

Text columns need encoding too. To show this, the latitude is turned into a region column with two values, and a ColumnTransformer one-hot encodes it and transforms the numeric columns.

[9]:
X_region = X.drop(columns="Latitude")
X_region["region"] = np.where(X["Latitude"] > 36, "north", "south")
numeric = [c for c in X_region.columns if c != "region"]

prep = ColumnTransformer(
    [
        ("region", OneHotEncoder(), ["region"]),
        ("numeric", QuantileTransformer(n_quantiles=500, random_state=0), numeric),
    ]
)
region_pipe = Pipeline([("prep", prep), ("djinn", clone(model))])

Xr_train, Xr_test = X_region.loc[X_train.index], X_region.loc[X_test.index]
region_pipe.fit(Xr_train, y_train)
print(f"R2: {region_pipe.score(Xr_test, y_test):.3f}")
R2: 0.696

Saving

A fitted model, or a pipeline containing one, can be pickled with pickle or joblib. That’s the easiest way to save a pipeline, but like any pickle it should be loaded with the same versions of the libraries.

save() and djinn.load() store just the DJINN model as PyTorch checkpoints and a JSON file, which is better for keeping a model long term or for continuing training later.

[12]:
joblib.dump(grid.best_estimator_, "djinn_pipeline.joblib")
loaded = joblib.load("djinn_pipeline.joblib")
np.allclose(loaded.predict(Xr_test), grid.predict(Xr_test))
[12]:
True
[13]:
os.remove("djinn_pipeline.joblib")