{"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, modules and pretrained model \n\nimport os\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom skimage import io\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.layers import Input, Dense, Conv2D, MaxPool2D, Dropout, Flatten, AveragePooling2D\nfrom tensorflow.keras.optimizers import RMSprop, SGD\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.applications.xception import Xception\n\n\nSEED = 42\nSIZE = (224, 224)\nBATCH_SIZE = 32\n\npd.set_option('display.max_rows', None)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-03-29T23:51:01.819513Z","iopub.execute_input":"2022-03-29T23:51:01.820193Z","iopub.status.idle":"2022-03-29T23:51:08.436627Z","shell.execute_reply.started":"2022-03-29T23:51:01.820098Z","shell.execute_reply":"2022-03-29T23:51:08.435886Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# training and validation data\n\nlabels = pd.read_csv('../input/dog-breed-identification/labels.csv')\nlabels.head()","metadata":{"execution":{"iopub.status.busy":"2022-03-29T23:51:08.439252Z","iopub.execute_input":"2022-03-29T23:51:08.439474Z","iopub.status.idle":"2022-03-29T23:51:08.484303Z","shell.execute_reply.started":"2022-03-29T23:51:08.439448Z","shell.execute_reply":"2022-03-29T23:51:08.483506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels['id'] = labels['id'].apply(lambda x: x + '.jpg')\nlabels.head()","metadata":{"execution":{"iopub.status.busy":"2022-03-29T23:51:08.485654Z","iopub.execute_input":"2022-03-29T23:51:08.485883Z","iopub.status.idle":"2022-03-29T23:51:08.503461Z","shell.execute_reply.started":"2022-03-29T23:51:08.485854Z","shell.execute_reply":"2022-03-29T23:51:08.502799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels['breed'].value_counts().plot.bar(figsize=(16, 8))","metadata":{"execution":{"iopub.status.busy":"2022-03-29T23:51:08.505466Z","iopub.execute_input":"2022-03-29T23:51:08.506183Z","iopub.status.idle":"2022-03-29T23:51:10.430957Z","shell.execute_reply.started":"2022-03-29T23:51:08.506145Z","shell.execute_reply":"2022-03-29T23:51:10.430175Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"****The data distribution is kind of ok. Maybe some data augmentaion to increase the lower quantity classes can be useful. Hopefully this part will be added to the notebook soon.****","metadata":{}},{"cell_type":"code","source":"# ImageDatagenerator to load the images in batches and perform data augmentation\n\ndata_generator = ImageDataGenerator(rescale= 1./255, validation_split=0.2, rotation_range=20,\n                                    zoom_range=0.1, width_shift_range=0.2, height_shift_range=0.2,\n                                    shear_range=0.1, horizontal_flip=True, fill_mode=\"nearest\")","metadata":{"execution":{"iopub.status.busy":"2022-03-29T23:51:10.431973Z","iopub.execute_input":"2022-03-29T23:51:10.432217Z","iopub.status.idle":"2022-03-29T23:51:10.438081Z","shell.execute_reply.started":"2022-03-29T23:51:10.432182Z","shell.execute_reply":"2022-03-29T23:51:10.437155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = data_generator.flow_from_dataframe(labels, directory='../input/dog-breed-identification/train/', x_col='id', y_col='breed', target_size=SIZE, class_mode='categorical', batch_size=BATCH_SIZE, shuffle=True, seed=SEED, subset='training')\nval_generator = data_generator.flow_from_dataframe(labels, directory='../input/dog-breed-identification/train/', x_col='id', y_col='breed', target_size=SIZE, class_mode='categorical', batch_size=BATCH_SIZE, shuffle=True, seed=SEED, subset='validation')","metadata":{"execution":{"iopub.status.busy":"2022-03-29T23:51:10.439936Z","iopub.execute_input":"2022-03-29T23:51:10.440475Z","iopub.status.idle":"2022-03-29T23:51:39.485041Z","shell.execute_reply.started":"2022-03-29T23:51:10.440438Z","shell.execute_reply":"2022-03-29T23:51:39.484273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 12 images after augmentation\n\nimg, label = next(train_generator)\n\nfig = plt.figure(figsize=(15, 10))\n\nfor i in range(12):\n    fig.add_subplot(3, 4, i+1)\n    plt.imshow(img[i])\n    plt.axis('off')","metadata":{"execution":{"iopub.status.busy":"2022-03-29T23:51:39.486479Z","iopub.execute_input":"2022-03-29T23:51:39.486747Z","iopub.status.idle":"2022-03-29T23:51:40.939009Z","shell.execute_reply.started":"2022-03-29T23:51:39.486711Z","shell.execute_reply":"2022-03-29T23:51:40.937682Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# callbacks that will be used during training\n\nearly_stopping = EarlyStopping(monitor='val_loss', mode = 'min', patience=10)\ncheckpoint = ModelCheckpoint(filepath = './weights.hdf5', verbose=1, save_best_only=True)\\","metadata":{"execution":{"iopub.status.busy":"2022-03-29T23:51:40.940355Z","iopub.execute_input":"2022-03-29T23:51:40.940791Z","iopub.status.idle":"2022-03-29T23:51:40.94538Z","shell.execute_reply.started":"2022-03-29T23:51:40.940756Z","shell.execute_reply":"2022-03-29T23:51:40.944493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"****The pretrained Xeption model on the imagenet dataset will be used. The Inception and ResNet models were also tried but have not performed better.****","metadata":{}},{"cell_type":"code","source":"base_model = Xception(weights=\"imagenet\", include_top=False, input_tensor=Input(shape=(224, 224, 3)))\n\nbase_model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-03-29T23:51:40.946987Z","iopub.execute_input":"2022-03-29T23:51:40.947655Z","iopub.status.idle":"2022-03-29T23:51:44.966127Z","shell.execute_reply.started":"2022-03-29T23:51:40.947622Z","shell.execute_reply":"2022-03-29T23:51:44.9654Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for layer in base_model.layers:\n    layer.trainable = False","metadata":{"execution":{"iopub.status.busy":"2022-03-29T23:51:44.969225Z","iopub.execute_input":"2022-03-29T23:51:44.969461Z","iopub.status.idle":"2022-03-29T23:51:44.980113Z","shell.execute_reply.started":"2022-03-29T23:51:44.969434Z","shell.execute_reply":"2022-03-29T23:51:44.979346Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"head_model = AveragePooling2D(pool_size=(4, 4))(base_model.output)\nhead_model = Flatten(name='flatten')(head_model)\nhead_model = Dense(1024, activation='relu')(head_model)\nhead_model = Dropout(0.3)(head_model)\nhead_model = Dense(512, activation='relu')(head_model)\nhead_model = Dropout(0.3)(head_model)\nhead_model = Dense(120, activation='softmax')(head_model)","metadata":{"execution":{"iopub.status.busy":"2022-03-29T23:51:44.982785Z","iopub.execute_input":"2022-03-29T23:51:44.98302Z","iopub.status.idle":"2022-03-29T23:51:45.024991Z","shell.execute_reply.started":"2022-03-29T23:51:44.982994Z","shell.execute_reply":"2022-03-29T23:51:45.02421Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Model(inputs=base_model.input, outputs=head_model)\noptimizer = SGD(learning_rate=0.1, momentum=0.9, decay=0.01)\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=optimizer, metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2022-03-29T23:51:45.026613Z","iopub.execute_input":"2022-03-29T23:51:45.027127Z","iopub.status.idle":"2022-03-29T23:51:45.053332Z","shell.execute_reply.started":"2022-03-29T23:51:45.027089Z","shell.execute_reply":"2022-03-29T23:51:45.052559Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**The model will be trained in 3 cycles. The first cycle only the added classifier's layers to the network \"head_model\" will be trainable with a relativly high learing rate. During the second cycle half of the xception model's layers will be unfrozen while the third cycle all of the layers will be unfrozen. During the second and third cycles the learning rate of the optimizer will be reduced.**","metadata":{}},{"cell_type":"code","source":"#first cycle\n\nhistory1 = model.fit(train_generator, epochs=5, validation_data=val_generator, callbacks=[checkpoint])","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-03-29T23:51:45.0545Z","iopub.execute_input":"2022-03-29T23:51:45.055178Z","iopub.status.idle":"2022-03-30T00:05:33.748364Z","shell.execute_reply.started":"2022-03-29T23:51:45.05514Z","shell.execute_reply":"2022-03-30T00:05:33.747622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history1.history['accuracy'], label='training accuracy')\nplt.plot(history1.history['val_accuracy'], label='validation accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Training and Validation Accuracy')\nplt.legend(loc='lower right')","metadata":{"execution":{"iopub.status.busy":"2022-03-30T00:05:33.749851Z","iopub.execute_input":"2022-03-30T00:05:33.750955Z","iopub.status.idle":"2022-03-30T00:05:33.987432Z","shell.execute_reply.started":"2022-03-30T00:05:33.750914Z","shell.execute_reply":"2022-03-30T00:05:33.986748Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history1.history['loss'], label='training loss')\nplt.plot(history1.history['val_loss'], label='validation loss')\nplt.xlabel('Epochs')\nplt.ylabel('Training and Validation Loss')\nplt.legend()","metadata":{"execution":{"iopub.status.busy":"2022-03-30T00:05:33.988536Z","iopub.execute_input":"2022-03-30T00:05:33.989264Z","iopub.status.idle":"2022-03-30T00:05:34.225215Z","shell.execute_reply.started":"2022-03-30T00:05:33.989222Z","shell.execute_reply":"2022-03-30T00:05:34.224462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#second cycle\n\nfor layer in base_model.layers[len(base_model.layers)//2:]:\n    layer.trainable = True\n\noptimizer = SGD(learning_rate=0.01, momentum=0.9, decay=0.001)\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=optimizer, metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2022-03-30T00:05:34.226818Z","iopub.execute_input":"2022-03-30T00:05:34.22734Z","iopub.status.idle":"2022-03-30T00:05:34.24582Z","shell.execute_reply.started":"2022-03-30T00:05:34.227289Z","shell.execute_reply":"2022-03-30T00:05:34.244949Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history2 = model.fit(train_generator, epochs=10, validation_data=val_generator, callbacks=[checkpoint])","metadata":{"execution":{"iopub.status.busy":"2022-03-30T00:05:34.247496Z","iopub.execute_input":"2022-03-30T00:05:34.2478Z","iopub.status.idle":"2022-03-30T00:31:11.565201Z","shell.execute_reply.started":"2022-03-30T00:05:34.247761Z","shell.execute_reply":"2022-03-30T00:31:11.564398Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history2.history['accuracy'], label='training accuracy')\nplt.plot(history2.history['val_accuracy'], label='validation accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Training and Validation Accuracy')\nplt.legend(loc='lower right')","metadata":{"execution":{"iopub.status.busy":"2022-03-30T00:31:11.567076Z","iopub.execute_input":"2022-03-30T00:31:11.56735Z","iopub.status.idle":"2022-03-30T00:31:11.799822Z","shell.execute_reply.started":"2022-03-30T00:31:11.567314Z","shell.execute_reply":"2022-03-30T00:31:11.799091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history2.history['loss'], label='training loss')\nplt.plot(history2.history['val_loss'], label='validation loss')\nplt.xlabel('Epochs')\nplt.ylabel('Training and Validation Loss')\nplt.legend()","metadata":{"execution":{"iopub.status.busy":"2022-03-30T00:31:11.801003Z","iopub.execute_input":"2022-03-30T00:31:11.801647Z","iopub.status.idle":"2022-03-30T00:31:12.015145Z","shell.execute_reply.started":"2022-03-30T00:31:11.801607Z","shell.execute_reply":"2022-03-30T00:31:12.014405Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**The model clearly started overfitting after after couple of epochs so the best weights saved in the weigh.hdf5 file will be loaded before the third cycle.**","metadata":{}},{"cell_type":"code","source":"model.load_weights('./weights.hdf5')","metadata":{"execution":{"iopub.status.busy":"2022-03-30T00:31:12.016411Z","iopub.execute_input":"2022-03-30T00:31:12.01666Z","iopub.status.idle":"2022-03-30T00:31:12.26341Z","shell.execute_reply.started":"2022-03-30T00:31:12.016626Z","shell.execute_reply":"2022-03-30T00:31:12.262646Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# third cycle\n\nfor layer in base_model.layers:\n    layer.trainable = True\n\noptimizer = SGD(learning_rate=0.01, momentum=0.9, decay=0.001)\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=optimizer, metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2022-03-30T00:31:12.265222Z","iopub.execute_input":"2022-03-30T00:31:12.265765Z","iopub.status.idle":"2022-03-30T00:31:12.287094Z","shell.execute_reply.started":"2022-03-30T00:31:12.265724Z","shell.execute_reply":"2022-03-30T00:31:12.286416Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history3 = model.fit(train_generator, epochs=100, validation_data=val_generator, callbacks=[checkpoint, early_stopping])","metadata":{"execution":{"iopub.status.busy":"2022-03-30T00:31:12.288068Z","iopub.execute_input":"2022-03-30T00:31:12.288259Z","iopub.status.idle":"2022-03-30T01:23:45.557639Z","shell.execute_reply.started":"2022-03-30T00:31:12.288236Z","shell.execute_reply":"2022-03-30T01:23:45.556872Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history3.history['accuracy'], label='training accuracy')\nplt.plot(history3.history['val_accuracy'], label='validation accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Training and Validation Accuracy')\nplt.legend(loc='lower right')","metadata":{"execution":{"iopub.status.busy":"2022-03-30T01:23:45.559364Z","iopub.execute_input":"2022-03-30T01:23:45.559685Z","iopub.status.idle":"2022-03-30T01:23:45.787036Z","shell.execute_reply.started":"2022-03-30T01:23:45.559642Z","shell.execute_reply":"2022-03-30T01:23:45.786392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history3.history['loss'], label='training loss')\nplt.plot(history3.history['val_loss'], label='validation loss')\nplt.xlabel('Epochs')\nplt.ylabel('Training and Validation Loss')\nplt.legend()","metadata":{"execution":{"iopub.status.busy":"2022-03-30T01:25:12.003485Z","iopub.execute_input":"2022-03-30T01:25:12.003754Z","iopub.status.idle":"2022-03-30T01:25:12.229492Z","shell.execute_reply.started":"2022-03-30T01:25:12.003724Z","shell.execute_reply":"2022-03-30T01:25:12.228849Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**The model performance did not improve at all so we will return to the best weights reached in the second cycle.**","metadata":{}},{"cell_type":"code","source":"# loading the testset\n\ntest_images_files_names = os.listdir('../input/dog-breed-identification/test/')\ntest_set = pd.DataFrame(test_images_files_names, columns=['id'])\ntest_set.head()","metadata":{"execution":{"iopub.status.busy":"2022-03-30T01:25:14.048414Z","iopub.execute_input":"2022-03-30T01:25:14.048983Z","iopub.status.idle":"2022-03-30T01:25:14.396162Z","shell.execute_reply.started":"2022-03-30T01:25:14.048936Z","shell.execute_reply":"2022-03-30T01:25:14.395479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data_generator = ImageDataGenerator(rescale= 1./255)\ntest_generator = test_data_generator.flow_from_dataframe(test_set, directory='../input/dog-breed-identification/test/', x_col='id',target_size=SIZE, class_mode=None, batch_size=BATCH_SIZE, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2022-03-30T01:25:20.811371Z","iopub.execute_input":"2022-03-30T01:25:20.811639Z","iopub.status.idle":"2022-03-30T01:25:40.117647Z","shell.execute_reply.started":"2022-03-30T01:25:20.811609Z","shell.execute_reply":"2022-03-30T01:25:40.116894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.load_weights('./weights.hdf5')","metadata":{"execution":{"iopub.status.busy":"2022-03-30T01:25:40.11917Z","iopub.execute_input":"2022-03-30T01:25:40.11998Z","iopub.status.idle":"2022-03-30T01:25:40.366938Z","shell.execute_reply.started":"2022-03-30T01:25:40.119942Z","shell.execute_reply":"2022-03-30T01:25:40.366172Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_prop = model.predict(test_generator)","metadata":{"execution":{"iopub.status.busy":"2022-03-30T01:25:40.368335Z","iopub.execute_input":"2022-03-30T01:25:40.368575Z","iopub.status.idle":"2022-03-30T01:27:02.169564Z","shell.execute_reply.started":"2022-03-30T01:25:40.368542Z","shell.execute_reply":"2022-03-30T01:27:02.168758Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results = pd.DataFrame(columns=[\"id\"] + [*train_generator.class_indices.keys()])\nresults","metadata":{"execution":{"iopub.status.busy":"2022-03-30T01:27:02.173448Z","iopub.execute_input":"2022-03-30T01:27:02.173882Z","iopub.status.idle":"2022-03-30T01:27:02.194347Z","shell.execute_reply.started":"2022-03-30T01:27:02.173853Z","shell.execute_reply":"2022-03-30T01:27:02.193688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results[\"id\"] = [os.path.splitext(file)[0] for file in os.listdir('../input/dog-breed-identification/test/')]\nresults.head()","metadata":{"execution":{"iopub.status.busy":"2022-03-30T01:27:02.196549Z","iopub.execute_input":"2022-03-30T01:27:02.197224Z","iopub.status.idle":"2022-03-30T01:27:02.247402Z","shell.execute_reply.started":"2022-03-30T01:27:02.197188Z","shell.execute_reply":"2022-03-30T01:27:02.246637Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results[[*train_generator.class_indices.keys()]] = y_prop\nresults.head()\n\nresults.to_csv(\"results.csv\",index=False)","metadata":{"execution":{"iopub.status.busy":"2022-03-30T01:27:02.248709Z","iopub.execute_input":"2022-03-30T01:27:02.249022Z","iopub.status.idle":"2022-03-30T01:27:04.687061Z","shell.execute_reply.started":"2022-03-30T01:27:02.248986Z","shell.execute_reply":"2022-03-30T01:27:04.686334Z"},"trusted":true},"execution_count":null,"outputs":[]}]}