{"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-11T23:00:46.138196Z","iopub.execute_input":"2023-02-11T23:00:46.139136Z","iopub.status.idle":"2023-02-11T23:01:44.339700Z","shell.execute_reply.started":"2023-02-11T23:00:46.139039Z","shell.execute_reply":"2023-02-11T23:01:44.337906Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Imports libraries\n\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import optimizers\nfrom keras.layers.pooling import GlobalAveragePooling2D\nimport numpy as np\nimport seaborn as sns\n\nfrom tensorflow.keras import Model,layers\nfrom tensorflow.keras.optimizers import Adam\nfrom sklearn.metrics import confusion_matrix\n\n# Import the inception model  \nfrom tensorflow.keras.applications.inception_v3 import InceptionV3","metadata":{"execution":{"iopub.status.busy":"2023-02-11T23:02:36.576486Z","iopub.execute_input":"2023-02-11T23:02:36.577203Z","iopub.status.idle":"2023-02-11T23:02:42.553895Z","shell.execute_reply.started":"2023-02-11T23:02:36.577102Z","shell.execute_reply":"2023-02-11T23:02:42.552871Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\ndf_train = pd.read_csv('/kaggle/input/happy-whale-and-dolphin/train.csv', index_col=None)\ndf_test =  pd.read_csv('/kaggle/input/happy-whale-and-dolphin/sample_submission.csv', index_col=None)","metadata":{"execution":{"iopub.status.busy":"2023-02-11T23:02:47.476380Z","iopub.execute_input":"2023-02-11T23:02:47.476972Z","iopub.status.idle":"2023-02-11T23:02:47.640440Z","shell.execute_reply.started":"2023-02-11T23:02:47.476938Z","shell.execute_reply":"2023-02-11T23:02:47.639441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.head()","metadata":{"execution":{"iopub.status.busy":"2023-02-11T23:02:47.731419Z","iopub.execute_input":"2023-02-11T23:02:47.733249Z","iopub.status.idle":"2023-02-11T23:02:47.752586Z","shell.execute_reply.started":"2023-02-11T23:02:47.733199Z","shell.execute_reply":"2023-02-11T23:02:47.751533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test.head()","metadata":{"execution":{"iopub.status.busy":"2023-02-11T23:02:48.001818Z","iopub.execute_input":"2023-02-11T23:02:48.002140Z","iopub.status.idle":"2023-02-11T23:02:48.012109Z","shell.execute_reply.started":"2023-02-11T23:02:48.002111Z","shell.execute_reply":"2023-02-11T23:02:48.011053Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Apply augmentation to data\n# augmentation train only\ntrain_datagen = ImageDataGenerator(rescale = 1./255.,\n                                   validation_split=0.15,\n                                   rotation_range = 40,\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\nvalidation_datagen = ImageDataGenerator(rescale = 1./255., validation_split=0.15)\n\ntest_datagen = ImageDataGenerator(rescale = 1./255.)","metadata":{"execution":{"iopub.status.busy":"2023-02-11T23:02:48.454698Z","iopub.execute_input":"2023-02-11T23:02:48.455171Z","iopub.status.idle":"2023-02-11T23:02:48.462410Z","shell.execute_reply.started":"2023-02-11T23:02:48.455141Z","shell.execute_reply":"2023-02-11T23:02:48.460347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = \"/kaggle/input/happy-whale-and-dolphin/train_images\"\ntest_data = \"/kaggle/input/happy-whale-and-dolphin/test_images\"","metadata":{"execution":{"iopub.status.busy":"2023-02-11T23:02:48.769463Z","iopub.execute_input":"2023-02-11T23:02:48.770557Z","iopub.status.idle":"2023-02-11T23:02:48.775522Z","shell.execute_reply.started":"2023-02-11T23:02:48.770515Z","shell.execute_reply":"2023-02-11T23:02:48.774472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = train_datagen.flow_from_dataframe(dataframe=df_train,\n                                                     directory = train_data, \n                                                     x_col = 'image',\n                                                     y_col = 'species',\n                                                     batch_size = 128, \n                                                     target_size=(225,225),\n                                                     class_mode='categorical',\n                                                     shuffle=True)\n\nvalidation_generator = validation_datagen.flow_from_dataframe(dataframe=df_train,\n                                                                directory = train_data, \n                                                                target_size=(225,225),\n                                                                x_col = 'image',\n                                                                y_col = 'species',\n                                                                batch_size=128,\n                                                                class_mode='categorical',\n                                                                shuffle=False,\n                                                                subset='validation')  ","metadata":{"execution":{"iopub.status.busy":"2023-02-11T23:02:49.521822Z","iopub.execute_input":"2023-02-11T23:02:49.522990Z","iopub.status.idle":"2023-02-11T23:04:00.888127Z","shell.execute_reply.started":"2023-02-11T23:02:49.522919Z","shell.execute_reply":"2023-02-11T23:04:00.887027Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# InceptionV3","metadata":{}},{"cell_type":"code","source":"base_model = InceptionV3(\n    include_top = False,\n    weights = \"imagenet\",\n    input_shape = None)","metadata":{"execution":{"iopub.status.busy":"2023-02-11T23:04:00.890261Z","iopub.execute_input":"2023-02-11T23:04:00.890659Z","iopub.status.idle":"2023-02-11T23:04:06.333529Z","shell.execute_reply.started":"2023-02-11T23:04:00.890621Z","shell.execute_reply":"2023-02-11T23:04:06.332011Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x = base_model.output\nx = GlobalAveragePooling2D()(x)\nx = Dense(512, activation='relu')(x)\npredictions = Dense(30, activation='softmax')(x)","metadata":{"execution":{"iopub.status.busy":"2023-02-11T23:04:06.339843Z","iopub.execute_input":"2023-02-11T23:04:06.343066Z","iopub.status.idle":"2023-02-11T23:04:06.377145Z","shell.execute_reply.started":"2023-02-11T23:04:06.343014Z","shell.execute_reply":"2023-02-11T23:04:06.376151Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Model(inputs = base_model.input, outputs = predictions)\n\nfor layer in model.layers[:249]:\n    layer.trainable = False\n\n    if layer.name.startswith('batch_normalization'):\n        layer.trainable = True\n\nfor layer in model.layers[249:]:\n    layer.trainable = True\n\n# compile\nmodel.compile(\n    optimizer = Adam(),\n    loss = 'categorical_crossentropy',\n    metrics = [\"accuracy\"]\n)","metadata":{"execution":{"iopub.status.busy":"2023-02-11T23:04:06.379441Z","iopub.execute_input":"2023-02-11T23:04:06.379799Z","iopub.status.idle":"2023-02-11T23:04:06.466014Z","shell.execute_reply.started":"2023-02-11T23:04:06.379764Z","shell.execute_reply":"2023-02-11T23:04:06.465085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.callbacks import EarlyStopping\nCallback = EarlyStopping(monitor = 'val_loss',\n                          min_delta = 0,\n                          patience =2,\n                          verbose = 1,\n                          restore_best_weights = True)","metadata":{"execution":{"iopub.status.busy":"2023-02-11T23:04:06.467618Z","iopub.execute_input":"2023-02-11T23:04:06.468002Z","iopub.status.idle":"2023-02-11T23:04:06.473022Z","shell.execute_reply.started":"2023-02-11T23:04:06.467947Z","shell.execute_reply":"2023-02-11T23:04:06.471997Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(\n                    train_generator,\n                    epochs = 5,\n                    validation_data = validation_generator,\n                    callbacks = Callback,\n                    shuffle = True,\n                    verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2023-02-11T23:04:06.474694Z","iopub.execute_input":"2023-02-11T23:04:06.475165Z","iopub.status.idle":"2023-02-12T06:13:55.932368Z","shell.execute_reply.started":"2023-02-11T23:04:06.475130Z","shell.execute_reply":"2023-02-12T06:13:55.929684Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'r', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\nplt.legend()\nplt.figure()\n\nplt.plot(epochs, loss, 'r', label='Training Loss')\nplt.plot(epochs, val_loss, 'b', label='Validation Loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.figure()\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-02-12T06:13:55.938995Z","iopub.execute_input":"2023-02-12T06:13:55.944864Z","iopub.status.idle":"2023-02-12T06:13:56.416228Z","shell.execute_reply.started":"2023-02-12T06:13:55.944831Z","shell.execute_reply":"2023-02-12T06:13:56.415289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"classes = train_generator.class_indices.keys()\nclasses\n\n# Confusion matrix\ny_pred = np.argmax(model.predict(validation_generator), axis=1)\ncm = confusion_matrix(validation_generator.classes, y_pred)\nclasses = list(train_generator.class_indices.keys())","metadata":{"execution":{"iopub.status.busy":"2023-02-12T06:50:34.586244Z","iopub.execute_input":"2023-02-12T06:50:34.586907Z","iopub.status.idle":"2023-02-12T06:59:14.935162Z","shell.execute_reply.started":"2023-02-12T06:50:34.586871Z","shell.execute_reply":"2023-02-12T06:59:14.934095Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Heatmap\nplt.figure(figsize=(16,12))\nsns.heatmap(cm, annot=True, fmt='d', cbar=True, cmap='Blues',xticklabels=classes, yticklabels=classes)\nplt.xlabel('Predicted label')\nplt.ylabel('True label')\nplt.title('Confusion matrix')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-02-12T06:50:28.984945Z","iopub.execute_input":"2023-02-12T06:50:28.986030Z","iopub.status.idle":"2023-02-12T06:50:32.482724Z","shell.execute_reply.started":"2023-02-12T06:50:28.985964Z","shell.execute_reply":"2023-02-12T06:50:32.481672Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Evaluate\nscore = model.evaluate(validation_generator, verbose=False)\nprint('Validation loss:', score[0])\nprint('Validation accuracy:', score[1])","metadata":{"execution":{"iopub.status.busy":"2023-02-12T06:59:14.937228Z","iopub.execute_input":"2023-02-12T06:59:14.937613Z","iopub.status.idle":"2023-02-12T07:08:49.723681Z","shell.execute_reply.started":"2023-02-12T06:59:14.937575Z","shell.execute_reply":"2023-02-12T07:08:49.722633Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Save\nmodel.save('model_finetuning.h5')","metadata":{"execution":{"iopub.status.busy":"2023-02-12T07:08:49.725485Z","iopub.execute_input":"2023-02-12T07:08:49.726195Z","iopub.status.idle":"2023-02-12T07:08:50.607956Z","shell.execute_reply.started":"2023-02-12T07:08:49.726154Z","shell.execute_reply":"2023-02-12T07:08:50.606966Z"},"trusted":true},"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":[]}]}