{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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 in \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 \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os,shutil\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"base_dir = \"../input\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dir = \"../input/train/train\"\ntest_dir = \"../input/test1/test1\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_imagenames = os.listdir(\"../input/train/train\")\nimage_name = []\nimage_paths = []\nfor imagename in train_imagenames:\n    image = imagename.split('.')[0]\n    image_path = os.path.join(train_dir, imagename)\n    image_paths.append(image_path)\n    image_name.append(image)\n    \n    \n\n\nimage_df = pd.DataFrame()\n\nimage_df[\"image_path\"] = image_paths\nimage_df[\"image_name\"] = image_name\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_df[\"image_name\"].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import layers\nfrom keras import models\nimport tensorflow as tf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.models.Sequential([\n    \n    tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(150, 150, 3)),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    \n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dropout(0.5),\n    tf.keras.layers.Dense(512, activation='relu'),\n    tf.keras.layers.Dense(1, activation='sigmoid')\n])\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import optimizers\nfrom keras.optimizers import SGD\nfrom tensorflow.keras.optimizers import RMSprop\nfrom sklearn.preprocessing import LabelEncoder\n\nmodel.compile(loss = \"binary_crossentropy\", optimizer = RMSprop(lr=1e-4), metrics = [\"acc\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain, validation = train_test_split(image_df,test_size=0.2, random_state=42) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\ntrain_datagen = ImageDataGenerator(rescale = 1./255, rotation_range = 40, width_shift_range = 0.2,\n                                   height_shift_range = 0.2, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True)\nvalidation_datagen = ImageDataGenerator(rescale = 1./255)\n\ntrain_generator = train_datagen.flow_from_dataframe(train, x_col = \"image_path\", y_col = \"image_name\", target_size = (150, 150), batch_size = 128, class_mode = \"binary\")\nvalidation_generator = validation_datagen.flow_from_dataframe(validation, x_col = \"image_path\", y_col = \"image_name\", target_size = (150, 150), batch_size = 128, class_mode = \"binary\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#class myCallback(tf.keras.callbacks.Callback):\n  #def on_epoch_end(self, epoch, logs={}):\n    #if(logs.get('acc')>0.9):\n    #        print(\"\\nReached 60% accuracy so cancelling training!\")\n    #self.model.stop_training = True\n#callbacks = myCallback()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(train_generator,\n                             steps_per_epoch = 80, epochs = 40, validation_data = validation_generator, validation_steps = 200)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nacc = history.history[\"acc\"]\nval_acc = history.history[\"val_acc\"]\nloss = history.history[\"loss\"]\nval_loss = history.history[\"val_loss\"]\n\nepochs = range(1, len(acc) + 1)\n\nplt.plot(epochs, acc, \"bo\", label = \"Training acc\")\nplt.plot(epochs, val_acc, \"b\", label = \"Validation acc\")\nplt.title(\"Training and Validation accuracy\")\nplt.legend()\nplt.figure()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(epochs, loss, \"bo\", label = \"Training loss\")\nplt.plot(epochs, val_loss, \"b\", label = \"Validation loss\")\nplt.title(\"Training and Validation loss\")\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale = 1./255)\ntest_dir = \"../input/test1\"\n\n#test_generator = test_datagen.flow_from_directory(test_dir, target_size =(150, 150), batch_size = 80, class_mode = None, shuffle = False)\n\ntest_generator = test_datagen.flow_from_directory(\n    directory= test_dir,\n    target_size=(150, 150),\n    color_mode=\"rgb\",\n    batch_size=100,\n    class_mode=None,\n    shuffle=False\n)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = model.predict_generator(test_generator, steps = 125)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Final_df =[1 if value>0.5 else 0 for value in results]\n\nsubmission = pd.DataFrame({\"label\": Final_df})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}