{ "cells": [ { "cell_type": "raw", "id": "29a0594d", "metadata": {}, "source": [ "Run in Google Colab" ] }, { "cell_type": "markdown", "id": "2ce8fe51", "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": "4ef8eaa1", "metadata": { "execution": { "iopub.execute_input": "2022-10-14T16:48:08.987218Z", "iopub.status.busy": "2022-10-14T16:48:08.986781Z", "iopub.status.idle": "2022-10-14T16:48:11.600590Z", "shell.execute_reply": "2022-10-14T16:48:11.599992Z" } }, "outputs": [], "source": [ "try:\n", " import scikeras\n", "except ImportError:\n", " !python -m pip install scikeras[tensorflow]" ] }, { "cell_type": "markdown", "id": "6454a5d3", "metadata": {}, "source": [ "Silence TensorFlow logging to keep output succinct." ] }, { "cell_type": "code", "execution_count": 2, "id": "617e59fa", "metadata": { "execution": { "iopub.execute_input": "2022-10-14T16:48:11.607281Z", "iopub.status.busy": "2022-10-14T16:48:11.605604Z", "iopub.status.idle": "2022-10-14T16:48:11.614991Z", "shell.execute_reply": "2022-10-14T16:48:11.612342Z" } }, "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": "73273523", "metadata": { "execution": { "iopub.execute_input": "2022-10-14T16:48:11.620679Z", "iopub.status.busy": "2022-10-14T16:48:11.619554Z", "iopub.status.idle": "2022-10-14T16:48:11.856165Z", "shell.execute_reply": "2022-10-14T16:48:11.855477Z" } }, "outputs": [], "source": [ "import numpy as np\n", "from scikeras.wrappers import KerasClassifier, KerasRegressor\n", "from tensorflow import keras" ] }, { "cell_type": "markdown", "id": "6c20dd28", "metadata": {}, "source": [ "## 2. Dataset\n", "\n", "We will be using the MNIST dataset available within Keras." ] }, { "cell_type": "code", "execution_count": 4, "id": "7a94a651", "metadata": { "execution": { "iopub.execute_input": "2022-10-14T16:48:11.860612Z", "iopub.status.busy": "2022-10-14T16:48:11.860059Z", "iopub.status.idle": "2022-10-14T16:48:12.650410Z", "shell.execute_reply": "2022-10-14T16:48:12.645324Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\r", " 8192/11490434 [..............................] - ETA: 0s" ] }, { "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\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r", " 3063808/11490434 [======>.......................] - ETA: 0s" ] }, { "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\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r", " 9060352/11490434 [======================>.......] - ETA: 0s" ] }, { "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\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\r", "11490434/11490434 [==============================] - 0s 0us/step\n" ] } ], "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": "e4b34e59", "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": "29b2a18b", "metadata": { "execution": { "iopub.execute_input": "2022-10-14T16:48:12.654784Z", "iopub.status.busy": "2022-10-14T16:48:12.654139Z", "iopub.status.idle": "2022-10-14T16:48:12.659575Z", "shell.execute_reply": "2022-10-14T16:48:12.659063Z" } }, "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": "5dd304da", "metadata": {}, "source": [ "## 4. Keras benchmarks" ] }, { "cell_type": "code", "execution_count": 6, "id": "daeac799", "metadata": { "execution": { "iopub.execute_input": "2022-10-14T16:48:12.662788Z", "iopub.status.busy": "2022-10-14T16:48:12.662374Z", "iopub.status.idle": "2022-10-14T16:48:12.665700Z", "shell.execute_reply": "2022-10-14T16:48:12.665209Z" } }, "outputs": [], "source": [ "fit_kwargs = {\"batch_size\": 128, \"validation_split\": 0.1, \"verbose\": 0, \"epochs\": 5}" ] }, { "cell_type": "code", "execution_count": 7, "id": "5968297a", "metadata": { "execution": { "iopub.execute_input": "2022-10-14T16:48:12.668647Z", "iopub.status.busy": "2022-10-14T16:48:12.668102Z", "iopub.status.idle": "2022-10-14T16:48:12.671032Z", "shell.execute_reply": "2022-10-14T16:48:12.670545Z" } }, "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": "0540cd5b", "metadata": { "execution": { "iopub.execute_input": "2022-10-14T16:48:12.674047Z", "iopub.status.busy": "2022-10-14T16:48:12.673377Z", "iopub.status.idle": "2022-10-14T16:48:19.003936Z", "shell.execute_reply": "2022-10-14T16:48:19.003369Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Training time: 6.02\n", "\r", " 1/16 [>.............................] - ETA: 1s" ] }, { "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\b\b\b\b\b\b\b\b\b\r", "11/16 [===================>..........] - ETA: 0s" ] }, { "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\b\b\b\b\b\b\b\b\b\r", "16/16 [==============================] - 0s 5ms/step\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 0.884\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": "7854f2bf", "metadata": {}, "source": [ "## 5. SciKeras benchmark" ] }, { "cell_type": "code", "execution_count": 9, "id": "1ea53f56", "metadata": { "execution": { "iopub.execute_input": "2022-10-14T16:48:19.008620Z", "iopub.status.busy": "2022-10-14T16:48:19.007474Z", "iopub.status.idle": "2022-10-14T16:48:19.012066Z", "shell.execute_reply": "2022-10-14T16:48:19.011544Z" } }, "outputs": [], "source": [ "clf = KerasClassifier(\n", " model=get_model,\n", " random_state=0,\n", " **fit_kwargs\n", ")" ] }, { "cell_type": "code", "execution_count": 10, "id": "016049ae", "metadata": { "execution": { "iopub.execute_input": "2022-10-14T16:48:19.016435Z", "iopub.status.busy": "2022-10-14T16:48:19.015336Z", "iopub.status.idle": "2022-10-14T16:48:26.015345Z", "shell.execute_reply": "2022-10-14T16:48:26.014562Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Training time: 6.80\n", "Accuracy: 0.884\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": "bcaad8b6", "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.14" } }, "nbformat": 4, "nbformat_minor": 5 }