{ "cells": [ { "cell_type": "raw", "id": "2b5a53fd", "metadata": {}, "source": [ "Run in Google Colab" ] }, { "cell_type": "markdown", "id": "38be5bd8", "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": "c102b0c3", "metadata": { "execution": { "iopub.execute_input": "2021-11-10T02:33:22.778080Z", "iopub.status.busy": "2021-11-10T02:33:22.777347Z", "iopub.status.idle": "2021-11-10T02:33:25.130205Z", "shell.execute_reply": "2021-11-10T02:33:25.130774Z" } }, "outputs": [], "source": [ "try:\n", " import scikeras\n", "except ImportError:\n", " !python -m pip install scikeras" ] }, { "cell_type": "markdown", "id": "d69c8a7e", "metadata": {}, "source": [ "Silence TensorFlow logging to keep output succinct." ] }, { "cell_type": "code", "execution_count": 2, "id": "8c2f29f3", "metadata": { "execution": { "iopub.execute_input": "2021-11-10T02:33:25.136982Z", "iopub.status.busy": "2021-11-10T02:33:25.136430Z", "iopub.status.idle": "2021-11-10T02:33:25.139632Z", "shell.execute_reply": "2021-11-10T02:33:25.140195Z" } }, "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": "31c0b076", "metadata": { "execution": { "iopub.execute_input": "2021-11-10T02:33:25.148907Z", "iopub.status.busy": "2021-11-10T02:33:25.148240Z", "iopub.status.idle": "2021-11-10T02:33:25.636972Z", "shell.execute_reply": "2021-11-10T02:33:25.637483Z" } }, "outputs": [], "source": [ "import numpy as np\n", "from scikeras.wrappers import KerasClassifier, KerasRegressor\n", "from tensorflow import keras" ] }, { "cell_type": "markdown", "id": "ef72185c", "metadata": {}, "source": [ "## 2. Dataset\n", "\n", "We will be using the MNIST dataset available within Keras." ] }, { "cell_type": "code", "execution_count": 4, "id": "2b17ee94", "metadata": { "execution": { "iopub.execute_input": "2021-11-10T02:33:25.643615Z", "iopub.status.busy": "2021-11-10T02:33:25.643051Z", "iopub.status.idle": "2021-11-10T02:33:26.129928Z", "shell.execute_reply": "2021-11-10T02:33:26.130922Z" } }, "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": "1d5cb4fa", "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": "a28f46ab", "metadata": { "execution": { "iopub.execute_input": "2021-11-10T02:33:26.139515Z", "iopub.status.busy": "2021-11-10T02:33:26.138958Z", "iopub.status.idle": "2021-11-10T02:33:26.142728Z", "shell.execute_reply": "2021-11-10T02:33:26.142231Z" } }, "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": "633cc773", "metadata": {}, "source": [ "## 4. Keras benchmarks" ] }, { "cell_type": "code", "execution_count": 6, "id": "e96e79cf", "metadata": { "execution": { "iopub.execute_input": "2021-11-10T02:33:26.147547Z", "iopub.status.busy": "2021-11-10T02:33:26.146891Z", "iopub.status.idle": "2021-11-10T02:33:26.150796Z", "shell.execute_reply": "2021-11-10T02:33:26.150316Z" } }, "outputs": [], "source": [ "fit_kwargs = {\"batch_size\": 128, \"validation_split\": 0.1, \"verbose\": 0, \"epochs\": 5}" ] }, { "cell_type": "code", "execution_count": 7, "id": "e11503a4", "metadata": { "execution": { "iopub.execute_input": "2021-11-10T02:33:26.154476Z", "iopub.status.busy": "2021-11-10T02:33:26.153888Z", "iopub.status.idle": "2021-11-10T02:33:26.165101Z", "shell.execute_reply": "2021-11-10T02:33:26.166416Z" } }, "outputs": [], "source": [ "from sklearn.metrics import accuracy_score\n", "from scikeras._utils import tensorflow_random_state" ] }, { "cell_type": "code", "execution_count": 8, "id": "d0a80394", "metadata": { "execution": { "iopub.execute_input": "2021-11-10T02:33:26.172352Z", "iopub.status.busy": "2021-11-10T02:33:26.171596Z", "iopub.status.idle": "2021-11-10T02:33:36.955781Z", "shell.execute_reply": "2021-11-10T02:33:36.954490Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Training time: 10.39\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 0.88\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": "11d94ad9", "metadata": {}, "source": [ "## 5. SciKeras benchmark" ] }, { "cell_type": "code", "execution_count": 9, "id": "01c28dec", "metadata": { "execution": { "iopub.execute_input": "2021-11-10T02:33:36.961145Z", "iopub.status.busy": "2021-11-10T02:33:36.960476Z", "iopub.status.idle": "2021-11-10T02:33:36.963641Z", "shell.execute_reply": "2021-11-10T02:33:36.962849Z" } }, "outputs": [], "source": [ "clf = KerasClassifier(\n", " model=get_model,\n", " random_state=0,\n", " **fit_kwargs\n", ")" ] }, { "cell_type": "code", "execution_count": 10, "id": "28ee04a8", "metadata": { "execution": { "iopub.execute_input": "2021-11-10T02:33:36.968784Z", "iopub.status.busy": "2021-11-10T02:33:36.968202Z", "iopub.status.idle": "2021-11-10T02:33:47.463113Z", "shell.execute_reply": "2021-11-10T02:33:47.462310Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Training time: 10.28\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 0.88\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": "6c764ee1", "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.8.12" } }, "nbformat": 4, "nbformat_minor": 5 }