{"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\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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import random\nimport shutil\nimport zipfile\n\n\n\npath_cats_and_dogs = '/kaggle/input/dogs-vs-cats/train.zip'\nshutil.rmtree('/tmp')\n\nlocal_zip = path_cats_and_dogs\nzip_ref = zipfile.ZipFile(local_zip, 'r')\nzip_ref.extractall('/tmp/source')\nzip_ref.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.mkdir('/tmp/train')\nos.mkdir('/tmp/train/cats')\nos.mkdir('/tmp/train/dogs')\nos.mkdir('/tmp/valid')\nos.mkdir('/tmp/valid/cats')\nos.mkdir('/tmp/valid/dogs')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames=os.listdir('/tmp/source/train')\nsplit_by=int(len(filenames)*0.8)\ntrain_files=random.sample(filenames,split_by)                  \nval_files = list(set(filenames)-set(train_files)) \n# Dividing images for Training and Validation \n\nfor filename in train_files:\n    if (filename[0:3]=='dog'):\n        shutil.copyfile('/tmp/source/train/'+filename,'/tmp/train/dogs/'+filename)\n    else:\n        shutil.copyfile('/tmp/source/train/'+filename,'/tmp/train/cats/'+filename)\n        \n        \nfor filename in val_files:\n    if (filename[0:3]=='dog'):\n        shutil.copyfile('/tmp/source/train/'+filename,'/tmp/valid/dogs/'+filename)\n    else:\n        shutil.copyfile('/tmp/source/train/'+filename,'/tmp/valid/cats/'+filename)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(os.listdir('/tmp/train/dogs')))\nprint(len(os.listdir('/tmp/train/cats')))\n\nprint(len(os.listdir('/tmp/valid/dogs')))\nprint(len(os.listdir('/tmp/valid/cats')))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# **Visualising data**"},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_source='/tmp/source/train'\ntrain_dir='/tmp/train'\ntrain_cats='/tmp/train/cats'\ntrain_dogs='/tmp/train/dogs'\nvalid_dir='/tmp/valid'\nvalid_cats='/tmp/valid/cats'\nvalid_dogs='/tmp/valid/dogs'\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Displaying 4 Random cat images \n\nplt.figure(figsize=(16,16))\n\nfor i,cat in enumerate(np.random.randint(0,len(os.listdir(train_cats)),4)):\n    fig = plt.subplot(4,4,i+1)\n    fig.axis('off')\n    img=mpimg.imread(os.path.join(train_cats,os.listdir(train_cats)[cat]))\n    fig.imshow(img)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(16,16))\n\nfor i,dog in enumerate(np.random.randint(0,len(os.listdir(train_dogs)),4)):\n    fig = plt.subplot(4,4,i+1)\n    fig.axis('off')\n    img=mpimg.imread(os.path.join(train_dogs,os.listdir(train_dogs)[dog]))\n    fig.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Build Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\nfrom keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization\nfrom tensorflow.keras import optimizers","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model=Sequential()\n\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(128,128,3)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(512, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(loss='binary_crossentropy', optimizer=optimizers.RMSprop(learning_rate=0.001), metrics=['accuracy'])\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Augmentation\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rotation_range=15,\n    rescale=1./255,\n    shear_range=0.1,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    width_shift_range=0.1,\n    height_shift_range=0.1\n)\n\nval_datagen=ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(train_dir,\n                                                    batch_size=20,\n                                                    target_size=(128,128),\n                                                    class_mode='binary')\nval_generator = val_datagen.flow_from_directory(valid_dir,\n                                                    batch_size=20,\n                                                    target_size=(128,128),\n                                                    class_mode='binary')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img1=load_img(os.path.join(train_cats,os.listdir(train_cats)[4]))\n\nimg_data=img_to_array(img1)\n\nsamples=np.expand_dims(img_data,0)       \n#Loading a single image and applying the augmentation that is applied to the whole dataset \n                                        \n\ndata_gen=ImageDataGenerator(rotation_range=15,\n                            rescale=1./255,\n                            shear_range=0.1,\n                            zoom_range=0.2,\n                            horizontal_flip=True,\n                            width_shift_range=0.1,\n                            height_shift_range=0.1)\n \niterator=data_gen.flow(samples,batch_size=1)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(12, 12))\n\nfor i in range(0, 15):                  # Displaying the Augmentation Applied to every image.\n    plt.subplot(5, 3, i+1)\n    for X_batch in iterator:         \n        image = X_batch[0]\n        plt.imshow(image)\n        break\nplt.tight_layout()\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### CallBack \nTo avoid Overfitting Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ReduceLROnPlateau\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"earlystop = EarlyStopping(patience=10)\n\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=2, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)\n\ncallbacks2 = [earlystop, learning_rate_reduction]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size=20\nhistory = model.fit(\n    train_generator,\n    epochs=50,\n    validation_data=val_generator,\n    callbacks=callbacks2\n     )\n\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save_weights(\"model.h5\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualising the Loss and Accuracy"},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12))\nax1.plot(history.history['loss'], color='b', label=\"Training loss\")\nax1.plot(history.history['val_loss'], color='r', label=\"validation loss\")\nax1.set_xticks(np.arange(1, 50, 1))\nax1.set_yticks(np.arange(0, 1, 0.1))\n\nax2.plot(history.history['accuracy'], color='b', label=\"Training accuracy\")\nax2.plot(history.history['val_accuracy'], color='r',label=\"Validation accuracy\")\nax2.set_xticks(np.arange(1, 50, 1))\n\nlegend = plt.legend(loc='best', shadow=True)\nplt.tight_layout()\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"# Predict"},{"metadata":{"trusted":true},"cell_type":"code","source":"path_test = '/kaggle/input/dogs-vs-cats/test1.zip'\nlocal_zip = path_test\nzip_ref = zipfile.ZipFile(local_zip, 'r')\nzip_ref.extractall('/tmp/source')\nzip_ref.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred = []\nfor pic in os.listdir('/tmp/source/test1'):\n    path = '/tmp/source/test1/'+ pic\n    img=load_img(path, target_size=(128, 128))\n\n    x=img_to_array(img)\n    x=np.expand_dims(x, axis=0)\n    x=x/255\n\n    pred.append(int(model.predict_classes(x)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"id_ = [int(name[:-4]) for name in os.listdir('/tmp/source/test1')]\nlabel = pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\nsubmission = pd.DataFrame({'id':id_,\n             'label':pred})\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.sort_values('id',).to_csv('submission.csv',index=False)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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}