{ "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(\"

Image Classification using TensorFlow

\")\n", " gr.Markdown(\"

This model classifies image using different models.

\")\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": [ "" ], "text/html": [ "
" ] }, "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": [] } ] }