{ "cells": [ { "cell_type": "markdown", "id": "d6f9fb6e", "metadata": {}, "source": [ "# Using DJINN with scikit-learn\n", "\n", "`DJINN_Regressor` and `DJINN_Classifier` are scikit-learn estimators. They take\n", "DataFrames, fit into a `Pipeline`, and work with `cross_val_score`,\n", "`GridSearchCV`, `clone` and pickling." ] }, { "cell_type": "code", "execution_count": 1, "id": "537e85fe", "metadata": { "execution": { "iopub.execute_input": "2026-10-10T21:28:52.496094Z", "iopub.status.busy": "2026-10-10T21:28:52.495958Z", "iopub.status.idle": "2026-10-10T21:28:54.308127Z", "shell.execute_reply": "2026-10-10T21:28:54.307544Z" } }, "outputs": [], "source": [ "import os\n", "\n", "import joblib\n", "import numpy as np\n", "import pandas as pd\n", "from sklearn.base import clone\n", "from sklearn.compose import ColumnTransformer\n", "from sklearn.datasets import fetch_california_housing\n", "from sklearn.ensemble import HistGradientBoostingRegressor, RandomForestRegressor\n", "from sklearn.model_selection import GridSearchCV, KFold, cross_val_score\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.pipeline import Pipeline, make_pipeline\n", "from sklearn.preprocessing import OneHotEncoder, QuantileTransformer\n", "\n", "from djinn import DJINN_Regressor" ] }, { "cell_type": "markdown", "id": "4b0b6e34", "metadata": {}, "source": [ "## DataFrames\n", "\n", "The California housing data as a DataFrame, cut down to 2,000 rows." ] }, { "cell_type": "code", "execution_count": 2, "id": "e9c9e145", "metadata": { "execution": { "iopub.execute_input": "2026-10-10T21:28:54.310332Z", "iopub.status.busy": "2026-10-10T21:28:54.310105Z", "iopub.status.idle": "2026-10-10T21:28:54.332747Z", "shell.execute_reply": "2026-10-10T21:28:54.332230Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
MedIncHouseAgeAveRoomsAveBedrmsPopulationAveOccupLatitudeLongitude
119474.632734.05.5528170.957746880.03.09859233.93-117.44
46581.992342.02.9171031.0322863480.03.03664934.05-118.32
47901.878345.04.4453331.064000928.02.47466734.02-118.33
64096.153637.06.8389061.094225989.03.00607934.12-118.02
130952.090127.04.0600001.131111852.01.89333338.56-121.37
\n", "
" ], "text/plain": [ " MedInc HouseAge AveRooms AveBedrms Population AveOccup Latitude \\\n", "11947 4.6327 34.0 5.552817 0.957746 880.0 3.098592 33.93 \n", "4658 1.9923 42.0 2.917103 1.032286 3480.0 3.036649 34.05 \n", "4790 1.8783 45.0 4.445333 1.064000 928.0 2.474667 34.02 \n", "6409 6.1536 37.0 6.838906 1.094225 989.0 3.006079 34.12 \n", "13095 2.0901 27.0 4.060000 1.131111 852.0 1.893333 38.56 \n", "\n", " Longitude \n", "11947 -117.44 \n", "4658 -118.32 \n", "4790 -118.33 \n", "6409 -118.02 \n", "13095 -121.37 " ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df = fetch_california_housing(as_frame=True).frame.sample(2000, random_state=0)\n", "X = df.drop(columns=\"MedHouseVal\")\n", "y = df[\"MedHouseVal\"]\n", "\n", "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\n", "X_train.head()" ] }, { "cell_type": "markdown", "id": "80509140", "metadata": {}, "source": [ "Setting the learning rate and epochs skips the hyperparameter search, which\n", "matters here because cross-validation and grid search fit the model many\n", "times." ] }, { "cell_type": "code", "execution_count": 3, "id": "45e57257", "metadata": { "execution": { "iopub.execute_input": "2026-10-10T21:28:54.334048Z", "iopub.status.busy": "2026-10-10T21:28:54.333906Z", "iopub.status.idle": "2026-10-10T21:29:19.443614Z", "shell.execute_reply": "2026-10-10T21:29:19.442842Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['MedInc' 'HouseAge' 'AveRooms' 'AveBedrms' 'Population' 'AveOccup'\n", " 'Latitude' 'Longitude']\n", "R2: 0.723\n" ] } ], "source": [ "model = DJINN_Regressor(\n", " n_trees=3,\n", " max_tree_depth=6,\n", " learning_rate=0.005,\n", " epochs=200,\n", " random_state=0,\n", ")\n", "model.fit(X_train, y_train)\n", "print(model.feature_names_in_)\n", "print(f\"R2: {model.score(X_test, y_test):.3f}\")" ] }, { "cell_type": "markdown", "id": "ddcda4e7", "metadata": {}, "source": [ "## Parameters, `clone` and `set_params`\n", "\n", "All the settings live in the constructor, so `get_params()`, `set_params()` and\n", "`clone()` work as usual. `clone()` copies the settings but not the trained\n", "networks." ] }, { "cell_type": "code", "execution_count": 4, "id": "8ded2fa7", "metadata": { "execution": { "iopub.execute_input": "2026-10-10T21:29:19.445513Z", "iopub.status.busy": "2026-10-10T21:29:19.445165Z", "iopub.status.idle": "2026-10-10T21:29:19.448507Z", "shell.execute_reply": "2026-10-10T21:29:19.447881Z" } }, "outputs": [ { "data": { "text/plain": [ "{'batch_size': None,\n", " 'device': 'cpu',\n", " 'dropout_keep_prob': 1.0,\n", " 'epochs': 200,\n", " 'learning_rate': 0.005,\n", " 'max_tree_depth': 6,\n", " 'n_trees': 3,\n", " 'random_state': 0,\n", " 'verbose': 0,\n", " 'weight_decay': 1e-08}" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model.get_params()" ] }, { "cell_type": "code", "execution_count": 5, "id": "9566f8ee", "metadata": { "execution": { "iopub.execute_input": "2026-10-10T21:29:19.450622Z", "iopub.status.busy": "2026-10-10T21:29:19.450031Z", "iopub.status.idle": "2026-10-10T21:29:19.456187Z", "shell.execute_reply": "2026-10-10T21:29:19.455455Z" } }, "outputs": [ { "data": { "text/html": [ "
DJINN_Regressor(epochs=200, learning_rate=0.005, max_tree_depth=6, n_trees=5,\n",
       "                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.
" ], "text/plain": [ "DJINN_Regressor(epochs=200, learning_rate=0.005, max_tree_depth=6, n_trees=5,\n", " random_state=0)" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bigger = clone(model).set_params(n_trees=5)\n", "bigger" ] }, { "cell_type": "markdown", "id": "abcbc0ec", "metadata": {}, "source": [ "## Cross-validation\n", "\n", "`cross_val_score` clones the model for each fold. Here DJINN is compared with\n", "a random forest and gradient boosting on the same three folds." ] }, { "cell_type": "code", "execution_count": 6, "id": "902da972", "metadata": { "execution": { "iopub.execute_input": "2026-10-10T21:29:19.457468Z", "iopub.status.busy": "2026-10-10T21:29:19.457340Z", "iopub.status.idle": "2026-10-10T21:30:24.331396Z", "shell.execute_reply": "2026-10-10T21:30:24.330889Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "DJINN R2 per fold: [ 0.716 0.679 -16.027]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Random forest R2 per fold: [0.719 0.723 0.775]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gradient boosting R2 per fold: [0.777 0.772 0.826]\n", "CPU times: user 10min 44s, sys: 59.3 s, total: 11min 44s\n", "Wall time: 1min 4s\n" ] } ], "source": [ "%%time\n", "cv = KFold(n_splits=3, shuffle=True, random_state=0)\n", "candidates = {\n", " \"DJINN\": model,\n", " \"Random forest\": RandomForestRegressor(random_state=0),\n", " \"Gradient boosting\": HistGradientBoostingRegressor(random_state=0),\n", "}\n", "for name, estimator in candidates.items():\n", " scores = cross_val_score(estimator, X, y, cv=cv)\n", " print(f\"{name:<18} R2 per fold: {np.round(scores, 3)}\")" ] }, { "cell_type": "markdown", "id": "f2947ebd", "metadata": {}, "source": [ "DJINN does well on two folds and very badly on the third. The reason is a few\n", "extreme values. `AveOccup`, the average number of people per household, is\n", "around 3 for most rows but over 1,000 for one of them:" ] }, { "cell_type": "code", "execution_count": 7, "id": "383dcb1c", "metadata": { "execution": { "iopub.execute_input": "2026-10-10T21:30:24.332873Z", "iopub.status.busy": "2026-10-10T21:30:24.332662Z", "iopub.status.idle": "2026-10-10T21:30:24.337076Z", "shell.execute_reply": "2026-10-10T21:30:24.336644Z" } }, "outputs": [ { "data": { "text/plain": [ "count 2000.000000\n", "mean 3.543134\n", "std 27.749121\n", "min 1.161290\n", "25% 2.426789\n", "50% 2.807675\n", "75% 3.268466\n", "max 1243.333333\n", "Name: AveOccup, dtype: float64" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X[\"AveOccup\"].describe()" ] }, { "cell_type": "markdown", "id": "9c85479a", "metadata": {}, "source": [ "DJINN scales each input to [0, 1] using the training data's minimum and\n", "maximum. When that row lands in the test fold, its `AveOccup` is far outside\n", "anything the networks saw, and like any ReLU network they extrapolate in a\n", "straight line, giving a nonsense prediction. Tree models don't have this\n", "problem because their predictions can't go past the training targets.\n", "\n", "## Pipelines\n", "\n", "DJINN doesn't need standardized inputs, but it does need inputs without\n", "extreme outliers. A `QuantileTransformer` in front of it maps each feature to\n", "its rank in the training data, which takes care of both. Because it's in a\n", "pipeline, it's refit on the training part of each fold." ] }, { "cell_type": "code", "execution_count": 8, "id": "0e39dcf6", "metadata": { "execution": { "iopub.execute_input": "2026-10-10T21:30:24.338224Z", "iopub.status.busy": "2026-10-10T21:30:24.338096Z", "iopub.status.idle": "2026-10-10T21:31:19.846360Z", "shell.execute_reply": "2026-10-10T21:31:19.845638Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "DJINN with quantiles R2 per fold: [0.747 0.737 0.797]\n", "Mean: 0.760\n", "CPU times: user 9min 45s, sys: 52.1 s, total: 10min 37s\n", "Wall time: 55.5 s\n" ] } ], "source": [ "%%time\n", "pipe = make_pipeline(QuantileTransformer(n_quantiles=500, random_state=0), clone(model))\n", "scores = cross_val_score(pipe, X, y, cv=cv)\n", "print(f\"DJINN with quantiles R2 per fold: {np.round(scores, 3)}\")\n", "print(f\"Mean: {scores.mean():.3f}\")" ] }, { "cell_type": "markdown", "id": "f6a760a1", "metadata": {}, "source": [ "With the quantile transform, DJINN beats the random forest on every fold here,\n", "though gradient boosting is still ahead on this dataset." ] }, { "cell_type": "markdown", "id": "ce7bf6ce", "metadata": {}, "source": [ "Text columns need encoding too. To show this, the latitude is turned into a\n", "`region` column with two values, and a `ColumnTransformer` one-hot encodes it\n", "and transforms the numeric columns." ] }, { "cell_type": "code", "execution_count": 9, "id": "0d9a0ac6", "metadata": { "execution": { "iopub.execute_input": "2026-10-10T21:31:19.847965Z", "iopub.status.busy": "2026-10-10T21:31:19.847827Z", "iopub.status.idle": "2026-10-10T21:31:36.721709Z", "shell.execute_reply": "2026-10-10T21:31:36.720981Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "R2: 0.696\n" ] } ], "source": [ "X_region = X.drop(columns=\"Latitude\")\n", "X_region[\"region\"] = np.where(X[\"Latitude\"] > 36, \"north\", \"south\")\n", "numeric = [c for c in X_region.columns if c != \"region\"]\n", "\n", "prep = ColumnTransformer(\n", " [\n", " (\"region\", OneHotEncoder(), [\"region\"]),\n", " (\"numeric\", QuantileTransformer(n_quantiles=500, random_state=0), numeric),\n", " ]\n", ")\n", "region_pipe = Pipeline([(\"prep\", prep), (\"djinn\", clone(model))])\n", "\n", "Xr_train, Xr_test = X_region.loc[X_train.index], X_region.loc[X_test.index]\n", "region_pipe.fit(Xr_train, y_train)\n", "print(f\"R2: {region_pipe.score(Xr_test, y_test):.3f}\")" ] }, { "cell_type": "markdown", "id": "4949b5d9", "metadata": {}, "source": [ "## Grid search\n", "\n", "Parameters inside a pipeline are named `__`." ] }, { "cell_type": "code", "execution_count": 10, "id": "0f2e18e3", "metadata": { "execution": { "iopub.execute_input": "2026-10-10T21:31:36.723304Z", "iopub.status.busy": "2026-10-10T21:31:36.723166Z", "iopub.status.idle": "2026-10-10T21:33:40.404712Z", "shell.execute_reply": "2026-10-10T21:33:40.403939Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'djinn__max_tree_depth': 6, 'djinn__n_trees': 3}\n", "Test R2 of the best model: 0.696\n", "CPU times: user 22min 47s, sys: 1min 56s, total: 24min 43s\n", "Wall time: 2min 3s\n" ] } ], "source": [ "%%time\n", "grid = GridSearchCV(\n", " region_pipe,\n", " {\"djinn__max_tree_depth\": [4, 6], \"djinn__n_trees\": [1, 3]},\n", " cv=cv,\n", ")\n", "grid.fit(Xr_train, y_train)\n", "print(grid.best_params_)\n", "print(f\"Test R2 of the best model: {grid.score(Xr_test, y_test):.3f}\")" ] }, { "cell_type": "code", "execution_count": 11, "id": "2755f9cb", "metadata": { "execution": { "iopub.execute_input": "2026-10-10T21:33:40.406131Z", "iopub.status.busy": "2026-10-10T21:33:40.405991Z", "iopub.status.idle": "2026-10-10T21:33:40.411446Z", "shell.execute_reply": "2026-10-10T21:33:40.410887Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
param_djinn__max_tree_depthparam_djinn__n_treesmean_test_score
0410.679074
1430.700141
2610.655212
3630.704428
\n", "
" ], "text/plain": [ " param_djinn__max_tree_depth param_djinn__n_trees mean_test_score\n", "0 4 1 0.679074\n", "1 4 3 0.700141\n", "2 6 1 0.655212\n", "3 6 3 0.704428" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pd.DataFrame(grid.cv_results_)[\n", " [\"param_djinn__max_tree_depth\", \"param_djinn__n_trees\", \"mean_test_score\"]\n", "]" ] }, { "cell_type": "markdown", "id": "73a8b033", "metadata": {}, "source": [ "## Saving\n", "\n", "A fitted model, or a pipeline containing one, can be pickled with `pickle` or\n", "`joblib`. That's the easiest way to save a pipeline, but like any pickle it\n", "should be loaded with the same versions of the libraries.\n", "\n", "`save()` and `djinn.load()` store just the DJINN model as PyTorch checkpoints\n", "and a JSON file, which is better for keeping a model long term or for\n", "continuing training later." ] }, { "cell_type": "code", "execution_count": 12, "id": "5619b914", "metadata": { "execution": { "iopub.execute_input": "2026-10-10T21:33:40.412938Z", "iopub.status.busy": "2026-10-10T21:33:40.412808Z", "iopub.status.idle": "2026-10-10T21:33:40.456960Z", "shell.execute_reply": "2026-10-10T21:33:40.456336Z" } }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "joblib.dump(grid.best_estimator_, \"djinn_pipeline.joblib\")\n", "loaded = joblib.load(\"djinn_pipeline.joblib\")\n", "np.allclose(loaded.predict(Xr_test), grid.predict(Xr_test))" ] }, { "cell_type": "code", "execution_count": 13, "id": "d0e7869f", "metadata": { "execution": { "iopub.execute_input": "2026-10-10T21:33:40.458558Z", "iopub.status.busy": "2026-10-10T21:33:40.458422Z", "iopub.status.idle": "2026-10-10T21:33:40.460731Z", "shell.execute_reply": "2026-10-10T21:33:40.460185Z" } }, "outputs": [], "source": [ "os.remove(\"djinn_pipeline.joblib\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.2" } }, "nbformat": 4, "nbformat_minor": 5 }