{ "cells": [ { "cell_type": "raw", "id": "d30bbda9", "metadata": {}, "source": [ "Run in Google Colab" ] }, { "cell_type": "markdown", "id": "3c31e07d", "metadata": {}, "source": [ "# SciKeras Benchmarks\n", "\n", "SciKeras wraps Keras Models, but does not alter their performance since all of the heavy lifting still happens within Keras/Tensorflow. In this notebook, we compare the performance and accuracy of a pure-Keras Model to the same model wrapped in SciKeras.\n", "\n", "## Table of contents\n", "\n", "* [1. Setup](#1.-Setup)\n", "* [2. Dataset](#2.-Dataset)\n", "* [3. Define Keras Model](#3.-Define-Keras-Model)\n", "* [4. Keras benchmarks](#4.-Keras-benchmarks)\n", "* [5. SciKeras benchmark](#5.-SciKeras-benchmark)\n", "\n", "## 1. Setup" ] }, { "cell_type": "code", "execution_count": 1, "id": "760feac7", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:47:50.500789Z", "iopub.status.busy": "2024-12-12T21:47:50.500522Z", "iopub.status.idle": "2024-12-12T21:47:54.338610Z", "shell.execute_reply": "2024-12-12T21:47:54.336977Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n", "E0000 00:00:1734040071.037723 6815 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:1734040071.045110 6815 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": "6dec191e", "metadata": {}, "source": [ "Silence TensorFlow logging to keep output succinct." ] }, { "cell_type": "code", "execution_count": 2, "id": "9def0896", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:47:54.344082Z", "iopub.status.busy": "2024-12-12T21:47:54.342472Z", "iopub.status.idle": "2024-12-12T21:47:54.349055Z", "shell.execute_reply": "2024-12-12T21:47:54.348459Z" } }, "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": "c05d750a", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:47:54.352914Z", "iopub.status.busy": "2024-12-12T21:47:54.351723Z", "iopub.status.idle": "2024-12-12T21:47:54.918649Z", "shell.execute_reply": "2024-12-12T21:47:54.917820Z" } }, "outputs": [], "source": [ "import numpy as np\n", "from scikeras.wrappers import KerasClassifier, KerasRegressor\n", "import keras" ] }, { "cell_type": "markdown", "id": "a38f87dd", "metadata": {}, "source": [ "## 2. Dataset\n", "\n", "We will be using the MNIST dataset available within Keras." ] }, { "cell_type": "code", "execution_count": 4, "id": "2a66b236", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:47:54.923370Z", "iopub.status.busy": "2024-12-12T21:47:54.921768Z", "iopub.status.idle": "2024-12-12T21:47:55.282574Z", "shell.execute_reply": "2024-12-12T21:47:55.281793Z" } }, "outputs": [], "source": [ "(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n", "# Scale images to the [0, 1] range\n", "x_train = x_train.astype(\"float32\") / 255\n", "x_test = x_test.astype(\"float32\") / 255\n", "# Make sure images have shape (28, 28, 1)\n", "x_train = np.expand_dims(x_train, -1)\n", "x_test = np.expand_dims(x_test, -1)\n", "# Reduce dataset size for faster benchmarks\n", "x_train, y_train = x_train[:2000], y_train[:2000]\n", "x_test, y_test = x_test[:500], y_test[:500]" ] }, { "cell_type": "markdown", "id": "1f950db6", "metadata": {}, "source": [ "## 3. Define Keras Model\n", "\n", "Next we will define our Keras model (adapted from [keras.io](https://keras.io/examples/vision/mnist_convnet/)):" ] }, { "cell_type": "code", "execution_count": 5, "id": "e653c197", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:47:55.288497Z", "iopub.status.busy": "2024-12-12T21:47:55.285944Z", "iopub.status.idle": "2024-12-12T21:47:55.294402Z", "shell.execute_reply": "2024-12-12T21:47:55.293572Z" } }, "outputs": [], "source": [ "num_classes = 10\n", "input_shape = (28, 28, 1)\n", "\n", "\n", "def get_model():\n", " model = keras.Sequential(\n", " [\n", " keras.Input(input_shape),\n", " keras.layers.Conv2D(32, kernel_size=(3, 3), activation=\"relu\"),\n", " keras.layers.MaxPooling2D(pool_size=(2, 2)),\n", " keras.layers.Conv2D(64, kernel_size=(3, 3), activation=\"relu\"),\n", " keras.layers.MaxPooling2D(pool_size=(2, 2)),\n", " keras.layers.Flatten(),\n", " keras.layers.Dropout(0.5),\n", " keras.layers.Dense(num_classes, activation=\"softmax\"),\n", " ]\n", " )\n", " model.compile(\n", " loss=\"sparse_categorical_crossentropy\", optimizer=\"adam\"\n", " )\n", " return model" ] }, { "cell_type": "markdown", "id": "7c99adf7", "metadata": {}, "source": [ "## 4. Keras benchmarks" ] }, { "cell_type": "code", "execution_count": 6, "id": "bbfcd164", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:47:55.297767Z", "iopub.status.busy": "2024-12-12T21:47:55.297395Z", "iopub.status.idle": "2024-12-12T21:47:55.304617Z", "shell.execute_reply": "2024-12-12T21:47:55.303181Z" } }, "outputs": [], "source": [ "fit_kwargs = {\"batch_size\": 128, \"validation_split\": 0.1, \"verbose\": 0, \"epochs\": 5}" ] }, { "cell_type": "code", "execution_count": 7, "id": "7bfd60e1", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:47:55.308754Z", "iopub.status.busy": "2024-12-12T21:47:55.307907Z", "iopub.status.idle": "2024-12-12T21:47:55.312798Z", "shell.execute_reply": "2024-12-12T21:47:55.311681Z" } }, "outputs": [], "source": [ "from sklearn.metrics import accuracy_score\n", "from scikeras.utils.random_state import tensorflow_random_state" ] }, { "cell_type": "code", "execution_count": 8, "id": "05e61ea8", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:47:55.316541Z", "iopub.status.busy": "2024-12-12T21:47:55.315751Z", "iopub.status.idle": "2024-12-12T21:48:02.918887Z", "shell.execute_reply": "2024-12-12T21:48:02.917269Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Training time: 7.13\n", "\r", "\u001b[1m 1/16\u001b[0m \u001b[32m━\u001b[0m\u001b[37m━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[1m1s\u001b[0m 83ms/step" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r", "\u001b[1m10/16\u001b[0m \u001b[32m━━━━━━━━━━━━\u001b[0m\u001b[37m━━━━━━━━\u001b[0m \u001b[1m0s\u001b[0m 6ms/step " ] }, { "name": "stdout", "output_type": "stream", "text": [ "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r", "\u001b[1m16/16\u001b[0m \u001b[32m━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[37m\u001b[0m \u001b[1m0s\u001b[0m 9ms/step" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r", "\u001b[1m16/16\u001b[0m \u001b[32m━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[37m\u001b[0m \u001b[1m0s\u001b[0m 9ms/step\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 0.89\n" ] } ], "source": [ "from time import time\n", "\n", "with tensorflow_random_state(seed=0): # we force a TF random state to be able to compare accuracy\n", " model = get_model()\n", " start = time()\n", " model.fit(x_train, y_train, **fit_kwargs)\n", " print(f\"Training time: {time()-start:.2f}\")\n", " y_pred = np.argmax(model.predict(x_test), axis=1)\n", "print(f\"Accuracy: {accuracy_score(y_test, y_pred)}\")" ] }, { "cell_type": "markdown", "id": "b7756184", "metadata": {}, "source": [ "## 5. SciKeras benchmark" ] }, { "cell_type": "code", "execution_count": 9, "id": "a9d3ddf5", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:48:02.923123Z", "iopub.status.busy": "2024-12-12T21:48:02.922173Z", "iopub.status.idle": "2024-12-12T21:48:02.929748Z", "shell.execute_reply": "2024-12-12T21:48:02.928678Z" } }, "outputs": [], "source": [ "clf = KerasClassifier(\n", " model=get_model,\n", " random_state=0,\n", " **fit_kwargs\n", ")" ] }, { "cell_type": "code", "execution_count": 10, "id": "e87174be", "metadata": { "execution": { "iopub.execute_input": "2024-12-12T21:48:02.933024Z", "iopub.status.busy": "2024-12-12T21:48:02.932716Z", "iopub.status.idle": "2024-12-12T21:48:09.135626Z", "shell.execute_reply": "2024-12-12T21:48:09.134922Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Training time: 5.82\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 0.89\n" ] } ], "source": [ "start = time()\n", "clf.fit(x_train, y_train)\n", "print(f\"Training time: {time()-start:.2f}\")\n", "y_pred = clf.predict(x_test)\n", "print(f\"Accuracy: {accuracy_score(y_test, y_pred)}\")" ] }, { "cell_type": "markdown", "id": "0a5477c7", "metadata": {}, "source": [ "As you can see, the overhead for SciKeras is <1 sec, and the accuracy is identical." ] } ], "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 }