File size: 6,748 Bytes
32621ad |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 |
{
"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": [
"<tf.Tensor: shape=(), dtype=float32, numpy=0.6341356>"
]
},
"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": [
"<div><iframe src=\"http://127.0.0.1:7863/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": []
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'numpy.ndarray'>\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
}
|