{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","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":31154,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install keras-tuner --upgrade","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:37:26.036222Z","iopub.execute_input":"2025-11-01T13:37:26.036914Z","iopub.status.idle":"2025-11-01T13:37:29.402469Z","shell.execute_reply.started":"2025-11-01T13:37:26.036888Z","shell.execute_reply":"2025-11-01T13:37:29.401482Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import libs\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport tensorflow as tf\nfrom keras.layers import Dense, Conv2D, Flatten\nfrom tensorflow.keras import datasets, layers, models\nfrom tensorflow.math import confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nimport os\nimport cv2\nimport warnings\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom kerastuner.tuners import RandomSearch\nimport matplotlib.pyplot as plt\n\nwarnings.filterwarnings('ignore')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:37:29.404429Z","iopub.execute_input":"2025-11-01T13:37:29.405243Z","iopub.status.idle":"2025-11-01T13:37:29.411042Z","shell.execute_reply.started":"2025-11-01T13:37:29.405218Z","shell.execute_reply":"2025-11-01T13:37:29.410107Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/dog-breed-identification/labels.csv\")\ntrain_dir = \"/kaggle/input/dog-breed-identification/train\"\ntest_dir = \"/kaggle/input/dog-breed-identification/test\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:37:29.411813Z","iopub.execute_input":"2025-11-01T13:37:29.412065Z","iopub.status.idle":"2025-11-01T13:37:29.445857Z","shell.execute_reply.started":"2025-11-01T13:37:29.412044Z","shell.execute_reply":"2025-11-01T13:37:29.445092Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_features(model_name, data_preprocessor, input_size, data):\n    input_layer = Input(input_size)\n    preprocessor = Lambda(data_preprocessor)(input_layer)\n    base_model = model_name(weights='imagenet', include_top=False,\n                            input_shape=input_size)(preprocessor)\n    avg = GlobalAveragePooling2D()(base_model)\n    feature_extractor = Model(inputs = input_layer, outputs = avg)\n    feature_maps = feature_extractor.predict(data, batch_size=64, verbose=1)\n    print('Feature maps shape: ', feature_maps.shape)\n    return feature_maps","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:37:29.447731Z","iopub.execute_input":"2025-11-01T13:37:29.448039Z","iopub.status.idle":"2025-11-01T13:37:29.453929Z","shell.execute_reply.started":"2025-11-01T13:37:29.448017Z","shell.execute_reply":"2025-11-01T13:37:29.453167Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dog_breeds = sorted(list(set(train['breed'])))\nn_classes = len(dog_breeds)\nprint(n_classes)\ndog_breeds[:5]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:37:29.454709Z","iopub.execute_input":"2025-11-01T13:37:29.454928Z","iopub.status.idle":"2025-11-01T13:37:29.474931Z","shell.execute_reply.started":"2025-11-01T13:37:29.454909Z","shell.execute_reply":"2025-11-01T13:37:29.474081Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class_to_num = dict(zip(dog_breeds, range(n_classes)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:37:29.475803Z","iopub.execute_input":"2025-11-01T13:37:29.476049Z","iopub.status.idle":"2025-11-01T13:37:29.488511Z","shell.execute_reply.started":"2025-11-01T13:37:29.476033Z","shell.execute_reply":"2025-11-01T13:37:29.487748Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def images_to_array(data_dir, labels_dataframe, img_size = (224,224,3)):\n    images_names = labels_dataframe['id']\n    images_labels = labels_dataframe['breed']\n    data_size = len(images_names)\n    X = np.zeros([data_size, img_size[0], img_size[1], img_size[2]], dtype=np.uint8)\n    y = np.zeros([data_size,1], dtype=np.uint8)\n\n    for i in tqdm(range(data_size)):\n        image_name = images_names[i]\n        img_dir = os.path.join(data_dir, image_name+'.jpg')\n        img_pixels = load_img(img_dir, target_size=img_size)\n        X[i] = img_pixels\n\n        image_breed = images_labels[i]\n        y[i] = class_to_num[image_breed]\n\n    y = to_categorical(y)\n\n    ind = np.random.permutation(data_size)\n    X = X[ind]\n    y = y[ind]\n    print('Output Data Size: ', X.shape)\n    print('Output Label Size: ', y.shape)\n    return X, y","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:37:29.489340Z","iopub.execute_input":"2025-11-01T13:37:29.489695Z","iopub.status.idle":"2025-11-01T13:37:29.503010Z","shell.execute_reply.started":"2025-11-01T13:37:29.489673Z","shell.execute_reply":"2025-11-01T13:37:29.502323Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import load_img\nfrom tqdm import tqdm\nfrom keras.utils import to_categorical\n\nimg_size = (224,224, 3)\nX, y = images_to_array(train_dir, train, img_size)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:37:29.503913Z","iopub.execute_input":"2025-11-01T13:37:29.504217Z","iopub.status.idle":"2025-11-01T13:37:49.449406Z","shell.execute_reply.started":"2025-11-01T13:37:29.504201Z","shell.execute_reply":"2025-11-01T13:37:49.448506Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.models import Model\nfrom keras.layers import BatchNormalization, Dense, GlobalAveragePooling2D, Lambda, Dropout, InputLayer, Input\nfrom keras.applications.inception_v3 import InceptionV3, preprocess_input\n\ninception_preprocessor = preprocess_input\ninception_features = get_features(InceptionV3,\n                                  inception_preprocessor,\n                                  img_size, X)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:37:49.450365Z","iopub.execute_input":"2025-11-01T13:37:49.450636Z","iopub.status.idle":"2025-11-01T13:38:27.737501Z","shell.execute_reply.started":"2025-11-01T13:37:49.450611Z","shell.execute_reply":"2025-11-01T13:38:27.736657Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.applications.xception import Xception, preprocess_input\nxception_preprocessor = preprocess_input\n\nxception_features = get_features(Xception,\n                                 xception_preprocessor,\n                                 img_size, X)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:38:27.740039Z","iopub.execute_input":"2025-11-01T13:38:27.740327Z","iopub.status.idle":"2025-11-01T13:39:23.917568Z","shell.execute_reply.started":"2025-11-01T13:38:27.740310Z","shell.execute_reply":"2025-11-01T13:39:23.916879Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input\nmobilenet_v2_preprocessor = preprocess_input\nmobilenet_v2_features = get_features(MobileNetV2,\n                                   mobilenet_v2_preprocessor,\n                                   img_size, X)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:39:23.918606Z","iopub.execute_input":"2025-11-01T13:39:23.918842Z","iopub.status.idle":"2025-11-01T13:39:49.417621Z","shell.execute_reply.started":"2025-11-01T13:39:23.918825Z","shell.execute_reply":"2025-11-01T13:39:49.416730Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"del X\nfinal_features = np.concatenate([inception_features,\n                                 xception_features,\n                                 mobilenet_v2_features], axis=-1)\nprint('Final feature maps shape', final_features.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:39:49.418734Z","iopub.execute_input":"2025-11-01T13:39:49.419521Z","iopub.status.idle":"2025-11-01T13:39:49.502448Z","shell.execute_reply.started":"2025-11-01T13:39:49.419492Z","shell.execute_reply":"2025-11-01T13:39:49.501784Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nX_train, X_temp, y_train, y_temp = train_test_split(final_features, y, test_size=0.2, random_state=42)\nX_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:39:49.503158Z","iopub.execute_input":"2025-11-01T13:39:49.503486Z","iopub.status.idle":"2025-11-01T13:39:49.592277Z","shell.execute_reply.started":"2025-11-01T13:39:49.503468Z","shell.execute_reply":"2025-11-01T13:39:49.591668Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.callbacks import EarlyStopping\nEarlyStop_callback = EarlyStopping(monitor='val_loss', patience=15, restore_best_weights=True)\nmy_callback=[EarlyStop_callback]\nimport tensorflow as tf\nfrom tensorflow.keras import layers, models\nimport matplotlib.pyplot as plt\n\n\nmodel = models.Sequential([\n    InputLayer(X_train.shape[1:]),\n    layers.Flatten(),\n    layers.Dense(128, activation='relu'),\n    layers.Dropout(0.4),\n    layers.Dense(n_classes, activation='softmax')\n])\n\n\nmodel.compile(optimizer='adam',\n              loss='categorical_crossentropy',\n              metrics=['accuracy'])\n\nmodel.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:39:49.592973Z","iopub.execute_input":"2025-11-01T13:39:49.593247Z","iopub.status.idle":"2025-11-01T13:39:49.641440Z","shell.execute_reply.started":"2025-11-01T13:39:49.593224Z","shell.execute_reply":"2025-11-01T13:39:49.640697Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(X_train, y_train, epochs=20, validation_data=(X_val, y_val), callbacks=my_callback, batch_size=128)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:39:49.642226Z","iopub.execute_input":"2025-11-01T13:39:49.642457Z","iopub.status.idle":"2025-11-01T13:39:59.658497Z","shell.execute_reply.started":"2025-11-01T13:39:49.642442Z","shell.execute_reply":"2025-11-01T13:39:59.657674Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"est_loss, test_accuracy = model.evaluate(X_test, y_test)\nprint(f'Test Accuracy: {test_accuracy*100:.2f}%')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:39:59.659580Z","iopub.execute_input":"2025-11-01T13:39:59.659920Z","iopub.status.idle":"2025-11-01T13:40:00.548934Z","shell.execute_reply.started":"2025-11-01T13:39:59.659894Z","shell.execute_reply":"2025-11-01T13:40:00.548355Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(history.history['accuracy'], label='accuracy')\nplt.plot(history.history['val_accuracy'], label='val_accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend(loc='lower right')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:40:00.549688Z","iopub.execute_input":"2025-11-01T13:40:00.550093Z","iopub.status.idle":"2025-11-01T13:40:00.712006Z","shell.execute_reply.started":"2025-11-01T13:40:00.550073Z","shell.execute_reply":"2025-11-01T13:40:00.711023Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(history.history['loss'], label='loss')\nplt.plot(history.history['val_loss'], label='val_loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend(loc='upper right')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:40:00.712809Z","iopub.execute_input":"2025-11-01T13:40:00.713094Z","iopub.status.idle":"2025-11-01T13:40:00.850777Z","shell.execute_reply.started":"2025-11-01T13:40:00.713073Z","shell.execute_reply":"2025-11-01T13:40:00.850094Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"fig, ax = plt.subplots(figsize=(7,5))\n\n# Accuracy\nax.plot(history.history['accuracy'], label='Train Accuracy', color='blue')\nax.plot(history.history['val_accuracy'], label='Val Accuracy', color='orange')\nax.set_title('Training & Validation Accuracy')\nax.set_xlabel('Epochs')\nax.set_ylabel('Accuracy')\nax.legend()\nax.grid(True)\n\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-01T13:45:03.550212Z","iopub.execute_input":"2025-11-01T13:45:03.550498Z","iopub.status.idle":"2025-11-01T13:45:03.719454Z","shell.execute_reply.started":"2025-11-01T13:45:03.550472Z","shell.execute_reply":"2025-11-01T13:45:03.718751Z"}},"outputs":[],"execution_count":null}]}