{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":7327,"databundleVersionId":861871,"sourceType":"competition"}],"dockerImageVersionId":30823,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"#   DOG BREED IDENTIFICATION - TFLite-READY NOTEBOOK\n#   (Kaggle Environment Compatible)","metadata":{}},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Model, Sequential\nfrom tensorflow.keras.layers import (\n    Input, InputLayer, Dense, GlobalAveragePooling2D, Dropout, Lambda\n)\nfrom tensorflow.keras.preprocessing.image import load_img\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\n\nimport warnings\nwarnings.filterwarnings('ignore')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-30T07:38:39.425178Z","iopub.execute_input":"2024-12-30T07:38:39.425525Z","iopub.status.idle":"2024-12-30T07:38:49.091774Z","shell.execute_reply.started":"2024-12-30T07:38:39.425490Z","shell.execute_reply":"2024-12-30T07:38:49.091076Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#   1. LOAD & PREPARE DATA","metadata":{}},{"cell_type":"code","source":"# Set your dataset path (Kaggle directory)\nDATASET_PATH = \"/kaggle/input/dog-breed-identification\"\n\ntrain_dir = os.path.join(DATASET_PATH, \"train\")\nlabels_csv = os.path.join(DATASET_PATH, \"labels.csv\")\n\ndf = pd.read_csv(labels_csv)\nprint(\"Number of training images:\", len(df))\nprint(\"Sample of labels.csv:\")\ndisplay(df.head())\n\n# All unique dog breeds\ndog_breeds = sorted(df['breed'].unique())\nn_classes = len(dog_breeds)\nprint(f\"Total distinct breeds: {n_classes}\")\n\n# Mapping breed to integer index\nclass_to_num = dict(zip(dog_breeds, np.arange(n_classes)))\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-30T07:38:53.627909Z","iopub.execute_input":"2024-12-30T07:38:53.628197Z","iopub.status.idle":"2024-12-30T07:38:53.679451Z","shell.execute_reply.started":"2024-12-30T07:38:53.628174Z","shell.execute_reply":"2024-12-30T07:38:53.678648Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Extract the list of dog breeds from the labels DataFrame\ndog_breeds = sorted(df['breed'].unique())\n\n# Save as a Python list\nprint(\"Copy and paste the following list into your Streamlit app:\")\nprint(dog_breeds)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-30T07:38:59.313873Z","iopub.execute_input":"2024-12-30T07:38:59.314311Z","iopub.status.idle":"2024-12-30T07:38:59.320594Z","shell.execute_reply.started":"2024-12-30T07:38:59.314270Z","shell.execute_reply":"2024-12-30T07:38:59.319812Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#   2. SPLIT DATA INTO TRAIN & TEST","metadata":{}},{"cell_type":"code","source":"X_train_df, X_val_df, y_train_df, y_val_df = train_test_split(\n    df.drop('breed', axis=1),\n    df['breed'],\n    test_size=0.2,\n    random_state=42,\n    stratify=df['breed']  # Keep breed distribution balanced\n)\n\nX_train_df['breed'] = y_train_df\nX_val_df['breed'] = y_val_df\n\nprint(f\"Train split size: {len(X_train_df)}, Val split size: {len(X_val_df)}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-30T07:39:08.253606Z","iopub.execute_input":"2024-12-30T07:39:08.253889Z","iopub.status.idle":"2024-12-30T07:39:08.273230Z","shell.execute_reply.started":"2024-12-30T07:39:08.253867Z","shell.execute_reply":"2024-12-30T07:39:08.272406Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#   3. UTILITIES - IMAGE LOADING & ARRAY CONVERSION","metadata":{}},{"cell_type":"code","source":"def images_to_array(data_df, folder_dir, image_size=(299, 299, 3)):\n    \"\"\"\n    Given a dataframe [id, breed], load images from folder_dir, \n    resize to image_size, and return X, y as Numpy arrays.\n    \"\"\"\n    image_names = data_df['id'].values\n    image_labels = data_df['breed'].values\n    data_size = len(image_names)\n    \n    # Initialize empty arrays\n    X = np.zeros((data_size, image_size[0], image_size[1], image_size[2]), dtype=np.uint8)\n    y = np.zeros((data_size,), dtype=np.uint8)\n    \n    for i, (img_name, breed_name) in enumerate(zip(image_names, image_labels)):\n        # Load image\n        img_path = os.path.join(folder_dir, img_name + '.jpg')\n        img = load_img(img_path, target_size=image_size[:2])  # Pillow image\n        X[i] = img\n        y[i] = class_to_num[breed_name]\n    \n    # Shuffle\n    idxs = np.random.permutation(data_size)\n    X = X[idxs]\n    y = y[idxs]\n    \n    return X, y\n\n# We will use an image size compatible with our chosen pretrained model\nIMG_SIZE = (299, 299, 3)\n\n# Load training and validation images\nX_train, y_train_int = images_to_array(X_train_df, train_dir, image_size=IMG_SIZE)\nX_val, y_val_int = images_to_array(X_val_df, train_dir, image_size=IMG_SIZE)\n\n# Convert labels to one-hot\ny_train = to_categorical(y_train_int, num_classes=n_classes)\ny_val = to_categorical(y_val_int, num_classes=n_classes)\n\nprint(\"Train data shape:\", X_train.shape, \"Train labels shape:\", y_train.shape)\nprint(\"Val data shape:\", X_val.shape, \"Val labels shape:\", y_val.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-30T07:39:11.658120Z","iopub.execute_input":"2024-12-30T07:39:11.658423Z","iopub.status.idle":"2024-12-30T07:40:32.810171Z","shell.execute_reply.started":"2024-12-30T07:39:11.658401Z","shell.execute_reply":"2024-12-30T07:40:32.809426Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 4. FEATURE EXTRACTION WITH PRETRAINED MODEL","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications.xception import Xception, preprocess_input as xception_preproc\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3, preprocess_input as incv3_preproc\n\ndef extract_features(model_class, preproc_func, input_size, data):\n    \"\"\"\n    Create a pipeline:\n      1) Lambda layer to apply preproc_func\n      2) Pretrained model (w/o top)\n      3) GlobalAveragePooling2D\n    Then run data through pipeline to get feature maps.\n    \"\"\"\n    base_input = keras.layers.Input(shape=input_size)\n    x = Lambda(preproc_func)(base_input)\n    \n    # Instantiate the pretrained base model\n    base_model = model_class(weights='imagenet', include_top=False, input_shape=input_size)(x)\n    \n    out = GlobalAveragePooling2D()(base_model)\n    \n    feature_extractor = Model(base_input, out)\n    feats = feature_extractor.predict(data, batch_size=32, verbose=1)\n    return feats\n\n# 1) Extract features using InceptionV3\ntrain_features_incv3 = extract_features(InceptionV3, incv3_preproc, IMG_SIZE, X_train)\nval_features_incv3   = extract_features(InceptionV3, incv3_preproc, IMG_SIZE, X_val)\n\n# 2) Extract features using Xception\ntrain_features_xcep = extract_features(Xception, xception_preproc, IMG_SIZE, X_train)\nval_features_xcep   = extract_features(Xception, xception_preproc, IMG_SIZE, X_val)\n\n# Concatenate features from both models\ntrain_features = np.concatenate([train_features_incv3, train_features_xcep], axis=-1)\nval_features   = np.concatenate([val_features_incv3,   val_features_xcep], axis=-1)\n\nprint(\"Combined train features shape:\", train_features.shape)\nprint(\"Combined val features shape:\", val_features.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-30T07:40:39.821007Z","iopub.execute_input":"2024-12-30T07:40:39.821312Z","iopub.status.idle":"2024-12-30T07:44:21.320932Z","shell.execute_reply.started":"2024-12-30T07:40:39.821288Z","shell.execute_reply":"2024-12-30T07:44:21.320195Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#   5. BUILD AND TRAIN DENSE CLASSIFIER ON FEATURES","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\n\nmodel = Sequential()\nmodel.add(InputLayer(train_features.shape[1:]))\nmodel.add(Dropout(0.6))\nmodel.add(Dense(120, activation='softmax', kernel_regularizer=keras.regularizers.l2(0.01)))\n\nmodel.compile(\n    optimizer='adam',\n    loss='categorical_crossentropy',\n    metrics=['accuracy']\n)\n\n# Increase epochs as needed, e.g. 50\nEPOCHS = 100\nBATCH_SIZE = 32\n\n# EarlyStopping: stops if val_loss doesn't improve for 'patience' epochs\n# ModelCheckpoint: saves the best model weights based on val_loss\ncallbacks_list = [\n    EarlyStopping(monitor='val_loss', patience=30, restore_best_weights=True),\n    ModelCheckpoint(\"best_model.keras\", monitor='val_loss', save_best_only=True, verbose=1)\n]\n\nhistory = model.fit(\n    train_features, y_train,\n    validation_data=(val_features, y_val),\n    epochs=EPOCHS,\n    batch_size=BATCH_SIZE,\n    callbacks=callbacks_list,\n    verbose=1\n)\n\n# Evaluate on the best weights\nval_loss, val_acc = model.evaluate(val_features, y_val, verbose=0)\nprint(f\"Final Validation Loss: {val_loss:.4f}, Validation Accuracy: {val_acc:.4f}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-30T07:44:31.960772Z","iopub.execute_input":"2024-12-30T07:44:31.961093Z","iopub.status.idle":"2024-12-30T07:44:53.126740Z","shell.execute_reply.started":"2024-12-30T07:44:31.961063Z","shell.execute_reply":"2024-12-30T07:44:53.125833Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#   6. EVALUATE MODEL","metadata":{}},{"cell_type":"code","source":"val_loss, val_acc = model.evaluate(val_features, y_val, verbose=0)\nprint(f\"Validation Loss: {val_loss:.4f}, Validation Accuracy: {val_acc:.4f}\")\n\n# Classification Report (optional)\ny_val_pred = model.predict(val_features)\nreport = classification_report(\n    np.argmax(y_val, axis=1),\n    np.argmax(y_val_pred, axis=1),\n    target_names=dog_breeds\n)\nprint(report)\n\n# Plot training curves\nplt.figure(figsize=(14, 5))\nplt.subplot(1,2,1)\nplt.plot(history.history['loss'], label='train_loss')\nplt.plot(history.history['val_loss'], label='val_loss')\nplt.title(\"Loss Curve\")\nplt.legend()\n\nplt.subplot(1,2,2)\nplt.plot(history.history['accuracy'], label='train_acc')\nplt.plot(history.history['val_accuracy'], label='val_acc')\nplt.title(\"Accuracy Curve\")\nplt.legend()\n\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-30T07:45:00.370981Z","iopub.execute_input":"2024-12-30T07:45:00.371328Z","iopub.status.idle":"2024-12-30T07:45:01.638251Z","shell.execute_reply.started":"2024-12-30T07:45:00.371299Z","shell.execute_reply":"2024-12-30T07:45:01.637009Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#   SAVE MODEL IN H5 FORMAT (OPTIONAL)","metadata":{}},{"cell_type":"code","source":"model.save(\"dog_breed_classifier.h5\")\nprint(\"Keras model (.h5) saved locally!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-30T07:45:14.629266Z","iopub.execute_input":"2024-12-30T07:45:14.629564Z","iopub.status.idle":"2024-12-30T07:45:14.651096Z","shell.execute_reply.started":"2024-12-30T07:45:14.629541Z","shell.execute_reply":"2024-12-30T07:45:14.650275Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#   7. TESTING THE MODEL WITH A SINGLE IMAGE","metadata":{}},{"cell_type":"code","source":"def predict_single_image(img_path, model, dog_breeds):\n    \"\"\"\n    Loads a single image, extracts features (using the same\n    steps as in training), and outputs the predicted breed.\n    \"\"\"\n    # 1. Load & resize image\n    img = load_img(img_path, target_size=IMG_SIZE[:2])\n    img_array = np.array(img)\n    \n    # 2. Expand dims to make it (1, height, width, 3)\n    img_array = np.expand_dims(img_array, axis=0)\n\n    # 3. Extract features from each pretrained model *the same way* you did above\n    feats_incv3 = extract_features(InceptionV3, incv3_preproc, IMG_SIZE, img_array)\n    feats_xcep  = extract_features(Xception, xception_preproc, IMG_SIZE, img_array)\n\n    # 4. Concatenate features\n    final_feats = np.concatenate([feats_incv3, feats_xcep], axis=-1)\n\n    # 5. Predict breed\n    preds = model.predict(final_feats)\n    pred_idx = np.argmax(preds, axis=1)[0]\n    pred_breed = dog_breeds[pred_idx]\n    print(f\"Predicted breed: {pred_breed}\")\n\n# Example usage on an arbitrary image inside your Kaggle environment:\ntest_image_path = \"/kaggle/input/dog-breed-identification/train/000bec180eb18c7604dcecc8fe0dba07.jpg\" \npredict_single_image(test_image_path, model, dog_breeds)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-30T07:47:28.877127Z","iopub.execute_input":"2024-12-30T07:47:28.877520Z","iopub.status.idle":"2024-12-30T07:47:42.709413Z","shell.execute_reply.started":"2024-12-30T07:47:28.877489Z","shell.execute_reply":"2024-12-30T07:47:42.708690Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 8. Testing the h5 format saved model","metadata":{}},{"cell_type":"code","source":"import numpy as np\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing.image import load_img\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3, preprocess_input as incv3_preproc\nfrom tensorflow.keras.applications.xception import Xception, preprocess_input as xception_preproc\nfrom tensorflow.keras.layers import GlobalAveragePooling2D\nimport tensorflow as tf\n\n# Path to the saved .h5 model\nMODEL_PATH = \"/kaggle/working/dog_breed_classifier.h5\"\n\n# Load the saved .h5 model\nmodel = load_model(MODEL_PATH)\n\n# Dog breeds (ensure this matches the list from your training pipeline)\ndog_breeds = sorted(df['breed'].unique())\n\n# Pretrained model input size\nIMG_SIZE = (299, 299, 3)\n\n# Function to extract features using pretrained models\ndef extract_features(model_class, preproc_func, input_size, data):\n    \"\"\"\n    Extract features using a pretrained model.\n    \"\"\"\n    # Create a Lambda layer for preprocessing\n    base_input = tf.keras.layers.Input(shape=input_size)\n    x = tf.keras.layers.Lambda(preproc_func)(base_input)\n    \n    # Instantiate the pretrained base model\n    base_model = model_class(weights='imagenet', include_top=False, input_shape=input_size)(x)\n    \n    # Apply Global Average Pooling\n    out = GlobalAveragePooling2D()(base_model)\n    \n    # Create feature extractor\n    feature_extractor = tf.keras.models.Model(base_input, out)\n    \n    # Extract features\n    feats = feature_extractor.predict(data, batch_size=1, verbose=1)\n    return feats\n\n# Function to preprocess and predict a single image\ndef predict_single_image(img_path, model, dog_breeds):\n    \"\"\"\n    Predict the breed of a single image using the .h5 model.\n    \"\"\"\n    # 1. Load & resize image\n    img = load_img(img_path, target_size=IMG_SIZE[:2])\n    img_array = np.array(img)\n    \n    # 2. Expand dims to make it (1, height, width, 3)\n    img_array = np.expand_dims(img_array, axis=0)\n    \n    # 3. Extract features from pretrained models\n    feats_incv3 = extract_features(InceptionV3, incv3_preproc, IMG_SIZE, img_array)\n    feats_xcep  = extract_features(Xception, xception_preproc, IMG_SIZE, img_array)\n\n    # 4. Concatenate features\n    final_feats = np.concatenate([feats_incv3, feats_xcep], axis=-1)\n    \n    # 5. Predict breed\n    preds = model.predict(final_feats)\n    pred_idx = np.argmax(preds, axis=1)[0]\n    pred_breed = dog_breeds[pred_idx]\n    print(f\"Predicted breed: {pred_breed}\")\n\n# Test image path\ntest_image_path = \"/kaggle/input/dog-breed-identification/train/000bec180eb18c7604dcecc8fe0dba07.jpg\"\n\n# Predict breed for the test image\npredict_single_image(test_image_path, model, dog_breeds)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-30T07:48:48.410729Z","iopub.execute_input":"2024-12-30T07:48:48.411029Z","iopub.status.idle":"2024-12-30T07:48:58.950317Z","shell.execute_reply.started":"2024-12-30T07:48:48.411005Z","shell.execute_reply":"2024-12-30T07:48:58.949569Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# TFlite Version ","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\n\n# Step 1: Load the Keras .h5 model\nkeras_model = tf.keras.models.load_model(\"dog_breed_classifier.h5\")\n\n# Step 2: Convert to TFLite model\nconverter = tf.lite.TFLiteConverter.from_keras_model(keras_model)\ntflite_model = converter.convert()\n\n# Step 3: Save the TFLite model to a file\nwith open(\"dog_breed_classifier.tflite\", \"wb\") as f:\n    f.write(tflite_model)\n\nprint(\"TFLite model saved as 'dog_breed_classifier.tflite'\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T12:57:01.813431Z","iopub.execute_input":"2024-12-29T12:57:01.813780Z","iopub.status.idle":"2024-12-29T12:57:02.188393Z","shell.execute_reply.started":"2024-12-29T12:57:01.813755Z","shell.execute_reply":"2024-12-29T12:57:02.187376Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.applications.xception import Xception, preprocess_input as xception_preproc\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3, preprocess_input as incv3_preproc\nfrom tensorflow.keras.preprocessing.image import load_img\n\n# Load and preprocess the test image\ndef preprocess_image(img_path, target_size):\n    img = load_img(img_path, target_size=target_size[:2])  # Resize image\n    img_array = np.array(img, dtype=np.float32)  # Convert to NumPy array\n    img_array = np.expand_dims(img_array, axis=0)  # Add batch dimension\n    return img_array\n\n# Extract features using the same method as during training\ndef extract_combined_features(img_array, target_size):\n    # Load pretrained models\n    inception_model = InceptionV3(weights='imagenet', include_top=False, input_shape=target_size)\n    xception_model = Xception(weights='imagenet', include_top=False, input_shape=target_size)\n    \n    # Preprocess the image\n    img_incv3 = incv3_preproc(img_array)\n    img_xcep = xception_preproc(img_array)\n    \n    # Extract features\n    features_incv3 = inception_model.predict(img_incv3)\n    features_xcep = xception_model.predict(img_xcep)\n    \n    # Global Average Pooling\n    pooled_incv3 = tf.keras.layers.GlobalAveragePooling2D()(features_incv3).numpy()\n    pooled_xcep = tf.keras.layers.GlobalAveragePooling2D()(features_xcep).numpy()\n    \n    # Concatenate features\n    combined_features = np.concatenate([pooled_incv3, pooled_xcep], axis=-1)\n    return combined_features\n\n# Load the TFLite model\nTFLITE_MODEL_PATH = \"dog_breed_classifier.tflite\"\ninterpreter = tf.lite.Interpreter(model_path=TFLITE_MODEL_PATH)\ninterpreter.allocate_tensors()\n\n# Get input and output details\ninput_details = interpreter.get_input_details()\noutput_details = interpreter.get_output_details()\n\nprint(\"Input details:\", input_details)\nprint(\"Output details:\", output_details)\n\n# Test image path\ntest_image_path = \"/kaggle/input/dog-breed-identification/train/000bec180eb18c7604dcecc8fe0dba07.jpg\"\nIMG_SIZE = (299, 299, 3)\n\n# Preprocess and extract features\ninput_image = preprocess_image(test_image_path, IMG_SIZE)\nextracted_features = extract_combined_features(input_image, IMG_SIZE)\n\n# Check the shape of the extracted features\nprint(\"Extracted features shape:\", extracted_features.shape)  # Should be (1, 4096)\n\n# Run inference\ninterpreter.set_tensor(input_details[0]['index'], extracted_features)\ninterpreter.invoke()\n\n# Get the output predictions\noutput_data = interpreter.get_tensor(output_details[0]['index'])\npredicted_class_idx = np.argmax(output_data, axis=1)[0]\n\n# Map the index back to the dog breed\npredicted_breed = dog_breeds[predicted_class_idx]\nprint(f\"Predicted breed: {predicted_breed}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T13:00:31.510779Z","iopub.execute_input":"2024-12-29T13:00:31.511084Z","iopub.status.idle":"2024-12-29T13:00:40.891342Z","shell.execute_reply.started":"2024-12-29T13:00:31.511061Z","shell.execute_reply":"2024-12-29T13:00:40.890480Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.applications import Xception, InceptionV3\nfrom tensorflow.keras.layers import Input, GlobalAveragePooling2D, Dense, Dropout, concatenate\nfrom tensorflow.keras.models import Model\n\n# Input layer for raw image\ninput_layer = Input(shape=(299, 299, 3))\n\n# Feature extraction with InceptionV3\nincv3_base = InceptionV3(weights='imagenet', include_top=False, input_shape=(299, 299, 3))\nx_incv3 = incv3_base(input_layer)\nx_incv3 = GlobalAveragePooling2D()(x_incv3)\n\n# Feature extraction with Xception\nxcep_base = Xception(weights='imagenet', include_top=False, input_shape=(299, 299, 3))\nx_xcep = xcep_base(input_layer)\nx_xcep = GlobalAveragePooling2D()(x_xcep)\n\n# Combine features from both models\ncombined_features = concatenate([x_incv3, x_xcep])\n\n# Add dropout and final dense layer\nx = Dropout(0.6)(combined_features)\noutput_layer = Dense(120, activation='softmax', kernel_regularizer=tf.keras.regularizers.l2(0.01))(x)\n\n# Define the new model\ncombined_model = Model(inputs=input_layer, outputs=output_layer)\n\n# Compile the model\ncombined_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Print model summary (optional)\ncombined_model.summary()\n\n# Save as TensorFlow Lite model\ntflite_converter = tf.lite.TFLiteConverter.from_keras_model(combined_model)\ntflite_model = tflite_converter.convert()\n\n# Save the TFLite model to a file\nwith open(\"dog_breed_classifier_simplified.tflite\", \"wb\") as f:\n    f.write(tflite_model)\n\nprint(\"Simplified TFLite model saved as 'dog_breed_classifier_simplified.tflite'\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T13:04:51.175931Z","iopub.execute_input":"2024-12-29T13:04:51.176247Z","iopub.status.idle":"2024-12-29T13:05:25.356715Z","shell.execute_reply.started":"2024-12-29T13:04:51.176224Z","shell.execute_reply":"2024-12-29T13:05:25.355711Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import load_img, img_to_array\n\n# Load the simplified TFLite model\nTFLITE_MODEL_PATH = \"dog_breed_classifier_simplified.tflite\"\ninterpreter = tf.lite.Interpreter(model_path=TFLITE_MODEL_PATH)\ninterpreter.allocate_tensors()\n\n# Get input and output details\ninput_details = interpreter.get_input_details()\noutput_details = interpreter.get_output_details()\n\nprint(\"Input details:\", input_details)\nprint(\"Output details:\", output_details)\n\n# Function to preprocess the image\ndef preprocess_image(img_path, target_size):\n    \"\"\"\n    Loads and preprocesses an image to match the input format of the TFLite model.\n    - Resizes the image to `target_size`.\n    - Normalizes pixel values to [0, 1].\n    \"\"\"\n    img = load_img(img_path, target_size=target_size[:2])  # Resize image\n    img_array = img_to_array(img) / 255.0  # Convert to array and normalize\n    img_array = np.expand_dims(img_array, axis=0)  # Add batch dimension\n    return img_array\n\n# Path to a test image\ntest_image_path = \"/kaggle/input/dog-breed-identification/train/000bec180eb18c7604dcecc8fe0dba07.jpg\"\nIMG_SIZE = (299, 299, 3)\n\n# Preprocess the test image\ninput_image = preprocess_image(test_image_path, IMG_SIZE)\nprint(\"Preprocessed image shape:\", input_image.shape)\n\n# Run inference\ninterpreter.set_tensor(input_details[0]['index'], input_image)\ninterpreter.invoke()\n\n# Get the predictions\noutput_data = interpreter.get_tensor(output_details[0]['index'])\npredicted_class_idx = np.argmax(output_data, axis=1)[0]\n\n# Map the index back to the dog breed\npredicted_breed = dog_breeds[predicted_class_idx]\nprint(f\"Predicted breed: {predicted_breed}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T13:07:43.518993Z","iopub.execute_input":"2024-12-29T13:07:43.519343Z","iopub.status.idle":"2024-12-29T13:07:44.161283Z","shell.execute_reply.started":"2024-12-29T13:07:43.519319Z","shell.execute_reply":"2024-12-29T13:07:44.160361Z"}},"outputs":[],"execution_count":null}]}