File size: 13,439 Bytes
31607dc |
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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 |
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"gpuType": "T4"
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
},
"accelerator": "GPU"
},
"cells": [
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "OdOgOEqcDzhY",
"outputId": "a1787cb0-c94a-4145-ef35-bb222f63a373"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n",
"/content/drive/My Drive/My Projects/Image_Classifier_TensorFlow\n"
]
}
],
"source": [
"# This mounts your Google Drive to the Colab VM.\n",
"from google.colab import drive\n",
"drive.mount('/content/drive')\n",
"\n",
"%cd /content/drive/My\\ Drive/My\\ Projects/Image_Classifier_TensorFlow"
]
},
{
"cell_type": "code",
"source": [
"pwd"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"id": "EuUA1qNaEdGB",
"outputId": "b9b3ca06-157a-4686-92ab-72c080dddcfb"
},
"execution_count": 10,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"'/content/drive/My Drive/My Projects/Image_Classifier_TensorFlow'"
],
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
}
},
"metadata": {},
"execution_count": 10
}
]
},
{
"cell_type": "markdown",
"source": [
"# Gradio App"
],
"metadata": {
"id": "6XXQqgGmErXJ"
}
},
{
"cell_type": "code",
"source": [
"# installations\n",
"!pip install gradio"
],
"metadata": {
"id": "wSuhvzbEE8Ql"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Training"
],
"metadata": {
"id": "71zplmVlFU9J"
}
},
{
"cell_type": "code",
"source": [
"print(\"Training model...\")\n",
"# Create an instance of the ImageClassifier\n",
"classifier = ImageClassifier()\n",
"\n",
"# Load the dataset\n",
"(x_train, y_train), (x_test, y_test) = classifier.load_dataset()\n",
"\n",
"# Build and train the model\n",
"classifier.build_model(x_train)\n",
"classifier.train_model(x_train, y_train, batch_size=64, epochs=1, validation_split=0.1)\n",
"\n",
"# Evaluate the model\n",
"classifier.evaluate_model(x_test, y_test)\n",
"\n",
"# Save the trained model\n",
"print(\"Saving model ...\")\n",
"classifier.save_model(\"image_classifier_model.h5\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Q9vKOsnKFRu4",
"outputId": "93268865-5288-44a3-bc09-6d30620655f8"
},
"execution_count": 13,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Training model...\n",
"704/704 [==============================] - 187s 263ms/step - loss: 1.5925 - accuracy: 0.4633 - val_loss: 1.3171 - val_accuracy: 0.5372\n",
"Test loss: 1.3429059982299805\n",
"Test accuracy: 0.5228999853134155\n",
"Saving model ...\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"import gradio as gr\n",
"import tensorflow as tf\n",
"from tensorflow import keras\n",
"from custom_model import ImageClassifier\n",
"from resnet_model import ResNetClassifier\n",
"from vgg16_model import VGG16Classifier\n",
"from inception_v3_model import InceptionV3Classifier\n",
"from mobilevet_v2 import MobileNetClassifier\n",
"\n",
"CLASS_NAMES =['Airplane', 'Automobile', 'Bird', 'Cat', 'Deer', 'Dog', 'Frog', 'Horse', 'Ship', 'Truck']\n",
"\n",
"# models\n",
"custom_model = ImageClassifier()\n",
"custom_model.load_model(\"image_classifier_model.h5\")\n",
"resnet_model = ResNetClassifier()\n",
"vgg16_model = VGG16Classifier()\n",
"inceptionV3_model = InceptionV3Classifier()\n",
"mobilenet_model = MobileNetClassifier()\n",
"\n",
"def make_prediction(image, model_type):\n",
" if \"CNN (2 layer) - Custom\" == model_type:\n",
" top_classes, top_probs = custom_model.classify_image(image, top_k=3)\n",
" return {CLASS_NAMES[cls_id]:str(prob) for cls_id, prob in zip(top_classes, top_probs)}\n",
" elif \"ResNet50\" == model_type:\n",
" predictions = resnet_model.classify_image(image)\n",
" return {class_name:str(prob) for _, class_name, prob in predictions}\n",
" elif \"VGG16\" == model_type:\n",
" predictions = vgg16_model.classify_image(image)\n",
" return {class_name:str(prob) for _, class_name, prob in predictions}\n",
" elif \"Inception v3\" == model_type:\n",
" predictions = inceptionV3_model.classify_image(image)\n",
" return {class_name:str(prob) for _, class_name, prob in predictions}\n",
" elif \"Mobile Net v2\" == model_type:\n",
" predictions = mobilenet_model.classify_image(image)\n",
" return {class_name:str(prob) for _, class_name, prob in predictions}\n",
" else:\n",
" return {\"Select a model to classify image\"}\n",
"\n",
"def train_model(epochs, batch_size, validation_split):\n",
"\n",
" print(\"Training model\")\n",
"\n",
" # Create an instance of the ImageClassifier\n",
" classifier = ImageClassifier()\n",
"\n",
" # Load the dataset\n",
" (x_train, y_train), (x_test, y_test) = classifier.load_dataset()\n",
"\n",
" # Build and train the model\n",
" classifier.build_model(x_train)\n",
" classifier.train_model(x_train, y_train, batch_size=int(batch_size), epochs=int(epochs), validation_split=float(validation_split))\n",
"\n",
" # Evaluate the model\n",
" classifier.evaluate_model(x_test, y_test)\n",
"\n",
" # Save the trained model\n",
" print(\"Saving model ...\")\n",
" classifier.save_model(\"image_classifier_model.h5\")\n",
"\n",
" custom_model = classifier\n",
"\n",
"\n",
"def update_train_param_display(model_type):\n",
" if \"CNN (2 layer) - Custom\" == model_type:\n",
" return [gr.update(visible=True), gr.update(visible=False)]\n",
" return [gr.update(visible=False), gr.update(visible=True)]\n",
"\n",
"if __name__ == \"__main__\":\n",
" # gradio gui app\n",
" with gr.Blocks() as my_app:\n",
" gr.Markdown(\"<h1><center>Image Classification using TensorFlow</center></h1>\")\n",
" gr.Markdown(\"<h3><center>This model classifies image using different models.</center></h3>\")\n",
"\n",
" with gr.Row():\n",
" with gr.Column(scale=1):\n",
" img_input = gr.Image()\n",
" model_type = gr.Dropdown(\n",
" [\"CNN (2 layer) - Custom\",\n",
" \"ResNet50\",\n",
" \"VGG16\",\n",
" \"Inception v3\",\n",
" \"Mobile Net v2\"],\n",
" label=\"Model Type\", value=\"CNN (2 layer) - Custom\",\n",
" info=\"Select the inference model before running predictions!\")\n",
"\n",
" with gr.Column() as train_col:\n",
" gr.Markdown(\"Train Parameters\")\n",
" with gr.Row():\n",
" epochs_inp = gr.Textbox(label=\"Epochs\", value=\"10\")\n",
" validation_split = gr.Textbox(label=\"Validation Split\", value=\"0.1\")\n",
"\n",
" with gr.Row():\n",
" batch_size = gr.Textbox(label=\"Batch Size\", value=\"64\")\n",
"\n",
" with gr.Row():\n",
" train_btn = gr.Button(value=\"Train\")\n",
" predict_btn_1 = gr.Button(value=\"Predict\")\n",
"\n",
" with gr.Column(visible=False) as no_train_col:\n",
" predict_btn_2 = gr.Button(value=\"Predict\")\n",
"\n",
" with gr.Column(scale=1):\n",
" output_label = gr.Label()\n",
"\n",
" # app logic\n",
" predict_btn_1.click(make_prediction, inputs=[img_input, model_type], outputs=[output_label])\n",
" predict_btn_2.click(make_prediction, inputs=[img_input, model_type], outputs=[output_label])\n",
" model_type.change(update_train_param_display, inputs=model_type, outputs=[train_col, no_train_col])\n",
" train_btn.click(train_model, inputs=[epochs_inp, batch_size, validation_split], outputs=[])\n",
"\n",
"my_app.queue(concurrency_count=5, max_size=20).launch(debug=True)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 936
},
"id": "1N6d3Y0oEozx",
"outputId": "07cc9273-30a8-4186-f0bf-e14a5aa45216"
},
"execution_count": 14,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/resnet/resnet50_weights_tf_dim_ordering_tf_kernels.h5\n",
"102967424/102967424 [==============================] - 1s 0us/step\n",
"Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels.h5\n",
"553467096/553467096 [==============================] - 9s 0us/step\n",
"Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/inception_v3/inception_v3_weights_tf_dim_ordering_tf_kernels.h5\n",
"96112376/96112376 [==============================] - 1s 0us/step\n",
"Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/mobilenet_v2/mobilenet_v2_weights_tf_dim_ordering_tf_kernels_1.0_224.h5\n",
"14536120/14536120 [==============================] - 0s 0us/step\n",
"Setting queue=True in a Colab notebook requires sharing enabled. Setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).\n",
"\n",
"Colab notebook detected. This cell will run indefinitely so that you can see errors and logs. To turn off, set debug=False in launch().\n",
"Running on public URL: https://bc9c4277de0c1cb0c9.gradio.live\n",
"\n",
"This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from Terminal to deploy to Spaces (https://huggingface.co/spaces)\n"
]
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"<IPython.core.display.HTML object>"
],
"text/html": [
"<div><iframe src=\"https://bc9c4277de0c1cb0c9.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
]
},
"metadata": {}
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"1/1 [==============================] - 0s 178ms/step\n",
"1/1 [==============================] - 1s 1s/step\n",
"Downloading data from https://storage.googleapis.com/download.tensorflow.org/data/imagenet_class_index.json\n",
"35363/35363 [==============================] - 0s 0us/step\n",
"1/1 [==============================] - 1s 755ms/step\n",
"1/1 [==============================] - 2s 2s/step\n",
"Keyboard interruption in main thread... closing server.\n",
"Killing tunnel 127.0.0.1:7860 <> https://bc9c4277de0c1cb0c9.gradio.live\n"
]
},
{
"output_type": "execute_result",
"data": {
"text/plain": []
},
"metadata": {},
"execution_count": 14
}
]
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "6p0TTCYYH2XA"
},
"execution_count": null,
"outputs": []
}
]
} |