{ "cells": [ { "cell_type": "raw", "id": "3b0a7907", "metadata": {}, "source": [ "Run in Google Colab" ] }, { "cell_type": "markdown", "id": "8e9c9e6f", "metadata": {}, "source": [ "# Meta Estimators in SciKeras\n", "\n", "In this notebook, we implement sklearn ensemble and tree meta-estimators backed by a Keras MLP model.\n", "\n", "## Table of contents\n", "\n", "* [1. Setup](#1.-Setup)\n", "* [2. Defining the Keras Model](#2.-Defining-the-Keras-Model)\n", " * [2.1 Building a boosting ensemble](#2.1-Building-a-boosting-ensemble)\n", "* [3. Testing with a toy dataset](#3.-Testing-with-a-toy-dataset)\n", "* [4. Bagging ensemble](#4.-Bagging-ensemble)\n", "\n", "## 1. Setup" ] }, { "cell_type": "code", "execution_count": 1, "id": "c7e66de5", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:46:16.060342Z", "iopub.status.busy": "2024-12-12T21:46:16.059661Z", "iopub.status.idle": "2024-12-12T21:46:19.022991Z", "shell.execute_reply": "2024-12-12T21:46:19.022114Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n", "E0000 00:00:1734039976.467631 4400 cuda_dnn.cc:8310] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n", "E0000 00:00:1734039976.471887 4400 cuda_blas.cc:1418] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n" ] } ], "source": [ "try:\n", " import scikeras\n", "except ImportError:\n", " !python -m pip install scikeras[tensorflow]" ] }, { "cell_type": "markdown", "id": "58b6a306", "metadata": {}, "source": [ "Silence TensorFlow logging to keep output succinct." ] }, { "cell_type": "code", "execution_count": 2, "id": "f4520c26", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:46:19.027321Z", "iopub.status.busy": "2024-12-12T21:46:19.026352Z", "iopub.status.idle": "2024-12-12T21:46:19.033988Z", "shell.execute_reply": "2024-12-12T21:46:19.032531Z" } }, "outputs": [], "source": [ "import warnings\n", "from tensorflow import get_logger\n", "get_logger().setLevel('ERROR')\n", "warnings.filterwarnings(\"ignore\", message=\"Setting the random state for TF\")" ] }, { "cell_type": "code", "execution_count": 3, "id": "61cbe361", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:46:19.038038Z", "iopub.status.busy": "2024-12-12T21:46:19.037053Z", "iopub.status.idle": "2024-12-12T21:46:19.587673Z", "shell.execute_reply": "2024-12-12T21:46:19.586714Z" } }, "outputs": [], "source": [ "import numpy as np\n", "from scikeras.wrappers import KerasClassifier, KerasRegressor\n", "import keras" ] }, { "cell_type": "markdown", "id": "a46f7dc4", "metadata": {}, "source": [ "## 2. Defining the Keras Model\n", "\n", "We borrow our MLPClassifier implementation from the [MLPClassifier notebook](https://colab.research.google.com/github/adriangb/scikeras/blob/master/notebooks/MLPClassifier_and_MLPRegressor.ipynb)." ] }, { "cell_type": "code", "execution_count": 4, "id": "b3930f8d", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:46:19.593051Z", "iopub.status.busy": "2024-12-12T21:46:19.591469Z", "iopub.status.idle": "2024-12-12T21:46:19.601131Z", "shell.execute_reply": "2024-12-12T21:46:19.599043Z" } }, "outputs": [], "source": [ "from typing import Dict, Iterable, Any\n", "\n", "\n", "def get_clf_model(hidden_layer_sizes: Iterable[int], meta: Dict[str, Any], compile_kwargs: Dict[str, Any]):\n", " model = keras.Sequential()\n", " inp = keras.layers.Input(shape=(meta[\"n_features_in_\"],))\n", " model.add(inp)\n", " for hidden_layer_size in hidden_layer_sizes:\n", " layer = keras.layers.Dense(hidden_layer_size, activation=\"relu\")\n", " model.add(layer)\n", " if meta[\"target_type_\"] == \"binary\":\n", " n_output_units = 1\n", " output_activation = \"sigmoid\"\n", " loss = \"binary_crossentropy\"\n", " elif meta[\"target_type_\"] == \"multiclass\":\n", " n_output_units = meta[\"n_classes_\"]\n", " output_activation = \"softmax\"\n", " loss = \"sparse_categorical_crossentropy\"\n", " else:\n", " raise NotImplementedError(f\"Unsupported task type: {meta['target_type_']}\")\n", " out = keras.layers.Dense(n_output_units, activation=output_activation)\n", " model.add(out)\n", " model.compile(loss=loss, optimizer=compile_kwargs[\"optimizer\"])\n", " return model" ] }, { "cell_type": "markdown", "id": "beaecbf3", "metadata": {}, "source": [ "Next we wrap this Keras model with SciKeras" ] }, { "cell_type": "code", "execution_count": 5, "id": "325b9780", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:46:19.605613Z", "iopub.status.busy": "2024-12-12T21:46:19.604979Z", "iopub.status.idle": "2024-12-12T21:46:19.611864Z", "shell.execute_reply": "2024-12-12T21:46:19.610698Z" } }, "outputs": [], "source": [ "clf = KerasClassifier(\n", " model=get_clf_model,\n", " hidden_layer_sizes=(100, ),\n", " optimizer=\"adam\",\n", " optimizer__learning_rate=0.001,\n", " verbose=0,\n", " random_state=0,\n", ")" ] }, { "cell_type": "markdown", "id": "3270d84b", "metadata": {}, "source": [ "### 2.1 Building a boosting ensemble\n", "\n", "Because SciKeras estimators are fully compliant with the Scikit-Learn API, we can make use of Scikit-Learn's built in utilities. In particular example, we will use `AdaBoostClassifier` from `sklearn.ensemble.AdaBoostClassifier`, but the process is the same for most Scikit-Learn meta-estimators.\n" ] }, { "cell_type": "code", "execution_count": 6, "id": "10602e7d", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:46:19.615496Z", "iopub.status.busy": "2024-12-12T21:46:19.614925Z", "iopub.status.idle": "2024-12-12T21:46:20.095188Z", "shell.execute_reply": "2024-12-12T21:46:20.093973Z" } }, "outputs": [], "source": [ "from sklearn.ensemble import AdaBoostClassifier\n", "\n", "\n", "adaboost = AdaBoostClassifier(estimator=clf, random_state=0)" ] }, { "cell_type": "markdown", "id": "75e7add1", "metadata": {}, "source": [ "## 3. Testing with a toy dataset\n", "\n", "Before continouing, we will run a small test to make sure we get somewhat reasonable results.\n" ] }, { "cell_type": "code", "execution_count": 7, "id": "075ea46a", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:46:20.099470Z", "iopub.status.busy": "2024-12-12T21:46:20.098993Z", "iopub.status.idle": "2024-12-12T21:47:30.704953Z", "shell.execute_reply": "2024-12-12T21:47:30.704302Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/runner/work/scikeras/scikeras/.venv/lib/python3.12/site-packages/sklearn/ensemble/_weight_boosting.py:527: FutureWarning: The SAMME.R algorithm (the default) is deprecated and will be removed in 1.6. Use the SAMME algorithm to circumvent this warning.\n", " warnings.warn(\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Single score: 0.53\n", "AdaBoost score: 0.87\n" ] } ], "source": [ "from sklearn.datasets import make_moons\n", "\n", "\n", "X, y = make_moons()\n", "\n", "single_score = clf.fit(X, y).score(X, y)\n", "\n", "adaboost_score = adaboost.fit(X, y).score(X, y)\n", "\n", "print(f\"Single score: {single_score:.2f}\")\n", "print(f\"AdaBoost score: {adaboost_score:.2f}\")" ] }, { "cell_type": "markdown", "id": "310c4fdc", "metadata": {}, "source": [ "We see that the score for the AdaBoost classifier is slightly higher than that of an individual MLPRegressor instance. We can explore the individual classifiers, and see that each one is composed of a Keras Model with it's own individual weights.\n" ] }, { "cell_type": "code", "execution_count": 8, "id": "7839cfa6", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:47:30.709598Z", "iopub.status.busy": "2024-12-12T21:47:30.708875Z", "iopub.status.idle": "2024-12-12T21:47:30.720570Z", "shell.execute_reply": "2024-12-12T21:47:30.719890Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-0.00939173 0.04660247 0.08650086 -0.20484188 0.11110867]\n", "[ 0.23005284 0.2013653 0.21442483 0.03201675 -0.09931928]\n" ] } ], "source": [ "print(adaboost.estimators_[0].model_.get_weights()[0][0, :5]) # first sub-estimator\n", "print(adaboost.estimators_[1].model_.get_weights()[0][0, :5]) # second sub-estimator" ] }, { "cell_type": "markdown", "id": "9e4f30a1", "metadata": {}, "source": [ "## 4. Bagging ensemble\n", "\n", "For comparison, we run the same test with an ensemble built using `sklearn.ensemble.BaggingClassifier`." ] }, { "cell_type": "code", "execution_count": 9, "id": "d106ea01", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:47:30.724484Z", "iopub.status.busy": "2024-12-12T21:47:30.723736Z", "iopub.status.idle": "2024-12-12T21:47:44.447797Z", "shell.execute_reply": "2024-12-12T21:47:44.447082Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n", "E0000 00:00:1734040053.229018 6471 cuda_dnn.cc:8310] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n", "E0000 00:00:1734040053.250741 6471 cuda_blas.cc:1418] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n", "E0000 00:00:1734040053.533584 6470 cuda_dnn.cc:8310] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n", "E0000 00:00:1734040053.542010 6470 cuda_blas.cc:1418] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n", "E0000 00:00:1734040053.896569 6472 cuda_dnn.cc:8310] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n", "E0000 00:00:1734040053.905468 6472 cuda_blas.cc:1418] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n", "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n", "E0000 00:00:1734040053.942108 6473 cuda_dnn.cc:8310] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n", "E0000 00:00:1734040053.949797 6473 cuda_blas.cc:1418] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Bagging score: 0.73\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "WARNING:tensorflow:5 out of the last 9 calls to .one_step_on_data_distributed at 0x7f31102fbec0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n", "WARNING:tensorflow:6 out of the last 12 calls to .one_step_on_data_distributed at 0x7f31102fbec0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n", "WARNING:tensorflow:5 out of the last 9 calls to .one_step_on_data_distributed at 0x7fd612e36c00> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n", "WARNING:tensorflow:6 out of the last 12 calls to .one_step_on_data_distributed at 0x7fd612e36c00> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for more details.\n" ] } ], "source": [ "from sklearn.ensemble import BaggingClassifier\n", "\n", "\n", "bagging = BaggingClassifier(estimator=clf, random_state=0, n_jobs=-1)\n", "\n", "bagging_score = bagging.fit(X, y).score(X, y)\n", "\n", "print(f\"Bagging score: {bagging_score:.2f}\")" ] } ], "metadata": { "jupytext": { "formats": "ipynb,md" }, "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.7" } }, "nbformat": 4, "nbformat_minor": 5 }