{ "cells": [ { "cell_type": "raw", "id": "e272e81f", "metadata": {}, "source": [ "Run in Google Colab" ] }, { "cell_type": "markdown", "id": "e7da2af0", "metadata": {}, "source": [ "# Sparse Inputs" ] }, { "cell_type": "markdown", "id": "0160b7ff", "metadata": {}, "source": [ "SciKeras supports sparse inputs (`X`/features).\n", "You don't have to do anything special for this to work, you can just pass a sparse matrix to `fit()`.\n", "\n", "In this notebook, we'll demonstrate how this works and compare memory consumption of sparse inputs to dense inputs." ] }, { "cell_type": "markdown", "id": "47bf4762", "metadata": {}, "source": [ "## Setup" ] }, { "cell_type": "code", "execution_count": 1, "id": "eb35f370", "metadata": { "execution": { "iopub.execute_input": "2024-04-11T22:22:36.527750Z", "iopub.status.busy": "2024-04-11T22:22:36.527540Z", "iopub.status.idle": "2024-04-11T22:22:39.838036Z", "shell.execute_reply": "2024-04-11T22:22:39.837226Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Collecting memory_profiler\r\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " Downloading memory_profiler-0.61.0-py3-none-any.whl.metadata (20 kB)\r\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Requirement already satisfied: psutil in /home/runner/work/scikeras/scikeras/.venv/lib/python3.12/site-packages (from memory_profiler) (5.9.8)\r\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Downloading memory_profiler-0.61.0-py3-none-any.whl (31 kB)\r\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Installing collected packages: memory_profiler\r\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully installed memory_profiler-0.61.0\r\n" ] } ], "source": [ "!pip install memory_profiler\n", "%load_ext memory_profiler" ] }, { "cell_type": "code", "execution_count": 2, "id": "26f985f9", "metadata": { "execution": { "iopub.execute_input": "2024-04-11T22:22:39.841823Z", "iopub.status.busy": "2024-04-11T22:22:39.841458Z", "iopub.status.idle": "2024-04-11T22:22:42.238545Z", "shell.execute_reply": "2024-04-11T22:22:42.237866Z" } }, "outputs": [], "source": [ "import warnings\n", "import os\n", "os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\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": "ccc385a7", "metadata": { "execution": { "iopub.execute_input": "2024-04-11T22:22:42.241660Z", "iopub.status.busy": "2024-04-11T22:22:42.241309Z", "iopub.status.idle": "2024-04-11T22:22:42.247081Z", "shell.execute_reply": "2024-04-11T22:22:42.246334Z" } }, "outputs": [], "source": [ "try:\n", " import scikeras\n", "except ImportError:\n", " !python -m pip install scikeras" ] }, { "cell_type": "code", "execution_count": 4, "id": "7d403397", "metadata": { "execution": { "iopub.execute_input": "2024-04-11T22:22:42.249528Z", "iopub.status.busy": "2024-04-11T22:22:42.249158Z", "iopub.status.idle": "2024-04-11T22:22:42.616183Z", "shell.execute_reply": "2024-04-11T22:22:42.614192Z" } }, "outputs": [], "source": [ "import scipy\n", "import numpy as np\n", "from scikeras.wrappers import KerasRegressor\n", "from sklearn.preprocessing import OneHotEncoder\n", "from sklearn.pipeline import Pipeline\n", "import keras" ] }, { "cell_type": "markdown", "id": "79ba136c", "metadata": {}, "source": [ "## Data\n", "\n", "The dataset we'll be using is designed to demostrate a worst-case/best-case scenario for dense and sparse input features respectively.\n", "It consists of a single categorical feature with equal number of categories as rows.\n", "This means the one-hot encoded representation will require as many columns as it does rows, making it very ineffienct to store as a dense matrix but very efficient to store as a sparse matrix." ] }, { "cell_type": "code", "execution_count": 5, "id": "4c265013", "metadata": { "execution": { "iopub.execute_input": "2024-04-11T22:22:42.622495Z", "iopub.status.busy": "2024-04-11T22:22:42.619800Z", "iopub.status.idle": "2024-04-11T22:22:42.626993Z", "shell.execute_reply": "2024-04-11T22:22:42.626290Z" } }, "outputs": [], "source": [ "N_SAMPLES = 20_000 # hand tuned to be ~4GB peak\n", "\n", "X = np.arange(0, N_SAMPLES).reshape(-1, 1)\n", "y = np.random.uniform(0, 1, size=(X.shape[0],))" ] }, { "cell_type": "markdown", "id": "71b0ae08", "metadata": {}, "source": [ "## Model\n", "\n", "The model here is nothing special, just a basic multilayer perceptron with one hidden layer." ] }, { "cell_type": "code", "execution_count": 6, "id": "b607e14c", "metadata": { "execution": { "iopub.execute_input": "2024-04-11T22:22:42.630110Z", "iopub.status.busy": "2024-04-11T22:22:42.629430Z", "iopub.status.idle": "2024-04-11T22:22:42.636672Z", "shell.execute_reply": "2024-04-11T22:22:42.635365Z" } }, "outputs": [], "source": [ "def get_clf(meta) -> keras.Model:\n", " n_features_in_ = meta[\"n_features_in_\"]\n", " model = keras.models.Sequential()\n", " model.add(keras.layers.Input(shape=(n_features_in_,)))\n", " # a single hidden layer\n", " model.add(keras.layers.Dense(100, activation=\"relu\"))\n", " model.add(keras.layers.Dense(1))\n", " return model" ] }, { "cell_type": "markdown", "id": "b13bf25f", "metadata": {}, "source": [ "## Pipelines\n", "\n", "Here is where it gets interesting.\n", "We make two Scikit-Learn pipelines that use `OneHotEncoder`: one that uses `sparse_output=False` to force a dense matrix as the output and another that uses `sparse_output=True` (the default)." ] }, { "cell_type": "code", "execution_count": 7, "id": "f927152e", "metadata": { "execution": { "iopub.execute_input": "2024-04-11T22:22:42.640189Z", "iopub.status.busy": "2024-04-11T22:22:42.639798Z", "iopub.status.idle": "2024-04-11T22:22:42.643689Z", "shell.execute_reply": "2024-04-11T22:22:42.643082Z" } }, "outputs": [], "source": [ "dense_pipeline = Pipeline(\n", " [\n", " (\"encoder\", OneHotEncoder(sparse_output=False)),\n", " (\"model\", KerasRegressor(get_clf, loss=\"mse\", epochs=5, verbose=False))\n", " ]\n", ")\n", "\n", "sparse_pipeline = Pipeline(\n", " [\n", " (\"encoder\", OneHotEncoder(sparse_output=True)),\n", " (\"model\", KerasRegressor(get_clf, loss=\"mse\", epochs=5, verbose=False))\n", " ]\n", ")" ] }, { "cell_type": "markdown", "id": "2fecbb4c", "metadata": {}, "source": [ "## Benchmark\n", "\n", "Our benchmark will be to just train each one of these pipelines and measure peak memory consumption." ] }, { "cell_type": "code", "execution_count": 8, "id": "ddb9248e", "metadata": { "execution": { "iopub.execute_input": "2024-04-11T22:22:42.647317Z", "iopub.status.busy": "2024-04-11T22:22:42.646917Z", "iopub.status.idle": "2024-04-11T22:23:29.643693Z", "shell.execute_reply": "2024-04-11T22:23:29.642981Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "peak memory: 5162.20 MiB, increment: 4638.93 MiB\n" ] } ], "source": [ "%memit dense_pipeline.fit(X, y)" ] }, { "cell_type": "code", "execution_count": 9, "id": "fc08feb1", "metadata": { "execution": { "iopub.execute_input": "2024-04-11T22:23:29.647519Z", "iopub.status.busy": "2024-04-11T22:23:29.646985Z", "iopub.status.idle": "2024-04-11T22:23:51.185372Z", "shell.execute_reply": "2024-04-11T22:23:51.184528Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "peak memory: 996.02 MiB, increment: 40.57 MiB\n" ] } ], "source": [ "%memit sparse_pipeline.fit(X, y)" ] }, { "cell_type": "markdown", "id": "ebc42e6a", "metadata": {}, "source": [ "You should see at least 100x more memory consumption **increment** in the dense pipeline." ] }, { "cell_type": "markdown", "id": "6f089999", "metadata": {}, "source": [ "### Runtime\n", "\n", "Using sparse inputs can have a drastic impact on memory usage, but it often (not always) hurts overall runtime." ] }, { "cell_type": "code", "execution_count": 10, "id": "b0fc91e5", "metadata": { "execution": { "iopub.execute_input": "2024-04-11T22:23:51.191048Z", "iopub.status.busy": "2024-04-11T22:23:51.190818Z", "iopub.status.idle": "2024-04-11T22:29:50.085998Z", "shell.execute_reply": "2024-04-11T22:29:50.083298Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "44.6 s ± 5.09 s per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" ] } ], "source": [ "%timeit dense_pipeline.fit(X, y)" ] }, { "cell_type": "code", "execution_count": 11, "id": "075ad334", "metadata": { "execution": { "iopub.execute_input": "2024-04-11T22:29:50.092195Z", "iopub.status.busy": "2024-04-11T22:29:50.091877Z", "iopub.status.idle": "2024-04-11T22:31:56.619880Z", "shell.execute_reply": "2024-04-11T22:31:56.619263Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "15.6 s ± 1.01 s per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" ] } ], "source": [ "%timeit sparse_pipeline.fit(X, y)" ] }, { "cell_type": "markdown", "id": "38522c53", "metadata": {}, "source": [ "## Tensorflow Datasets\n", "\n", "Tensorflow provides a whole suite of functionality around the [Dataset].\n", "Datasets are lazily evaluated, can be sparse and minimize the transformations required to feed data into the model.\n", "They are _a lot_ more performant and efficient at scale than using numpy datastructures, even sparse ones.\n", "\n", "SciKeras does not (and cannot) support Datasets directly because Scikit-Learn itself does not support them and SciKeras' outwards API is Scikit-Learn's API.\n", "You may want to explore breaking out of SciKeras and just using TensorFlow/Keras directly to see if Datasets can have a large impact for your use case.\n", "\n", "[Dataset]: https://www.tensorflow.org/api_docs/python/tf/data/Dataset" ] }, { "cell_type": "markdown", "id": "bc0ba267", "metadata": {}, "source": [ "## Bonus: dtypes\n", "\n", "You might be able to save even more memory by changing the output dtype of `OneHotEncoder`." ] }, { "cell_type": "code", "execution_count": 12, "id": "6a9b1793", "metadata": { "execution": { "iopub.execute_input": "2024-04-11T22:31:56.623299Z", "iopub.status.busy": "2024-04-11T22:31:56.622785Z", "iopub.status.idle": "2024-04-11T22:31:56.626192Z", "shell.execute_reply": "2024-04-11T22:31:56.625623Z" } }, "outputs": [], "source": [ "sparse_pipline_uint8 = Pipeline(\n", " [\n", " (\"encoder\", OneHotEncoder(sparse_output=True, dtype=np.uint8)),\n", " (\"model\", KerasRegressor(get_clf, loss=\"mse\", epochs=5, verbose=False))\n", " ]\n", ")" ] }, { "cell_type": "code", "execution_count": 13, "id": "35b654b6", "metadata": { "execution": { "iopub.execute_input": "2024-04-11T22:31:56.628505Z", "iopub.status.busy": "2024-04-11T22:31:56.628187Z", "iopub.status.idle": "2024-04-11T22:32:14.308799Z", "shell.execute_reply": "2024-04-11T22:32:14.303528Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "peak memory: 1130.52 MiB, increment: 26.03 MiB\n" ] } ], "source": [ "%memit sparse_pipline_uint8.fit(X, y)" ] } ], "metadata": { "jupytext": { "formats": "ipynb,md" }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "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 }