{"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        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":"2022-03-01T09:07:12.342674Z","iopub.execute_input":"2022-03-01T09:07:12.343091Z","iopub.status.idle":"2022-03-01T09:07:19.598927Z","shell.execute_reply.started":"2022-03-01T09:07:12.343058Z","shell.execute_reply":"2022-03-01T09:07:19.598175Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Importing the libraries**","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\nimport PIL\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers import Dense,Flatten\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator,load_img\nimport random\nfrom keras.models import Model\nfrom tensorflow.keras.applications import VGG16\nfrom sklearn.utils import shuffle","metadata":{"execution":{"iopub.status.busy":"2022-03-01T09:07:19.600552Z","iopub.execute_input":"2022-03-01T09:07:19.600834Z","iopub.status.idle":"2022-03-01T09:07:25.407562Z","shell.execute_reply.started":"2022-03-01T09:07:19.600799Z","shell.execute_reply":"2022-03-01T09:07:25.406828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = \"../input/dog-vs-cat-classification/train/train\"\ntest = \"../input/dog-vs-cat-classification/test/test\"","metadata":{"execution":{"iopub.status.busy":"2022-03-01T09:07:25.409554Z","iopub.execute_input":"2022-03-01T09:07:25.409773Z","iopub.status.idle":"2022-03-01T09:07:25.418327Z","shell.execute_reply.started":"2022-03-01T09:07:25.409748Z","shell.execute_reply":"2022-03-01T09:07:25.417663Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Image Data Auguementation**","metadata":{}},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale=1./255,\n                                  zoom_range=0.2,\n                                  height_shift_range=0.2,\n                                  width_shift_range=0.2,\n                                  horizontal_flip=True,\n                                  validation_split=0.2,                                   \n                                  )\n\ntest_datagen = ImageDataGenerator(rescale=1./255,\n                                 validation_split=0.2)","metadata":{"execution":{"iopub.status.busy":"2022-03-01T09:07:25.420961Z","iopub.execute_input":"2022-03-01T09:07:25.421232Z","iopub.status.idle":"2022-03-01T09:07:25.429725Z","shell.execute_reply.started":"2022-03-01T09:07:25.421205Z","shell.execute_reply":"2022-03-01T09:07:25.429072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"training_set =  train_datagen.flow_from_directory(directory = train,\n                                                 subset='training',\n                                                 class_mode='categorical',\n                                                 batch_size=32,\n                                                 color_mode=\"rgb\",\n                                                 seed=123,\n                                                 target_size=(224,224)\n                                                 )\n\ntest_set =  train_datagen.flow_from_directory(directory = train,\n                                              subset='validation',\n                                              class_mode='categorical',\n                                              batch_size=32,\n                                              color_mode=\"rgb\",\n                                              seed=123,\n                                              target_size=(224,224)\n                                                 )","metadata":{"execution":{"iopub.status.busy":"2022-03-01T09:07:25.432504Z","iopub.execute_input":"2022-03-01T09:07:25.433186Z","iopub.status.idle":"2022-03-01T09:07:30.064402Z","shell.execute_reply.started":"2022-03-01T09:07:25.433156Z","shell.execute_reply":"2022-03-01T09:07:30.063673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Transfer Learning**","metadata":{}},{"cell_type":"code","source":"vgg = VGG16(input_shape=[224,224,3],weights='imagenet',include_top=False)","metadata":{"execution":{"iopub.status.busy":"2022-03-01T09:07:30.065488Z","iopub.execute_input":"2022-03-01T09:07:30.066052Z","iopub.status.idle":"2022-03-01T09:07:33.287596Z","shell.execute_reply.started":"2022-03-01T09:07:30.066013Z","shell.execute_reply":"2022-03-01T09:07:33.286818Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for layer in vgg.layers:\n    layer.trainable = False","metadata":{"execution":{"iopub.status.busy":"2022-03-01T09:07:33.288959Z","iopub.execute_input":"2022-03-01T09:07:33.289209Z","iopub.status.idle":"2022-03-01T09:07:33.293662Z","shell.execute_reply.started":"2022-03-01T09:07:33.289175Z","shell.execute_reply":"2022-03-01T09:07:33.292958Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x = Flatten()(vgg.output)","metadata":{"execution":{"iopub.status.busy":"2022-03-01T09:07:33.294720Z","iopub.execute_input":"2022-03-01T09:07:33.295221Z","iopub.status.idle":"2022-03-01T09:07:33.309070Z","shell.execute_reply.started":"2022-03-01T09:07:33.295185Z","shell.execute_reply":"2022-03-01T09:07:33.308201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"vgg_output = Dense(2,activation='softmax')(x)","metadata":{"execution":{"iopub.status.busy":"2022-03-01T09:07:33.310417Z","iopub.execute_input":"2022-03-01T09:07:33.311055Z","iopub.status.idle":"2022-03-01T09:07:33.324040Z","shell.execute_reply.started":"2022-03-01T09:07:33.311016Z","shell.execute_reply":"2022-03-01T09:07:33.323143Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Model(inputs=vgg.input, outputs=vgg_output)","metadata":{"execution":{"iopub.status.busy":"2022-03-01T09:07:33.325328Z","iopub.execute_input":"2022-03-01T09:07:33.325800Z","iopub.status.idle":"2022-03-01T09:07:33.333780Z","shell.execute_reply.started":"2022-03-01T09:07:33.325765Z","shell.execute_reply":"2022-03-01T09:07:33.333043Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-03-01T09:07:33.335263Z","iopub.execute_input":"2022-03-01T09:07:33.335541Z","iopub.status.idle":"2022-03-01T09:07:33.351654Z","shell.execute_reply.started":"2022-03-01T09:07:33.335507Z","shell.execute_reply":"2022-03-01T09:07:33.350978Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optimizer=Adam(learning_rate = 0.0001)\n\nmodel.compile(optimizer=optimizer,\n              loss='binary_crossentropy',\n              metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-03-01T09:48:45.713237Z","iopub.execute_input":"2022-03-01T09:48:45.713507Z","iopub.status.idle":"2022-03-01T09:48:45.726237Z","shell.execute_reply.started":"2022-03-01T09:48:45.713476Z","shell.execute_reply":"2022-03-01T09:48:45.725422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Fitting & Training**","metadata":{}},{"cell_type":"code","source":"cnn = model.fit(\n  training_set,\n  validation_data=test_set,\n  epochs=10,\n  steps_per_epoch=len(training_set),\n  validation_steps=len(test_set)\n)","metadata":{"execution":{"iopub.status.busy":"2022-03-01T09:48:53.291126Z","iopub.execute_input":"2022-03-01T09:48:53.291397Z","iopub.status.idle":"2022-03-01T10:44:28.479525Z","shell.execute_reply.started":"2022-03-01T09:48:53.291367Z","shell.execute_reply":"2022-03-01T10:44:28.478764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig , ax = plt.subplots(1,2)\ntrain_acc = cnn.history['accuracy']\ntrain_loss = cnn.history['loss']\nfig.set_size_inches(12,4)\n\nax[0].plot(cnn.history['accuracy'])\nax[0].plot(cnn.history['val_accuracy'])\nax[0].set_title('Training Accuracy vs Validation Accuracy')\nax[0].set_ylabel('Accuracy')\nax[0].set_xlabel('Epoch')\nax[0].legend(['Train', 'Validation'], loc='upper left')\n\nax[1].plot(cnn.history['loss'])\nax[1].plot(cnn.history['val_loss'])\nax[1].set_title('Training Loss vs Validation Loss')\nax[1].set_ylabel('Loss')\nax[1].set_xlabel('Epoch')\nax[1].legend(['Train', 'Validation'], loc='upper left')\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-03-01T10:46:00.343604Z","iopub.execute_input":"2022-03-01T10:46:00.343902Z","iopub.status.idle":"2022-03-01T10:46:00.644176Z","shell.execute_reply.started":"2022-03-01T10:46:00.343869Z","shell.execute_reply":"2022-03-01T10:46:00.643490Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Prediction**","metadata":{}},{"cell_type":"code","source":"import os\ntest_filenames = os.listdir(\"../input/dog-vs-cat-classification/test/test\")\ntest_df = pd.DataFrame({\n    'id': test_filenames\n})\nnb_samples = test_df.shape[0]\nnb_samples","metadata":{"execution":{"iopub.status.busy":"2022-03-01T10:44:57.093393Z","iopub.execute_input":"2022-03-01T10:44:57.093820Z","iopub.status.idle":"2022-03-01T10:44:57.111012Z","shell.execute_reply.started":"2022-03-01T10:44:57.093783Z","shell.execute_reply":"2022-03-01T10:44:57.110379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator, load_img\ntest_gen = ImageDataGenerator()\ntest_generator = test_gen.flow_from_dataframe(\n    test_df, \n    \"../input/dog-vs-cat-classification/test/test\", \n    x_col='id',\n    y_col=None,\n    class_mode=None,\n    target_size=(224,224),\n    batch_size=32,\n    shuffle=False\n   )","metadata":{"execution":{"iopub.status.busy":"2022-03-01T10:44:57.112797Z","iopub.execute_input":"2022-03-01T10:44:57.113107Z","iopub.status.idle":"2022-03-01T10:45:00.376831Z","shell.execute_reply.started":"2022-03-01T10:44:57.113071Z","shell.execute_reply":"2022-03-01T10:45:00.376071Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predict = model.predict(test_generator)\ntest_df['labels'] = np.argmax(predict, axis=-1)","metadata":{"execution":{"iopub.status.busy":"2022-03-01T10:45:00.378175Z","iopub.execute_input":"2022-03-01T10:45:00.378682Z","iopub.status.idle":"2022-03-01T10:46:00.299324Z","shell.execute_reply.started":"2022-03-01T10:45:00.378618Z","shell.execute_reply":"2022-03-01T10:46:00.297804Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df","metadata":{"execution":{"iopub.status.busy":"2022-03-01T10:46:00.303298Z","iopub.execute_input":"2022-03-01T10:46:00.303501Z","iopub.status.idle":"2022-03-01T10:46:00.319010Z","shell.execute_reply.started":"2022-03-01T10:46:00.303476Z","shell.execute_reply":"2022-03-01T10:46:00.318304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.set_index('id')\ntest_df.to_csv('submission.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2022-03-01T10:46:46.420589Z","iopub.execute_input":"2022-03-01T10:46:46.421272Z","iopub.status.idle":"2022-03-01T10:46:46.441993Z","shell.execute_reply.started":"2022-03-01T10:46:46.421238Z","shell.execute_reply":"2022-03-01T10:46:46.441363Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}