{"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        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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-08-18T03:22:21.022286Z","iopub.execute_input":"2021-08-18T03:22:21.022699Z","iopub.status.idle":"2021-08-18T03:22:21.037169Z","shell.execute_reply.started":"2021-08-18T03:22:21.022611Z","shell.execute_reply":"2021-08-18T03:22:21.036392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Required Libraries","metadata":{}},{"cell_type":"code","source":"import os\nimport zipfile\nimport tensorflow as tf\nimport random\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.optimizers import RMSprop\nfrom shutil import copyfile","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:25:09.543918Z","iopub.execute_input":"2021-08-18T03:25:09.544405Z","iopub.status.idle":"2021-08-18T03:25:16.135639Z","shell.execute_reply.started":"2021-08-18T03:25:09.544361Z","shell.execute_reply":"2021-08-18T03:25:16.134838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Dataset Folder\n## Folder creation for Easiness","metadata":{}},{"cell_type":"code","source":"local_zip1 = '/kaggle/input/dogs-vs-cats/'\ndirs = [\"train.zip\", \"test1.zip\"]\nfor directory in dirs:\n    local_zip = os.path.join(local_zip1, directory)\n    zip_ref = zipfile.ZipFile(local_zip, 'r')\n    zip_ref.extractall('/kaggle/working/dogs-vs-cats/')\n    zip_ref.close()","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:26:10.530485Z","iopub.execute_input":"2021-08-18T03:26:10.530988Z","iopub.status.idle":"2021-08-18T03:26:28.584988Z","shell.execute_reply.started":"2021-08-18T03:26:10.530939Z","shell.execute_reply":"2021-08-18T03:26:28.584112Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for directory in [\"train\", \"test1\"]:\n    path = os.path.join(\"/kaggle/working/dogs-vs-cats/\", directory)\n    for dirname, _, filenames in os.walk(path):\n        for filename in filenames:\n            print(os.path.join(dirname, filename))\n            break","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:26:45.07596Z","iopub.execute_input":"2021-08-18T03:26:45.07661Z","iopub.status.idle":"2021-08-18T03:26:45.142748Z","shell.execute_reply.started":"2021-08-18T03:26:45.076567Z","shell.execute_reply":"2021-08-18T03:26:45.141467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(os.listdir('/kaggle/working/dogs-vs-cats/train')))\nprint(len(os.listdir('/kaggle/working/dogs-vs-cats/test1')))","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:26:59.723205Z","iopub.execute_input":"2021-08-18T03:26:59.723775Z","iopub.status.idle":"2021-08-18T03:26:59.753582Z","shell.execute_reply.started":"2021-08-18T03:26:59.723741Z","shell.execute_reply":"2021-08-18T03:26:59.752492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    os.mkdir('/kaggle/working/dogs-vs-cats/train/cat')\n    os.mkdir('/kaggle/working/dogs-vs-cats/train/dog')\nexcept OSError:\n    pass","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:27:09.515898Z","iopub.execute_input":"2021-08-18T03:27:09.516537Z","iopub.status.idle":"2021-08-18T03:27:09.521224Z","shell.execute_reply.started":"2021-08-18T03:27:09.516495Z","shell.execute_reply":"2021-08-18T03:27:09.520064Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CATDIR = '/kaggle/working/dogs-vs-cats/train/cat'\nDOGDIR = '/kaggle/working/dogs-vs-cats/train/dog'","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:27:25.125747Z","iopub.execute_input":"2021-08-18T03:27:25.126442Z","iopub.status.idle":"2021-08-18T03:27:25.129885Z","shell.execute_reply.started":"2021-08-18T03:27:25.126398Z","shell.execute_reply":"2021-08-18T03:27:25.129039Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for file in os.listdir(\"/kaggle/working/dogs-vs-cats/train\"):\n    if \"cat\" in file:\n        copyfile((os.path.join(dirname, filename)),(os.path.join(CATDIR, file)))\n    elif \"dog\" in file:\n        copyfile((os.path.join(dirname, filename)),(os.path.join(DOGDIR, file)))","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:27:37.701285Z","iopub.execute_input":"2021-08-18T03:27:37.701946Z","iopub.status.idle":"2021-08-18T03:27:40.853456Z","shell.execute_reply.started":"2021-08-18T03:27:37.701892Z","shell.execute_reply":"2021-08-18T03:27:40.852597Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(os.listdir(CATDIR)))\nprint(len(os.listdir(DOGDIR)))","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:28:14.033622Z","iopub.execute_input":"2021-08-18T03:28:14.034133Z","iopub.status.idle":"2021-08-18T03:28:14.055459Z","shell.execute_reply.started":"2021-08-18T03:28:14.03409Z","shell.execute_reply":"2021-08-18T03:28:14.054501Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train, Validation and Tet","metadata":{}},{"cell_type":"code","source":"DIRS = ['/kaggle/working/cats-v-dogs',\n        '/kaggle/working/cats-v-dogs/training',\n        '/kaggle/working/cats-v-dogs/validation',\n        '/kaggle/working/cats-v-dogs/training/cats',\n        '/kaggle/working/cats-v-dogs/training/dogs',\n        '/kaggle/working/cats-v-dogs/validation/cats',\n        '/kaggle/working/cats-v-dogs/validation/dogs']","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:28:18.95527Z","iopub.execute_input":"2021-08-18T03:28:18.95577Z","iopub.status.idle":"2021-08-18T03:28:18.960282Z","shell.execute_reply.started":"2021-08-18T03:28:18.955722Z","shell.execute_reply":"2021-08-18T03:28:18.95951Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for directory in DIRS:\n    try:\n        os.mkdir(directory)\n    except OSError:\n        pass","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:28:26.548873Z","iopub.execute_input":"2021-08-18T03:28:26.549715Z","iopub.status.idle":"2021-08-18T03:28:26.555476Z","shell.execute_reply.started":"2021-08-18T03:28:26.549645Z","shell.execute_reply":"2021-08-18T03:28:26.554597Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def split_data(SOURCE, TRAINING, TESTING, SPLIT_SIZE):\n    files = []\n    \n    for file_name in os.listdir(SOURCE):\n        file_path = os.path.join(SOURCE, file_name)\n        \n        if os.path.getsize(file_path):\n            files.append(file_name)\n    \n    length_of_files = len(files)\n    split_point = int(length_of_files * SPLIT_SIZE)\n    \n    shuffled = random.sample(files, length_of_files)\n    \n    train_set = shuffled[:split_point]\n    test_set = shuffled[split_point:]\n    \n    for file_name in train_set:\n        copyfile(SOURCE + file_name, TRAINING + file_name)\n        \n    for file_name in test_set:\n        copyfile(SOURCE + file_name, TESTING + file_name)","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:28:43.284274Z","iopub.execute_input":"2021-08-18T03:28:43.284956Z","iopub.status.idle":"2021-08-18T03:28:43.293489Z","shell.execute_reply.started":"2021-08-18T03:28:43.284882Z","shell.execute_reply":"2021-08-18T03:28:43.292523Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CAT_SOURCE_DIR = \"/kaggle/working/dogs-vs-cats/train/cat/\"\nTRAINING_CATS_DIR = \"/kaggle/working/cats-v-dogs/training/cats/\"\nTESTING_CATS_DIR = \"/kaggle/working/cats-v-dogs/validation/cats/\"\nDOG_SOURCE_DIR = \"/kaggle/working/dogs-vs-cats/train/dog/\"\nTRAINING_DOGS_DIR = \"/kaggle/working/cats-v-dogs/training/dogs/\"\nTESTING_DOGS_DIR = \"/kaggle/working/cats-v-dogs/validation/dogs/\"\n\nsplit_size = .9\nsplit_data(CAT_SOURCE_DIR, TRAINING_CATS_DIR, TESTING_CATS_DIR, split_size)\nsplit_data(DOG_SOURCE_DIR, TRAINING_DOGS_DIR, TESTING_DOGS_DIR, split_size)","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:28:55.595477Z","iopub.execute_input":"2021-08-18T03:28:55.596144Z","iopub.status.idle":"2021-08-18T03:28:59.063707Z","shell.execute_reply.started":"2021-08-18T03:28:55.596089Z","shell.execute_reply":"2021-08-18T03:28:59.062828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(os.listdir('/kaggle/working/cats-v-dogs/training/cats/')))\nprint(len(os.listdir('/kaggle/working/cats-v-dogs/training/dogs/')))\nprint(len(os.listdir('/kaggle/working/cats-v-dogs/validation/cats/')))\nprint(len(os.listdir('/kaggle/working/cats-v-dogs/validation/dogs/')))","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:29:28.244279Z","iopub.execute_input":"2021-08-18T03:29:28.246151Z","iopub.status.idle":"2021-08-18T03:29:28.268967Z","shell.execute_reply.started":"2021-08-18T03:29:28.246092Z","shell.execute_reply":"2021-08-18T03:29:28.268208Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Modelling","metadata":{}},{"cell_type":"code","source":"model  = tf.keras.Sequential([\n    tf.keras.layers.Conv2D(16, (3,3), activation = \"relu\", input_shape =(150, 150, 3)),\n    tf.keras.layers.MaxPool2D(2,2),\n    tf.keras.layers.Conv2D(32, (3,3), activation = \"relu\"),\n    tf.keras.layers.MaxPool2D(2,2),\n    tf.keras.layers.Conv2D(64, (3,3), activation = \"relu\"),\n    tf.keras.layers.MaxPool2D(2,2),\n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(512, activation = \"relu\"),\n    tf.keras.layers.Dense(1, activation = \"sigmoid\")\n])","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:29:42.95245Z","iopub.execute_input":"2021-08-18T03:29:42.953162Z","iopub.status.idle":"2021-08-18T03:29:43.469926Z","shell.execute_reply.started":"2021-08-18T03:29:42.95312Z","shell.execute_reply":"2021-08-18T03:29:43.468809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model Compiling","metadata":{}},{"cell_type":"code","source":"model.compile(\n    optimizer=RMSprop(learning_rate=0.001),\n    loss='binary_crossentropy',\n    metrics=['accuracy']\n)","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:29:52.186567Z","iopub.execute_input":"2021-08-18T03:29:52.187038Z","iopub.status.idle":"2021-08-18T03:29:52.206886Z","shell.execute_reply.started":"2021-08-18T03:29:52.186995Z","shell.execute_reply":"2021-08-18T03:29:52.205469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TRAINING_DIR = '/kaggle/working/cats-v-dogs/training/'\ntrain_datagen = ImageDataGenerator( rescale = 1.0/255. )\n\ntrain_generator = train_datagen.flow_from_directory(TRAINING_DIR,\n                                                    batch_size=20,\n                                                    class_mode='binary',\n                                                    target_size=(150, 150))\n\nVALIDATION_DIR = '/kaggle/working/cats-v-dogs/validation/'\nvalidation_datagen = ImageDataGenerator( rescale = 1.0/255. )\n\nvalidation_generator = validation_datagen.flow_from_directory(VALIDATION_DIR,\n                                                         batch_size=20,\n                                                         class_mode  = 'binary',\n                                                         target_size = (150, 150))","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:30:03.054209Z","iopub.execute_input":"2021-08-18T03:30:03.05486Z","iopub.status.idle":"2021-08-18T03:30:03.840639Z","shell.execute_reply.started":"2021-08-18T03:30:03.054799Z","shell.execute_reply":"2021-08-18T03:30:03.839473Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model Building","metadata":{}},{"cell_type":"code","source":"history = model.fit(train_generator,\n                    epochs=5,\n                    verbose=1,\n                    validation_data=validation_generator)","metadata":{"execution":{"iopub.status.busy":"2021-08-18T03:30:15.9961Z","iopub.execute_input":"2021-08-18T03:30:15.996556Z","iopub.status.idle":"2021-08-18T04:00:33.983222Z","shell.execute_reply.started":"2021-08-18T03:30:15.99652Z","shell.execute_reply":"2021-08-18T04:00:33.982203Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prediction","metadata":{}},{"cell_type":"code","source":"%matplotlib inline\n\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing import image\n\ncount = 1\nfor filename in os.listdir('/kaggle/working/dogs-vs-cats/test1'):\n    #Get the path of the images in the test directory\n    print(os.path.join('/kaggle/working/dogs-vs-cats/test1', filename))\n    \n    path = os.path.join('/kaggle/working/dogs-vs-cats/test1', filename)\n    img = image.load_img(path, target_size=(150, 150))\n    x = image.img_to_array(img)\n    x = np.expand_dims(x, axis=0)\n    \n    img = mpimg.imread(path)\n    plt.imshow(img)\n    plt.show()\n    \n    images = np.vstack([x])\n    classes = model.predict(images, batch_size=10)\n    if classes[0]>0.5:\n        print(filename + \" is a dog\")\n    else:\n        print(filename + \" is a cat\")\n    print(\"--\"*30)\n    count -= 1\n    if(count < 0):\n        break","metadata":{"execution":{"iopub.status.busy":"2021-08-18T04:01:56.38453Z","iopub.execute_input":"2021-08-18T04:01:56.384872Z","iopub.status.idle":"2021-08-18T04:01:57.194474Z","shell.execute_reply.started":"2021-08-18T04:01:56.384843Z","shell.execute_reply":"2021-08-18T04:01:57.193416Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}