{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"#Importing required libraries\nimport os\nimport gc\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport pandas as pd \n\nfrom sklearn.model_selection import train_test_split\nfrom tqdm.autonotebook import tqdm\n\nimport tensorflow as tf\nfrom keras import Sequential\nfrom keras.callbacks import EarlyStopping\nfrom keras.optimizers import Adam, SGD\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.layers import Flatten,Dense,BatchNormalization,Activation,Dropout\nfrom keras.layers import Lambda, Input, GlobalAveragePooling2D,BatchNormalization\nfrom keras.utils import to_categorical\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.preprocessing.image import load_img","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:50:03.424309Z","iopub.execute_input":"2023-06-19T22:50:03.424595Z","iopub.status.idle":"2023-06-19T22:50:12.698135Z","shell.execute_reply.started":"2023-06-19T22:50:03.424569Z","shell.execute_reply":"2023-06-19T22:50:12.697201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = pd.read_csv('/kaggle/input/dog-breed-identification/labels.csv')\nlabels.head()","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:50:12.700150Z","iopub.execute_input":"2023-06-19T22:50:12.701008Z","iopub.status.idle":"2023-06-19T22:50:12.742059Z","shell.execute_reply.started":"2023-06-19T22:50:12.700971Z","shell.execute_reply":"2023-06-19T22:50:12.741222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Create list of alphabetically sorted labels.\nclasses = sorted(list(set(labels['breed'])))\nn_classes = len(classes)\nprint('Total unique breed {}'.format(n_classes))\n\n\n#Map each label string to an integer label.\nclass_to_num = dict(zip(classes, range(n_classes)))","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:50:12.743407Z","iopub.execute_input":"2023-06-19T22:50:12.743747Z","iopub.status.idle":"2023-06-19T22:50:12.751773Z","shell.execute_reply.started":"2023-06-19T22:50:12.743700Z","shell.execute_reply":"2023-06-19T22:50:12.750811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"input_shape = (331,331,3)\n\ndef images_to_array(directory, label_dataframe, target_size = input_shape):\n    \n    image_labels = label_dataframe['breed']\n    images = np.zeros([len(label_dataframe), target_size[0], target_size[1], target_size[2]],dtype=np.uint8) #as we have huge data and limited ram memory. uint8 takes less memory\n    y = np.zeros([len(label_dataframe),1],dtype = np.uint8)\n    \n    for ix, image_name in enumerate(tqdm(label_dataframe['id'].values)):\n        img_dir = os.path.join(directory, image_name + '.jpg')\n        img = load_img(img_dir, target_size = target_size)\n        images[ix] = img\n        del img\n        \n        dog_breed = image_labels[ix]\n        y[ix] = class_to_num[dog_breed]\n    \n    y = to_categorical(y)\n    \n    return images, y","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:50:12.754532Z","iopub.execute_input":"2023-06-19T22:50:12.755338Z","iopub.status.idle":"2023-06-19T22:50:12.764550Z","shell.execute_reply.started":"2023-06-19T22:50:12.755306Z","shell.execute_reply":"2023-06-19T22:50:12.763462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import time \nt = time.time()\n\nX, y = images_to_array('/kaggle/input/dog-breed-identification/train', labels[:])\n\nprint('runtime in seconds: {}'.format(time.time() - t))","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:50:12.766073Z","iopub.execute_input":"2023-06-19T22:50:12.766411Z","iopub.status.idle":"2023-06-19T22:51:10.711304Z","shell.execute_reply.started":"2023-06-19T22:50:12.766379Z","shell.execute_reply":"2023-06-19T22:51:10.710222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Learning Rate Annealer\nlrr= ReduceLROnPlateau(monitor='val_acc', factor=.01, patience=3, min_lr=1e-5,verbose = 1)\n\n#Prepare call backs\nEarlyStop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:51:10.713007Z","iopub.execute_input":"2023-06-19T22:51:10.713373Z","iopub.status.idle":"2023-06-19T22:51:10.719701Z","shell.execute_reply.started":"2023-06-19T22:51:10.713339Z","shell.execute_reply":"2023-06-19T22:51:10.718436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Hyperparameters\nbatch_size= 128\nepochs=100\nlearn_rate=.001\nsgd=SGD(learning_rate=learn_rate, momentum=0.9, nesterov=False)\nadam=Adam(learning_rate=learn_rate, beta_1=0.9, beta_2=0.999, epsilon=None,  amsgrad=False)","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:51:10.721234Z","iopub.execute_input":"2023-06-19T22:51:10.721556Z","iopub.status.idle":"2023-06-19T22:51:10.743055Z","shell.execute_reply.started":"2023-06-19T22:51:10.721525Z","shell.execute_reply":"2023-06-19T22:51:10.742208Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#function to extract features from the dataset by a given pretrained model\nimg_size = (331,331,3)\n\ndef get_features(model_name, model_preprocessor, input_size, data):\n\n    input_layer = Input(input_size)\n    preprocessor = Lambda(model_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    \n    #Extract feature.\n    feature_maps = feature_extractor.predict(data, verbose=1)\n    print('Feature maps shape: ', feature_maps.shape)\n    return feature_maps","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:51:10.744510Z","iopub.execute_input":"2023-06-19T22:51:10.744805Z","iopub.status.idle":"2023-06-19T22:51:10.752793Z","shell.execute_reply.started":"2023-06-19T22:51:10.744777Z","shell.execute_reply":"2023-06-19T22:51:10.751834Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Extract features using InceptionV3 \nfrom keras.applications.inception_v3 import InceptionV3, preprocess_input\ninception_preprocessor = preprocess_input\ninception_features = get_features(InceptionV3,\n                                  inception_preprocessor,\n                                  img_size, X)\n\nprint('Inception feature maps shape', inception_features.shape)","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:51:10.754074Z","iopub.execute_input":"2023-06-19T22:51:10.754523Z","iopub.status.idle":"2023-06-19T22:52:10.288533Z","shell.execute_reply.started":"2023-06-19T22:51:10.754491Z","shell.execute_reply":"2023-06-19T22:52:10.287476Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del X #to free up some ram memory\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:52:10.292381Z","iopub.execute_input":"2023-06-19T22:52:10.293219Z","iopub.status.idle":"2023-06-19T22:52:10.964102Z","shell.execute_reply.started":"2023-06-19T22:52:10.293182Z","shell.execute_reply":"2023-06-19T22:52:10.963185Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Prepare Deep net\n\nmodel = Sequential()\n# model.add(Dense(1028,input_shape=(final_features.shape[1],)))\nmodel.add(Dropout(0.7,input_shape=(inception_features.shape[1],)))\nmodel.add(Dense(n_classes,activation= 'softmax'))\n\nmodel.compile(optimizer=adam,\n              loss='categorical_crossentropy',\n              metrics=['accuracy'])\n\n#Training the model. \nhistory = model.fit(inception_features, y,\n            batch_size=batch_size,\n            epochs=epochs,\n            validation_split=0.2,\n            callbacks=[lrr, EarlyStop])","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:52:10.967007Z","iopub.execute_input":"2023-06-19T22:52:10.967524Z","iopub.status.idle":"2023-06-19T22:52:21.043985Z","shell.execute_reply.started":"2023-06-19T22:52:10.967498Z","shell.execute_reply":"2023-06-19T22:52:21.043038Z"},"scrolled":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:52:21.045323Z","iopub.execute_input":"2023-06-19T22:52:21.045688Z","iopub.status.idle":"2023-06-19T22:52:21.063643Z","shell.execute_reply.started":"2023-06-19T22:52:21.045654Z","shell.execute_reply":"2023-06-19T22:52:21.062920Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot result\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(acc) + 1)\n\n# Accuracy\nplt.plot(epochs, acc, label='Train accuracy')\nplt.plot(epochs, val_acc, label='Val accuracy')\nplt.title('Training & validation accuracy')\nplt.legend()\n\n# Loss\nplt.figure()\nplt.plot(epochs, loss, label='Train loss')\nplt.plot(epochs, val_loss, label='Val loss')\nplt.title('Training & validation loss')\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:52:21.064697Z","iopub.execute_input":"2023-06-19T22:52:21.065016Z","iopub.status.idle":"2023-06-19T22:52:21.662314Z","shell.execute_reply.started":"2023-06-19T22:52:21.064986Z","shell.execute_reply":"2023-06-19T22:52:21.661365Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del inception_features\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:52:21.663895Z","iopub.execute_input":"2023-06-19T22:52:21.664250Z","iopub.status.idle":"2023-06-19T22:52:21.915469Z","shell.execute_reply.started":"2023-06-19T22:52:21.664217Z","shell.execute_reply":"2023-06-19T22:52:21.914407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Function to read images from test directory\n\ndef images_to_array_test(test_path, img_size = (331,331,3)):\n    test_filenames = [test_path + fname for fname in os.listdir(test_path)]\n    data_size = len(test_filenames)\n    images = np.zeros([data_size, img_size[0], img_size[1], 3], dtype=np.uint8)\n        \n    for ix,img_dir in enumerate(tqdm(test_filenames)):\n        img = load_img(img_dir, target_size = img_size)\n        images[ix]=img\n        del img\n    print('Ouptut Data Size: ', images.shape)\n    return images\n\ntest_data = images_to_array_test('/kaggle/input/dog-breed-identification/test/', img_size)","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:52:21.917158Z","iopub.execute_input":"2023-06-19T22:52:21.917585Z","iopub.status.idle":"2023-06-19T22:53:21.653138Z","shell.execute_reply.started":"2023-06-19T22:52:21.917541Z","shell.execute_reply":"2023-06-19T22:53:21.652235Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Extract test data features.\ndef extact_features(data):\n    inception_features = get_features(InceptionV3, inception_preprocessor, img_size, data)\n    print('Inception feature maps shape', inception_features.shape)\n    return inception_features\n\ntest_features = extact_features(test_data)","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:53:21.654638Z","iopub.execute_input":"2023-06-19T22:53:21.655741Z","iopub.status.idle":"2023-06-19T22:54:13.206635Z","shell.execute_reply.started":"2023-06-19T22:53:21.655706Z","shell.execute_reply":"2023-06-19T22:54:13.205482Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Free up some space.\ndel test_data\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:54:13.208523Z","iopub.execute_input":"2023-06-19T22:54:13.208885Z","iopub.status.idle":"2023-06-19T22:54:14.109906Z","shell.execute_reply.started":"2023-06-19T22:54:13.208850Z","shell.execute_reply":"2023-06-19T22:54:14.109030Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred = model.predict(test_features)","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:54:14.114354Z","iopub.execute_input":"2023-06-19T22:54:14.116401Z","iopub.status.idle":"2023-06-19T22:54:15.119659Z","shell.execute_reply.started":"2023-06-19T22:54:14.116368Z","shell.execute_reply":"2023-06-19T22:54:15.118754Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create pandas DataFrame with empty columns\npreds_df = pd.DataFrame(columns=[\"id\"] + list(classes))\n\ntest_path = \"/kaggle/input/dog-breed-identification/test/\"\npreds_df[\"id\"] = [os.path.splitext(path)[0] for path in os.listdir(test_path)]","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:54:15.121561Z","iopub.execute_input":"2023-06-19T22:54:15.121911Z","iopub.status.idle":"2023-06-19T22:54:15.177649Z","shell.execute_reply.started":"2023-06-19T22:54:15.121878Z","shell.execute_reply":"2023-06-19T22:54:15.176727Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds_df.loc[:,list(classes)] = pred\n\npreds_df.to_csv('submission.csv',index=None)","metadata":{"execution":{"iopub.status.busy":"2023-06-19T22:54:15.179176Z","iopub.execute_input":"2023-06-19T22:54:15.179531Z","iopub.status.idle":"2023-06-19T22:54:18.810328Z","shell.execute_reply.started":"2023-06-19T22:54:15.179497Z","shell.execute_reply":"2023-06-19T22:54:18.809402Z"},"trusted":true},"execution_count":null,"outputs":[]}]}