{"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":"none","dataSources":[{"sourceId":7327,"databundleVersionId":861871,"sourceType":"competition"},{"sourceId":7220126,"sourceType":"datasetVersion","datasetId":4178877}],"dockerImageVersionId":30626,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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        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":"2023-12-17T15:25:33.618394Z","iopub.execute_input":"2023-12-17T15:25:33.618759Z","iopub.status.idle":"2023-12-17T15:25:38.472800Z","shell.execute_reply.started":"2023-12-17T15:25:33.618729Z","shell.execute_reply":"2023-12-17T15:25:38.471800Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Dog Breed Classification Exercise\n\nThe dataset contains 10,222 images of 120 breeds of dogs, labeled with the corresponding breed name in a csv file called labels.csv. The images are in JPEG format and have various resolutions and orientations. The dataset is a subset of the Stanford Dogs Dataset, which was created for fine-grained image categorization.","metadata":{}},{"cell_type":"code","source":"# Defining the paths to various folders containing the datasets\ntrain_dir = '/kaggle/input/dog-breed-identification/train'    #folder for train data\ntest_dir = '/kaggle/input/dog-breed-identification/test'    #folder for test data\nlabels_file = '/kaggle/input/dog-breed-identification/labels.csv'  #path to labels file\n\ndata_dir = '/kaggle/working/'# Output folders directory\n# Defining paths for train and validation directories\ntrain_data_dir = os.path.join(data_dir, 'train_data/')\nval_data_dir = os.path.join(data_dir, 'val_data/')","metadata":{"execution":{"iopub.status.busy":"2023-12-17T15:26:13.450905Z","iopub.execute_input":"2023-12-17T15:26:13.451663Z","iopub.status.idle":"2023-12-17T15:26:13.456660Z","shell.execute_reply.started":"2023-12-17T15:26:13.451627Z","shell.execute_reply":"2023-12-17T15:26:13.455474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Coverting the labels into a dataframe\ndog_label = pd.read_csv('/kaggle/input/dog-breed-identification/labels.csv') ","metadata":{"execution":{"iopub.status.busy":"2023-12-17T15:26:22.233978Z","iopub.execute_input":"2023-12-17T15:26:22.234374Z","iopub.status.idle":"2023-12-17T15:26:22.269718Z","shell.execute_reply.started":"2023-12-17T15:26:22.234342Z","shell.execute_reply":"2023-12-17T15:26:22.268637Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# add file extensions (.jpg) to 'Id' column in the DataFrame so thatlabels can match with actual file names\ndog_label['id'] = dog_label['id'].apply(lambda x: f'{x}.jpg')","metadata":{"execution":{"iopub.status.busy":"2023-12-17T15:27:07.249755Z","iopub.execute_input":"2023-12-17T15:27:07.250123Z","iopub.status.idle":"2023-12-17T15:27:07.264957Z","shell.execute_reply.started":"2023-12-17T15:27:07.250094Z","shell.execute_reply":"2023-12-17T15:27:07.263898Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dog_label","metadata":{"execution":{"iopub.status.busy":"2023-12-17T15:27:15.129821Z","iopub.execute_input":"2023-12-17T15:27:15.130785Z","iopub.status.idle":"2023-12-17T15:27:15.147792Z","shell.execute_reply.started":"2023-12-17T15:27:15.130745Z","shell.execute_reply":"2023-12-17T15:27:15.146692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating train and validation directories\nos.makedirs(train_data_dir, exist_ok=True)\nos.makedirs(val_data_dir, exist_ok=True)\n\n# Creating a list of image filenames from the 'train' directory\ntrain_images = os.listdir(train_dir)","metadata":{"execution":{"iopub.status.busy":"2023-12-17T15:27:21.407084Z","iopub.execute_input":"2023-12-17T15:27:21.407474Z","iopub.status.idle":"2023-12-17T15:27:21.417539Z","shell.execute_reply.started":"2023-12-17T15:27:21.407418Z","shell.execute_reply":"2023-12-17T15:27:21.416186Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Splittig the train folder and datasets into train set and Validation set","metadata":{}},{"cell_type":"code","source":"import shutil\nfrom sklearn.model_selection import train_test_split\n\n\n# Splitting the 'train' dataset into train and validation sets\ntrain_images, val_images = train_test_split(train_images, test_size=0.2, random_state=42)\n\n# Moving images to respective train and validation directories\nfor image in train_images:\n    shutil.copy(os.path.join(train_dir, image), os.path.join(train_data_dir, image))\n\nfor image in val_images:\n    shutil.copy(os.path.join(train_dir, image), os.path.join(val_data_dir, image))","metadata":{"execution":{"iopub.status.busy":"2023-12-17T15:27:32.059292Z","iopub.execute_input":"2023-12-17T15:27:32.059682Z","iopub.status.idle":"2023-12-17T15:28:38.128289Z","shell.execute_reply.started":"2023-12-17T15:27:32.059650Z","shell.execute_reply":"2023-12-17T15:28:38.127153Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Making and Executing a Pipeline to correctly match data in train and validation folders with their corresponding labels","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Define input shape and batch size\ninput_shape = (224, 224)\nbatch_size = 32\n\n\n\n# Define ImageDataGenerators for train and validation sets with preprocessing and augmentation\ntrain_datagen = ImageDataGenerator(\n    rescale=1.0/255.0,\n    rotation_range=20,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest'\n)\n\nval_datagen = ImageDataGenerator(rescale=1.0/255.0)\n\n# Generating batches of preprocessed images and labels for train and validation sets\ntrain_generator = train_datagen.flow_from_dataframe(\n    dog_label,\n    directory=train_data_dir,\n    x_col= str('id'),  \n    y_col='breed',  \n    target_size=input_shape,\n    batch_size=batch_size,\n    class_mode='categorical'\n)\n\nval_generator = val_datagen.flow_from_dataframe(\n    dog_label,\n    directory=val_data_dir,\n    x_col=str('id'),\n    y_col='breed',\n    target_size=input_shape,\n    batch_size=batch_size,\n    class_mode='categorical'\n)\n","metadata":{"execution":{"iopub.status.busy":"2023-12-17T15:32:10.282767Z","iopub.execute_input":"2023-12-17T15:32:10.283208Z","iopub.status.idle":"2023-12-17T15:32:22.584749Z","shell.execute_reply.started":"2023-12-17T15:32:10.283174Z","shell.execute_reply":"2023-12-17T15:32:22.583946Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Creating a Dog breed Baseline model","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\n\n# Creating a Sequential model\nmodel = Sequential()\n\n# Adding convolutional layers\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D((2, 2)))\n\n# Flattening the output and add dense layers\nmodel.add(Flatten())\nmodel.add(Dense(512, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dense(120, activation='softmax'))  #  number of output classes\n\n# Compiling the model\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Training the model\nhistory = model.fit(\n    train_generator,\n    steps_per_epoch=len(train_generator),\n    epochs=10,\n    validation_data=val_generator,\n    validation_steps=len(val_generator)\n)\n","metadata":{"execution":{"iopub.status.busy":"2023-12-17T01:28:08.385393Z","iopub.execute_input":"2023-12-17T01:28:08.386217Z","iopub.status.idle":"2023-12-17T03:15:50.343688Z","shell.execute_reply.started":"2023-12-17T01:28:08.386162Z","shell.execute_reply":"2023-12-17T03:15:50.342419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### we can see that the baseline model has a very poor performance and slow learning rate. Hence, we deploy a saved pretrained CNN model","metadata":{}},{"cell_type":"markdown","source":"## Using the Resnet 50 pre_trained model, we build the following deployment pipeline:","metadata":{}},{"cell_type":"code","source":"from tensorflow import keras\nfrom tensorflow.keras import layers\n\n# Defining the CNN model\ncnn_model = keras.Sequential([\n    layers.InputLayer(input_shape=(28, 28, 1)),\n    layers.Conv2D(16, 3, padding='same', activation='relu'),\n    layers.MaxPooling2D(),\n    layers.Conv2D(32, 3, padding='same', activation='relu'),\n    layers.MaxPooling2D(),\n    layers.Conv2D(64, 3, padding='same', activation='relu'),\n    layers.MaxPooling2D(),\n    layers.Flatten(),\n    layers.Dense(128, activation='relu'), #using 128 neurons\n    layers.Dense(10, activation='softmax')\n])","metadata":{"execution":{"iopub.status.busy":"2023-12-17T15:36:02.220578Z","iopub.execute_input":"2023-12-17T15:36:02.221009Z","iopub.status.idle":"2023-12-17T15:36:02.326061Z","shell.execute_reply.started":"2023-12-17T15:36:02.220974Z","shell.execute_reply":"2023-12-17T15:36:02.324976Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### I have a response that memory requirements outweighs alloted memory... hence I cannot run further.","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}