{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":7327,"databundleVersionId":861871,"sourceType":"competition"},{"sourceId":8961347,"sourceType":"datasetVersion","datasetId":5393841},{"sourceId":10145405,"sourceType":"datasetVersion","datasetId":6262366}],"dockerImageVersionId":30732,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        pass\n#         print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-12-09T07:02:08.158923Z","iopub.execute_input":"2024-12-09T07:02:08.159180Z","iopub.status.idle":"2024-12-09T07:02:44.318767Z","shell.execute_reply.started":"2024-12-09T07:02:08.159157Z","shell.execute_reply":"2024-12-09T07:02:44.318016Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#  **Data Preparation**","metadata":{}},{"cell_type":"markdown","source":"### Importing Libraries and Suppressing Warnings","metadata":{}},{"cell_type":"code","source":"\nimport warnings\nwarnings.filterwarnings('ignore', category=UserWarning)\n\nimport os\nimport pandas as pd\nfrom shutil import copyfile\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout, BatchNormalization\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom tensorflow.keras.optimizers import Adam\n","metadata":{"execution":{"iopub.status.busy":"2024-12-09T07:02:44.320403Z","iopub.execute_input":"2024-12-09T07:02:44.321139Z","iopub.status.idle":"2024-12-09T07:02:56.104315Z","shell.execute_reply.started":"2024-12-09T07:02:44.321109Z","shell.execute_reply":"2024-12-09T07:02:56.103383Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Setting Dataset Paths and Loading Labels\n","metadata":{}},{"cell_type":"code","source":"\n\n# Set the path to the dataset\ntrain_dir = '/kaggle/input/dog-breed-identification/train'\nlabels_file = '/kaggle/input/dog-breed-identification/labels.csv'\n\n# Load the labels\nlabels_df = pd.read_csv(labels_file)\n","metadata":{"execution":{"iopub.status.busy":"2024-12-09T07:02:56.105592Z","iopub.execute_input":"2024-12-09T07:02:56.106475Z","iopub.status.idle":"2024-12-09T07:02:56.136729Z","shell.execute_reply.started":"2024-12-09T07:02:56.106442Z","shell.execute_reply":"2024-12-09T07:02:56.135943Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Count the number of images per breed\nbreed_counts = labels_df['breed'].value_counts()\n\n# Plotting the bar graph\nplt.figure(figsize=(20, 20))\nbreed_counts.plot(kind='barh',color='g')\nplt.title('Number of Images per Breed')\nplt.xlabel('Breed')\nplt.ylabel('Count')\nplt.xticks(rotation=45)\nplt.tight_layout()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-12-09T07:02:56.138531Z","iopub.execute_input":"2024-12-09T07:02:56.139022Z","iopub.status.idle":"2024-12-09T07:02:57.640289Z","shell.execute_reply.started":"2024-12-09T07:02:56.138999Z","shell.execute_reply":"2024-12-09T07:02:57.639287Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#### Filtering for Top 10 Breeds and Ensuring Image Count\n","metadata":{}},{"cell_type":"code","source":"\n\n# Filter for 10 breeds with 100 images each\nselected_breeds = labels_df['breed'].value_counts().nlargest(10).index\nfiltered_labels_df = labels_df[labels_df['breed'].isin(selected_breeds)]\n\n# Ensure each breed has exactly 100 images\nfiltered_labels_df = filtered_labels_df.groupby('breed').head(100)\n\nfiltered_labels_df['id'] = filtered_labels_df['id'] + '.jpg'\n","metadata":{"execution":{"iopub.status.busy":"2024-12-09T07:02:57.641497Z","iopub.execute_input":"2024-12-09T07:02:57.641846Z","iopub.status.idle":"2024-12-09T07:02:57.661654Z","shell.execute_reply.started":"2024-12-09T07:02:57.641816Z","shell.execute_reply":"2024-12-09T07:02:57.660696Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#### Selected Breeds","metadata":{}},{"cell_type":"code","source":"selected_breeds_list = filtered_labels_df['breed'].unique()\nfor breed in selected_breeds_list:\n    print(breed)\n\n","metadata":{"execution":{"iopub.status.busy":"2024-12-09T07:02:57.662939Z","iopub.execute_input":"2024-12-09T07:02:57.663383Z","iopub.status.idle":"2024-12-09T07:02:57.669184Z","shell.execute_reply.started":"2024-12-09T07:02:57.663353Z","shell.execute_reply":"2024-12-09T07:02:57.668161Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"####  Creating Directory for Filtered Images and Copying\n","metadata":{}},{"cell_type":"code","source":"\nfiltered_images_dir = '/kaggle/working/filtered_images'\nos.makedirs(filtered_images_dir, exist_ok=True)\n\nfor img_name in filtered_labels_df['id']:\n    src = os.path.join(train_dir, img_name)\n    dst = os.path.join(filtered_images_dir, img_name)\n    copyfile(src, dst)\n","metadata":{"execution":{"iopub.status.busy":"2024-12-09T07:02:57.670351Z","iopub.execute_input":"2024-12-09T07:02:57.670733Z","iopub.status.idle":"2024-12-09T07:03:03.974171Z","shell.execute_reply.started":"2024-12-09T07:02:57.670704Z","shell.execute_reply":"2024-12-09T07:03:03.973471Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#### Encoding Labels and Splitting Data\n","metadata":{}},{"cell_type":"code","source":"\n\nfiltered_labels_df['breed'] = filtered_labels_df['breed'].astype('category')\nfiltered_labels_df['breed_code'] = filtered_labels_df['breed'].cat.codes\nnum_classes = filtered_labels_df['breed_code'].nunique()\n\ntrain_df, val_df = train_test_split(\n    filtered_labels_df, \n    test_size=0.2, \n    stratify=filtered_labels_df['breed_code'],\n    random_state=42\n)\n","metadata":{"execution":{"iopub.status.busy":"2024-12-09T07:03:03.975089Z","iopub.execute_input":"2024-12-09T07:03:03.975339Z","iopub.status.idle":"2024-12-09T07:03:03.990806Z","shell.execute_reply.started":"2024-12-09T07:03:03.975318Z","shell.execute_reply":"2024-12-09T07:03:03.989984Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"####  Data Augmentation and Image Loading\n","metadata":{}},{"cell_type":"code","source":"\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    rotation_range=30,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    fill_mode='nearest',\n    validation_split=0.2 \n)\n\nval_datagen = ImageDataGenerator(rescale=1./255, validation_split=0.2)  \n","metadata":{"execution":{"iopub.status.busy":"2024-12-09T07:03:03.991921Z","iopub.execute_input":"2024-12-09T07:03:03.992263Z","iopub.status.idle":"2024-12-09T07:03:03.999059Z","shell.execute_reply.started":"2024-12-09T07:03:03.992222Z","shell.execute_reply":"2024-12-09T07:03:03.998367Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#### Generating Image Data for Training and Validation\n","metadata":{}},{"cell_type":"code","source":"\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe=train_df,\n    directory=filtered_images_dir,\n    x_col='id',\n    y_col='breed',\n    subset='training', \n    batch_size=16,\n    shuffle=True,\n    class_mode='categorical',\n    target_size=(128, 128)  \n)\n\nval_generator = val_datagen.flow_from_dataframe(\n    dataframe=val_df,\n    directory=filtered_images_dir,\n    x_col='id',\n    y_col='breed',\n    subset='validation',  \n    batch_size=16,  \n    shuffle=True,\n    class_mode='categorical',\n    target_size=(128, 128)  \n)\n","metadata":{"execution":{"iopub.status.busy":"2024-12-09T07:03:04.001247Z","iopub.execute_input":"2024-12-09T07:03:04.001457Z","iopub.status.idle":"2024-12-09T07:03:04.030121Z","shell.execute_reply.started":"2024-12-09T07:03:04.001440Z","shell.execute_reply":"2024-12-09T07:03:04.029400Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#### Model Building and Training\n","metadata":{}},{"cell_type":"code","source":"base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(128, 128, 3))\n\nx = base_model.output\nx = GlobalAveragePooling2D()(x)\nx = Dropout(0.5)(x)  \nx = Dense(1024, activation='relu', kernel_regularizer=l2(0.01))(x) \nx = BatchNormalization()(x)  \nx = Dropout(0.5)(x)  \npredictions = Dense(num_classes, activation='softmax')(x)\nmodel = Model(inputs=base_model.input, outputs=predictions)\n","metadata":{"execution":{"iopub.status.busy":"2024-12-09T07:03:04.031098Z","iopub.execute_input":"2024-12-09T07:03:04.031437Z","iopub.status.idle":"2024-12-09T07:03:05.809283Z","shell.execute_reply.started":"2024-12-09T07:03:04.031407Z","shell.execute_reply":"2024-12-09T07:03:05.808371Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Compiling and Training the Model","metadata":{}},{"cell_type":"code","source":"for layer in base_model.layers[-40:]:\n    layer.trainable = True\n\nmodel.compile(optimizer=Adam(learning_rate=1e-4), loss='categorical_crossentropy', metrics=['accuracy'])\n\nearly_stopping = EarlyStopping(monitor='val_loss', patience=7, restore_best_weights=True)\nreduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1)\nmodel_checkpoint = ModelCheckpoint('best_model.keras', save_best_only=True, monitor='val_loss', mode='min')\n\nhistory = model.fit(\n    train_generator,\n    validation_data=val_generator,\n    epochs=50,  \n    callbacks=[early_stopping, reduce_lr, model_checkpoint]\n)\n","metadata":{"execution":{"iopub.status.busy":"2024-12-09T07:03:05.810454Z","iopub.execute_input":"2024-12-09T07:03:05.811112Z","iopub.status.idle":"2024-12-09T07:07:23.424421Z","shell.execute_reply.started":"2024-12-09T07:03:05.811080Z","shell.execute_reply":"2024-12-09T07:07:23.423714Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Evaluation\n","metadata":{}},{"cell_type":"code","source":"\nevaluation = model.evaluate(val_generator)\nprint(f'Validation Loss: {evaluation[0]}, Validation Accuracy: {evaluation[1]}')\n","metadata":{"execution":{"iopub.status.busy":"2024-12-09T07:07:23.425846Z","iopub.execute_input":"2024-12-09T07:07:23.426117Z","iopub.status.idle":"2024-12-09T07:07:23.598860Z","shell.execute_reply.started":"2024-12-09T07:07:23.426097Z","shell.execute_reply":"2024-12-09T07:07:23.598025Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.models import load_model\n\ndef load_original_image(img_path):\n    img = image.load_img(img_path)\n    return img\n\ndef preprocess_image(img_path, target_size):\n    img = image.load_img(img_path, target_size=target_size)\n    img_array = image.img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0)\n    img_array /= 255.0  \n    return img, img_array\ntarget_size = (128, 128)\n\nimage_paths = [\n    '/kaggle/input/dogs-breed/basenji.jpg',\n    '/kaggle/input/dogs-breed/maltese.jpg',\n    '/kaggle/input/dogs-breed/pomeranian.jpg'\n]\n\n\nactual_breeds = ['basenji', 'maltese', 'pomeranian']\n\nclass_indices = train_generator.class_indices\nclass_indices = {v: k for k, v in class_indices.items()}  \n\nplt.figure(figsize=(10, 5 * len(image_paths)))\n\nfor i, (img_path, actual_breed) in enumerate(zip(image_paths, actual_breeds), 1):\n    original_img = load_original_image(img_path)\n    img, img_array = preprocess_image(img_path, target_size)\n    predictions = model.predict(img_array)\n    predicted_class = np.argmax(predictions, axis=1)[0]\n    predicted_breed = class_indices[predicted_class]\n    plt.subplot(len(image_paths), 1, i)\n    plt.imshow(original_img)\n    plt.title(f'Predicted Breed: {predicted_breed},  Actual Breed: {actual_breed}')\n    plt.axis('off')\n\nplt.tight_layout()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-12-09T07:07:23.599769Z","iopub.execute_input":"2024-12-09T07:07:23.599985Z","iopub.status.idle":"2024-12-09T07:07:33.590472Z","shell.execute_reply.started":"2024-12-09T07:07:23.599967Z","shell.execute_reply":"2024-12-09T07:07:33.589482Z"},"trusted":true},"outputs":[],"execution_count":null}]}