{"cells":[{"metadata":{"id":"wsbn3Rwh3svm"},"cell_type":"markdown","source":"## Import Library","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"id":"1J3xsK_w3svs"},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport shutil                     # File_Operation Library\nimport cv2\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import GlobalMaxPooling2D, Dense, Flatten, GlobalAveragePooling2D, Dropout, Input, Concatenate, BatchNormalization\n\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3","execution_count":null,"outputs":[]},{"metadata":{"id":"XR_PZHM13sv1"},"cell_type":"markdown","source":"## Extract Dataset from ZIP","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"shutil.unpack_archive('../input/dogs-vs-cats/train.zip', '/kaggle/working/')\nshutil.unpack_archive('../input/dogs-vs-cats/test1.zip', '/kaggle/working/')","execution_count":null,"outputs":[]},{"metadata":{"id":"3mCCtbbN3sv_"},"cell_type":"markdown","source":"## Reference Directory","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true,"id":"gyqgu0kA3swA"},"cell_type":"code","source":"train_dir = '/kaggle/working/train/'\ntest_dir = '/kaggle/working/test1/'","execution_count":null,"outputs":[]},{"metadata":{"id":"rKZ1l_cw3swH"},"cell_type":"markdown","source":"## Label Extraction","execution_count":null},{"metadata":{"trusted":true,"id":"EY4AsHKx3swI","outputId":"ed5950d2-004e-4ae4-ebd6-d40e4f233be2"},"cell_type":"code","source":"train_df = []\nimg_list = []\nl_list = []\n\nfor img in os.listdir(train_dir):\n    if img.split('.')[-1]=='jpg':\n        img_list.append(train_dir+img)\n        l_list.append(img.split('.')[0])\n\ntrain_df = pd.DataFrame(train_df)\ntrain_df['image'] = img_list\ntrain_df['label'] = l_list\n\nprint(train_df.head())","execution_count":null,"outputs":[]},{"metadata":{"id":"xSM78v0m3swT"},"cell_type":"markdown","source":"## Data Generators","execution_count":null},{"metadata":{"trusted":true,"id":"fKK80Ku53swU","outputId":"4569da31-c316-4722-9c7b-662f05d1722e"},"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale = 1./255, \n                                   horizontal_flip = True, \n                                   rotation_range = 45, \n                                   shear_range = 19,\n                                   zoom_range = 0.2,\n                                   validation_split = 0.2)\n\ntrain_generator = train_datagen.flow_from_dataframe(train_df,\n                                                    x_col='image',\n                                                    y_col='label',\n                                                    target_size = (180, 180), \n                                                    class_mode = 'binary',\n                                                    batch_size = 280,\n                                                    shuffle = True,\n                                                    subset = 'training')\n\nval_generator = train_datagen.flow_from_dataframe(train_df,\n                                                  x_col='image',\n                                                  y_col='label',\n                                                  target_size = (180, 180),\n                                                  class_mode = 'binary',\n                                                  batch_size = 280,\n                                                  shuffle = True,\n                                                  subset = 'validation')","execution_count":null,"outputs":[]},{"metadata":{"id":"bBh4ZHWS3swY"},"cell_type":"markdown","source":"## CNN_Model","execution_count":null},{"metadata":{"trusted":true,"id":"mhOm2F493swa"},"cell_type":"code","source":"inputs = Input((180, 180, 3))\npretrained_model= InceptionV3(include_top= False)\nx = pretrained_model(inputs)\noutput1 = GlobalMaxPooling2D()(x)\noutput2 = GlobalAveragePooling2D()(x)\noutput3 = Flatten()(x)\n\noutputs = Concatenate(axis=-1)([output1, output2, output3])\noutputs = Dropout(0.5)(outputs)\noutputs = BatchNormalization()(outputs)\noutput = Dense(1, activation= 'sigmoid')(outputs)\n\nmodel = Model(inputs, output)","execution_count":null,"outputs":[]},{"metadata":{"id":"VZ07u1uc3swi"},"cell_type":"markdown","source":"## Callback Functions","execution_count":null},{"metadata":{"trusted":true,"id":"E10RHrKO3swj"},"cell_type":"code","source":"from keras.callbacks import ModelCheckpoint, EarlyStopping, Callback\n\n\n# autosave best Model\nbest_model = ModelCheckpoint(\"model\", monitor='val_accuracy', mode='max',verbose=1, save_best_only=True)\n\nearlystop = EarlyStopping(monitor = 'val_accuracy',\n                          patience = 5,\n                          mode = 'auto',\n                          verbose = 1,\n                          restore_best_weights = True)\n\nacc_thresh = 0.998\n\nclass myCallback(Callback): \n    def on_epoch_end(self, epoch, logs={}): \n        if(logs.get('accuracy') > acc_thresh):   \n          print(\"\\nWe have reached %2.2f%% accuracy, so we will stopping training.\" %(acc_thresh*100))   \n          self.model.stop_training = True\n\ncallbacks = [myCallback(), best_model, earlystop]","execution_count":null,"outputs":[]},{"metadata":{"id":"r8FxkHNG3swp"},"cell_type":"markdown","source":"## Compiling and Training...","execution_count":null},{"metadata":{"trusted":true,"id":"QyR2Oeav3swq","outputId":"c3d9268f-b44e-44a3-9283-744bafee001f"},"cell_type":"code","source":"model.compile(optimizer='RMSprop', loss= 'binary_crossentropy', metrics= ['accuracy'])\nhistory = model.fit_generator(train_generator,\n                              epochs = 100,\n                              steps_per_epoch = len(train_generator),\n                              validation_data = val_generator,\n                              validation_steps = len(val_generator),\n                              callbacks = callbacks,\n                              verbose= 1)","execution_count":null,"outputs":[]},{"metadata":{"id":"F52maKZo3swx"},"cell_type":"markdown","source":"## Plotting Accuracy","execution_count":null},{"metadata":{"trusted":true,"id":"Pt0FzrD73swy","outputId":"5b45b026-6586-43fb-a2de-a4795b1ad55a"},"cell_type":"code","source":"plt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='best')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"id":"J9ss_e9N3sw2"},"cell_type":"markdown","source":"## Prediction","execution_count":null},{"metadata":{"id":"9P8iMEzI9HIW","trusted":true},"cell_type":"code","source":"def predict(path):\n    img = cv2.imread(str(path))\n    img = cv2.resize(img, (180,180))\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    img = img.astype(np.float32)/255.\n    img = np.reshape(img,(1,180,180,3))\n    return model.predict(img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"id":"Fl40mWDP3sw3","outputId":"2af161a1-4903-4713-bd3f-5f755c554fb3"},"cell_type":"code","source":"print(train_generator.class_indices)    # Mapping Dictionary","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"id":"zHMgiwVg3sxA"},"cell_type":"code","source":"test_df = []\ntest_list = []\n\nfor i in os.listdir(test_dir):\n    test_list.append(test_dir +i)\n    test_df.append(i.split('.')[0])\n\ntarget=[]\nfor path in test_list:\n    prediction = predict(path)\n    target.append(prediction[0][0])\n    \ntest_df = pd.DataFrame(test_df)\ntest_df.columns = ['id']\ntest_df['label'] = target\n\ntest_df.sort_values(by=['id'], inplace=True)\ntest_df.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"id":"znxqsXno3sxE"},"cell_type":"markdown","source":"## Evaluation","execution_count":null},{"metadata":{"trusted":true,"id":"0ZxXkTif3sxF","outputId":"752e06fc-c0ff-43bb-dcc2-beab3b220f3f"},"cell_type":"code","source":"img_num = 1234   # change me!\n\npath = test_list[img_num]\nimg=cv2.imread(str(path))\nplt.imshow(img)\n\nprediction = predict(path)\n\nif prediction < 0.5:\n    print(\"It's a Cat!\")\nelse:\n    print(\"It's a Dog!\")","execution_count":null,"outputs":[]},{"metadata":{"id":"iOxr17mz3sxN"},"cell_type":"markdown","source":"## Thank You!!","execution_count":null}],"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":4,"nbformat_minor":4}