{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import tensorflow as tf\nimport zipfile\nimport os\nimport shutil","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def extract_files(source_path, target_path):\n    zip_ref = zipfile.ZipFile(source_path,'r')\n    zip_ref.extractall(target_path)\n    zip_ref.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"extract_files('/kaggle/input/dogs-vs-cats/test1.zip','/kaggle/working/')\nextract_files('/kaggle/input/dogs-vs-cats/train.zip','/kaggle/working/')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(os.listdir('/kaggle/working/'))\nprint(os.listdir('/kaggle/working/train/')[:5])\nprint(os.listdir('/kaggle/working/test1/')[:5])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#creating directories for cat and dog \nos.makedirs('/kaggle/working/training/')\nos.makedirs('/kaggle/working/training/dog/')\nos.makedirs('/kaggle/working/training/cat/')\n\nos.listdir('/kaggle/working/training/')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Separating dogs and cats images in separate folder for training set\ntarget_path = '/kaggle/working/training/'\n\ndef copy_file(path,file_name,target):\n    source_path = os.path.join(path,file_name)\n    destination_path = os.path.join(target_path,target)\n    shutil.copy(source_path,destination_path) \n\ndef segregate_images(path):\n    for img in os.listdir(path):\n        category = img.split(\".\")[0]\n        if category == 'cat':\n            copy_file(path,img,'cat')\n        else:\n            copy_file(path,img,'dog')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"segregate_images('/kaggle/working/train/')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Total no of cat images :\", len(os.listdir('/kaggle/working/training/cat')))\nprint(\"Total no of dog images :\", len(os.listdir('/kaggle/working/training/dog')))\n\ntrain_cat_names= os.listdir('/kaggle/working/training/cat')\ntrain_dog_names = os.listdir('/kaggle/working/training/dog')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%matplotlib inline\n\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\n\n# Parameters for our graph; we'll output images in a 4x4 configuration\nnrows = 4\nncols = 4\n\npic_index = 0 # Index for iterating over images","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.gcf()\nfig.set_size_inches(nrows*4,ncols*4)\n\npic_index+=8\n\ncat_pic = [os.path.join('/kaggle/working/training/cat/',fname) \n          for fname in train_cat_names[pic_index-8:pic_index]]\n\ndog_pic = [os.path.join('/kaggle/working/training/dog/',fname)\n          for fname in train_dog_names[pic_index-8:pic_index]]\n\nfor i, img_path in enumerate(cat_pic+dog_pic):\n    \n    # Set up subplot; subplot indices start at 1\n    sp = plt.subplot(nrows, ncols, i + 1)\n    sp.axis('Off') # Don't show axes (or gridlines)\n\n    img = mpimg.imread(img_path)\n    plt.imshow(img)\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nmodel = tf.keras.Sequential([\n    \n    #Conv layer:1\n    tf.keras.layers.Conv2D(128, (3,3), activation='relu', input_shape=(150,150,3)),\n    tf.keras.layers.MaxPooling2D(2,2),\n    #Conv layer:2\n    tf.keras.layers.Conv2D(64,(3,3),activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    #Conv layer 3\n    tf.keras.layers.Conv2D(64,(3,3),activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    #Conv layer 4\n    tf.keras.layers.Conv2D(32,(3,3),activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    #Conv layer 5\n    tf.keras.layers.Conv2D(16,(3,3),activation='relu'),\n    tf.keras.layers.MaxPool2D(2,2),\n    #Flatten\n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(512,activation='relu'),\n    tf.keras.layers.Dense(1,activation='sigmoid')\n    \n])\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Compile the model with loss='binary_crossentropy' and optimizer=RMSProp\nmodel.compile(loss='binary_crossentropy', \n              optimizer=tf.keras.optimizers.RMSprop(lr=1e-8),\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ntrain_gen = ImageDataGenerator(rescale=1.0/255.0)\n\ntrain_data_generator = train_gen.flow_from_directory(\n    '/kaggle/working/training/',\n    batch_size=250,\n    target_size=(150,150),\n    class_mode='binary'\n)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"mycallback = tf.keras.callbacks.EarlyStopping(monitor='loss',patience=10)\nhistory = model.fit(train_data_generator, epochs=5, \n                    steps_per_epoch=5, \n                   verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save('cats_vs_dogs.h5')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing import image\nimport numpy as np\n\npath = '/kaggle/working/test1'\noutput = []\nfor file in os.listdir(path):\n    k = {}\n    test_path = os.path.join(path,file)\n    k['file_path'] = test_path\n    img = image.load_img(test_path,target_size=(150,150))\n    x = image.img_to_array(img)\n    x = np.expand_dims(x,axis=0)\n    images = np.vstack([x])\n    \n    classes = model.predict(images,batch_size=10)\n    print(classes[0])\n    if classes[0]> 0 :\n        k['prediction']='dog'\n    else:\n        k['prediction']='cat'\n    output.append(k)\n\nprint(k)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\n\nout_data = pd.DataFrame(output)\nout_data.head()\n\nout_data.to_csv('/kaggle/working/predictions.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}