{"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":"# 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-02-21T04:59:55.016814Z","iopub.execute_input":"2023-02-21T04:59:55.01717Z","iopub.status.idle":"2023-02-21T05:00:00.136569Z","shell.execute_reply.started":"2023-02-21T04:59:55.017141Z","shell.execute_reply":"2023-02-21T05:00:00.134386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-02-21T05:00:00.138937Z","iopub.execute_input":"2023-02-21T05:00:00.139343Z","iopub.status.idle":"2023-02-21T05:00:00.15139Z","shell.execute_reply.started":"2023-02-21T05:00:00.139302Z","shell.execute_reply":"2023-02-21T05:00:00.149339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# training and validation data\n\nlabels = pd.read_csv('/kaggle/input/dog-breed-identification/labels.csv')\nlabels.head()","metadata":{"execution":{"iopub.status.busy":"2023-02-21T05:00:35.745558Z","iopub.execute_input":"2023-02-21T05:00:35.745965Z","iopub.status.idle":"2023-02-21T05:00:35.76988Z","shell.execute_reply.started":"2023-02-21T05:00:35.745925Z","shell.execute_reply":"2023-02-21T05:00:35.768474Z"},"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":"2023-02-21T05:00:39.47198Z","iopub.execute_input":"2023-02-21T05:00:39.472363Z","iopub.status.idle":"2023-02-21T05:00:39.488286Z","shell.execute_reply.started":"2023-02-21T05:00:39.472332Z","shell.execute_reply":"2023-02-21T05:00:39.486628Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels['breed'].value_counts().plot.bar(figsize=(16, 8))","metadata":{"execution":{"iopub.status.busy":"2023-02-21T05:00:41.759529Z","iopub.execute_input":"2023-02-21T05:00:41.759944Z","iopub.status.idle":"2023-02-21T05:00:43.298746Z","shell.execute_reply.started":"2023-02-21T05:00:41.759915Z","shell.execute_reply":"2023-02-21T05:00:43.297277Z"},"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.\n\n","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":"2023-02-21T05:00:48.176691Z","iopub.execute_input":"2023-02-21T05:00:48.177139Z","iopub.status.idle":"2023-02-21T05:00:48.183756Z","shell.execute_reply.started":"2023-02-21T05:00:48.177104Z","shell.execute_reply":"2023-02-21T05:00:48.182207Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = data_generator.flow_from_dataframe(labels, directory='/kaggle/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='/kaggle/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":"2023-02-21T05:01:06.123053Z","iopub.execute_input":"2023-02-21T05:01:06.123419Z","iopub.status.idle":"2023-02-21T05:01:12.346564Z","shell.execute_reply.started":"2023-02-21T05:01:06.123389Z","shell.execute_reply":"2023-02-21T05:01:12.345391Z"},"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":"2023-02-21T05:01:14.978515Z","iopub.execute_input":"2023-02-21T05:01:14.979273Z","iopub.status.idle":"2023-02-21T05:01:44.570682Z","shell.execute_reply.started":"2023-02-21T05:01:14.979238Z","shell.execute_reply":"2023-02-21T05:01:44.569382Z"},"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":"2023-02-21T05:01:49.497245Z","iopub.execute_input":"2023-02-21T05:01:49.497608Z","iopub.status.idle":"2023-02-21T05:01:49.506672Z","shell.execute_reply.started":"2023-02-21T05:01:49.497572Z","shell.execute_reply":"2023-02-21T05:01:49.505Z"},"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":"2023-02-21T05:01:54.082057Z","iopub.execute_input":"2023-02-21T05:01:54.08243Z","iopub.status.idle":"2023-02-21T05:01:55.660942Z","shell.execute_reply.started":"2023-02-21T05:01:54.082399Z","shell.execute_reply":"2023-02-21T05:01:55.659671Z"},"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":"2023-02-21T05:02:09.012023Z","iopub.execute_input":"2023-02-21T05:02:09.012426Z","iopub.status.idle":"2023-02-21T05:02:09.022528Z","shell.execute_reply.started":"2023-02-21T05:02:09.012392Z","shell.execute_reply":"2023-02-21T05:02:09.021072Z"},"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":"2023-02-21T05:02:15.921965Z","iopub.execute_input":"2023-02-21T05:02:15.922306Z","iopub.status.idle":"2023-02-21T05:02:15.978567Z","shell.execute_reply.started":"2023-02-21T05:02:15.922278Z","shell.execute_reply":"2023-02-21T05:02:15.97673Z"},"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":"2023-02-21T05:02:19.194898Z","iopub.execute_input":"2023-02-21T05:02:19.195286Z","iopub.status.idle":"2023-02-21T05:02:19.218164Z","shell.execute_reply.started":"2023-02-21T05:02:19.195255Z","shell.execute_reply":"2023-02-21T05:02:19.216971Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","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":{"execution":{"iopub.status.busy":"2023-02-21T05:02:25.66998Z","iopub.execute_input":"2023-02-21T05:02:25.670382Z","iopub.status.idle":"2023-02-21T05:02:25.678219Z","shell.execute_reply.started":"2023-02-21T05:02:25.670352Z","shell.execute_reply":"2023-02-21T05:02:25.676213Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#first cycle\n\nhistory1 = model.fit(train_generator, epochs=5, validation_data=val_generator, callbacks=[checkpoint])","metadata":{"execution":{"iopub.status.busy":"2023-02-21T05:02:28.794121Z","iopub.execute_input":"2023-02-21T05:02:28.794458Z"},"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":"2023-02-21T05:00:00.246719Z","iopub.status.idle":"2023-02-21T05:00:00.24747Z","shell.execute_reply.started":"2023-02-21T05:00:00.247236Z","shell.execute_reply":"2023-02-21T05:00:00.247258Z"},"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":"2023-02-21T05:00:00.249403Z","iopub.status.idle":"2023-02-21T05:00:00.249943Z","shell.execute_reply.started":"2023-02-21T05:00:00.249664Z","shell.execute_reply":"2023-02-21T05:00:00.249686Z"},"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":"2023-02-21T05:00:00.251686Z","iopub.status.idle":"2023-02-21T05:00:00.25225Z","shell.execute_reply.started":"2023-02-21T05:00:00.252003Z","shell.execute_reply":"2023-02-21T05:00:00.252026Z"},"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":"2023-02-21T05:00:00.253574Z","iopub.status.idle":"2023-02-21T05:00:00.254054Z","shell.execute_reply.started":"2023-02-21T05:00:00.253817Z","shell.execute_reply":"2023-02-21T05:00:00.253839Z"},"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":"2023-02-21T05:00:00.256146Z","iopub.status.idle":"2023-02-21T05:00:00.256626Z","shell.execute_reply.started":"2023-02-21T05:00:00.256394Z","shell.execute_reply":"2023-02-21T05:00:00.256417Z"},"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":"2023-02-21T05:00:00.259Z","iopub.status.idle":"2023-02-21T05:00:00.259486Z","shell.execute_reply.started":"2023-02-21T05:00:00.259247Z","shell.execute_reply":"2023-02-21T05:00:00.25927Z"},"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":"2023-02-21T05:00:00.262083Z","iopub.status.idle":"2023-02-21T05:00:00.262609Z","shell.execute_reply.started":"2023-02-21T05:00:00.262349Z","shell.execute_reply":"2023-02-21T05:00:00.26237Z"},"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":"2023-02-21T05:00:00.264828Z","iopub.status.idle":"2023-02-21T05:00:00.265336Z","shell.execute_reply.started":"2023-02-21T05:00:00.265109Z","shell.execute_reply":"2023-02-21T05:00:00.26513Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history3 = model.fit(train_generator, epochs=50, validation_data=val_generator, callbacks=[checkpoint, early_stopping])","metadata":{"execution":{"iopub.status.busy":"2023-02-21T05:00:00.267604Z","iopub.status.idle":"2023-02-21T05:00:00.268021Z","shell.execute_reply.started":"2023-02-21T05:00:00.267839Z","shell.execute_reply":"2023-02-21T05:00:00.267857Z"},"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":"2023-02-21T05:00:00.269726Z","iopub.status.idle":"2023-02-21T05:00:00.270109Z","shell.execute_reply.started":"2023-02-21T05:00:00.269947Z","shell.execute_reply":"2023-02-21T05:00:00.269964Z"},"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":"2023-02-21T05:00:00.271695Z","iopub.status.idle":"2023-02-21T05:00:00.272084Z","shell.execute_reply.started":"2023-02-21T05:00:00.27191Z","shell.execute_reply":"2023-02-21T05:00:00.271927Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"The model performance did not improve at all so we will return to the best weights reached in the second cycle.","metadata":{"execution":{"iopub.status.busy":"2023-02-21T05:00:00.273228Z","iopub.status.idle":"2023-02-21T05:00:00.273561Z","shell.execute_reply.started":"2023-02-21T05:00:00.273403Z","shell.execute_reply":"2023-02-21T05:00:00.273418Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# loading the testset\n\ntest_images_files_names = os.listdir('../input/dogs-classification-2022-fall/test/test/')\ntest_set = pd.DataFrame(test_images_files_names, columns=['id'])\ntest_set.head()","metadata":{"execution":{"iopub.status.busy":"2023-02-21T05:00:00.274742Z","iopub.status.idle":"2023-02-21T05:00:00.275123Z","shell.execute_reply.started":"2023-02-21T05:00:00.27495Z","shell.execute_reply":"2023-02-21T05:00:00.274967Z"},"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/dogs-classification-2022-fall/test/test/', x_col='id',target_size=SIZE, class_mode=None, batch_size=BATCH_SIZE, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2023-02-21T05:00:00.276244Z","iopub.status.idle":"2023-02-21T05:00:00.276691Z","shell.execute_reply.started":"2023-02-21T05:00:00.276432Z","shell.execute_reply":"2023-02-21T05:00:00.276449Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.load_weights('./weights.hdf5')","metadata":{"execution":{"iopub.status.busy":"2023-02-21T05:00:00.277483Z","iopub.status.idle":"2023-02-21T05:00:00.27783Z","shell.execute_reply.started":"2023-02-21T05:00:00.27765Z","shell.execute_reply":"2023-02-21T05:00:00.277666Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_prop = model.predict(test_generator)","metadata":{"execution":{"iopub.status.busy":"2023-02-21T05:00:00.280303Z","iopub.status.idle":"2023-02-21T05:00:00.280829Z","shell.execute_reply.started":"2023-02-21T05:00:00.280581Z","shell.execute_reply":"2023-02-21T05:00:00.280602Z"},"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":"2023-02-21T05:00:00.282166Z","iopub.status.idle":"2023-02-21T05:00:00.282534Z","shell.execute_reply.started":"2023-02-21T05:00:00.282366Z","shell.execute_reply":"2023-02-21T05:00:00.282383Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results[\"id\"] = [os.path.splitext(file)[0] for file in os.listdir('../input/dogs-classification-2022-fall/test/test/')]\nresults.head()","metadata":{"execution":{"iopub.status.busy":"2023-02-21T05:00:00.283567Z","iopub.status.idle":"2023-02-21T05:00:00.283952Z","shell.execute_reply.started":"2023-02-21T05:00:00.283753Z","shell.execute_reply":"2023-02-21T05:00:00.28377Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results[[*train_generator.class_indices.keys()]] = y_prop\nresults.head()\n\nresults.to_csv(\"results2.csv\",index=False)","metadata":{"execution":{"iopub.status.busy":"2023-02-21T05:00:00.284922Z","iopub.status.idle":"2023-02-21T05:00:00.285259Z","shell.execute_reply.started":"2023-02-21T05:00:00.285097Z","shell.execute_reply":"2023-02-21T05:00:00.285112Z"},"trusted":true},"execution_count":null,"outputs":[]}]}