{ "cells": [ { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/Users/loic/Library/Python/3.9/lib/python/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020\n", " warnings.warn(\n", "/Users/loic/Library/Python/3.9/lib/python/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", " from .autonotebook import tqdm as notebook_tqdm\n" ] } ], "source": [ "import gradio as gr\n", "import tensorflow as tf\n", "import numpy as np\n", "from PIL import Image" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "model_path = \"dogs-vs-cats-model_transferlearning.keras\"\n", "model = tf.keras.models.load_model(model_path)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "# Define the core prediction function\n", "def predict_cat_dog(image):\n", " # Preprocess image\n", " print(type(image))\n", " image = Image.fromarray(image.astype('uint8')) # Convert numpy array to PIL image\n", " image = image.resize((150, 150)) #resize the image to 28x28 and converts it to gray scale\n", " image = np.array(image)\n", " image = np.expand_dims(image, axis=0) # same as image[None, ...]\n", " \n", " # Predict\n", " prediction = model.predict(image)\n", " \n", " # Because the output layer was dense(0) without an activation function, we need to apply sigmoid to get the probability\n", " # we could also change the output layer to dense(1, activation='sigmoid')\n", " prediction = np.round(float(tf.sigmoid(prediction)[0]), 2)\n", " p_cat = (1 - prediction)\n", " p_dog = prediction\n", " return {'cat': p_cat, 'dog': p_dog}" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tf.sigmoid(0.55)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Running on local URL: http://127.0.0.1:7863\n", "\n", "To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\u001b[1m1/1\u001b[0m \u001b[32m━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[37m\u001b[0m \u001b[1m0s\u001b[0m 32ms/step\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Traceback (most recent call last):\n", " File \"/Users/loic/Library/Python/3.9/lib/python/site-packages/gradio/queueing.py\", line 527, in process_events\n", " response = await route_utils.call_process_api(\n", " File \"/Users/loic/Library/Python/3.9/lib/python/site-packages/gradio/route_utils.py\", line 261, in call_process_api\n", " output = await app.get_blocks().process_api(\n", " File \"/Users/loic/Library/Python/3.9/lib/python/site-packages/gradio/blocks.py\", line 1786, in process_api\n", " result = await self.call_function(\n", " File \"/Users/loic/Library/Python/3.9/lib/python/site-packages/gradio/blocks.py\", line 1338, in call_function\n", " prediction = await anyio.to_thread.run_sync(\n", " File \"/Users/loic/Library/Python/3.9/lib/python/site-packages/anyio/to_thread.py\", line 56, in run_sync\n", " return await get_async_backend().run_sync_in_worker_thread(\n", " File \"/Users/loic/Library/Python/3.9/lib/python/site-packages/anyio/_backends/_asyncio.py\", line 2144, in run_sync_in_worker_thread\n", " return await future\n", " File \"/Users/loic/Library/Python/3.9/lib/python/site-packages/anyio/_backends/_asyncio.py\", line 851, in run\n", " result = context.run(func, *args)\n", " File \"/Users/loic/Library/Python/3.9/lib/python/site-packages/gradio/utils.py\", line 759, in wrapper\n", " response = f(*args, **kwargs)\n", " File \"/var/folders/vr/l64rqhls46j_2hyn4pdl0m880000gn/T/ipykernel_56385/4113486017.py\", line 15, in predict_cat_dog\n", " prediction = np.round(float(tf.sigmoid(prediction)[0]), 2)\n", " File \"/Users/loic/Library/Python/3.9/lib/python/site-packages/tensorflow/python/framework/ops.py\", line 307, in __float__\n", " return float(self._numpy())\n", "TypeError: only length-1 arrays can be converted to Python scalars\n" ] } ], "source": [ "# Create the Gradio interface\n", "input_image = gr.Image()\n", "iface = gr.Interface(\n", " fn=predict_cat_dog,\n", " inputs=input_image, \n", " outputs=gr.Label(),\n", " examples=[\"images/cat1.jpeg\", \"images/cat2.jpeg\", \"images/cat3.jpeg\", \"images/cat4.jpeg\", \"images/dog1.jpeg\", \"images/dog2.jpeg\", \"images/dog3.jpeg\"], \n", " description=\"A simple mlp classification model for image classification using the mnist dataset.\")\n", "iface.launch()" ] } ], "metadata": { "kernelspec": { "display_name": "venv_new", "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.9.6" } }, "nbformat": 4, "nbformat_minor": 2 }