{"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":"2022-07-25T22:32:35.134994Z","iopub.execute_input":"2022-07-25T22:32:35.135349Z","iopub.status.idle":"2022-07-25T22:32:35.144466Z","shell.execute_reply.started":"2022-07-25T22:32:35.135318Z","shell.execute_reply":"2022-07-25T22:32:35.143399Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\n\n#unzip test1.zip\ntrain_zip = zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\", \"r\")\ntrain_zip.extractall()\n#unzip test2.zip\ntest_zip = zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\", \"r\")\ntest_zip.extractall()\n","metadata":{"execution":{"iopub.status.busy":"2022-07-25T22:32:42.905049Z","iopub.execute_input":"2022-07-25T22:32:42.905425Z","iopub.status.idle":"2022-07-25T22:32:57.752791Z","shell.execute_reply.started":"2022-07-25T22:32:42.905380Z","shell.execute_reply":"2022-07-25T22:32:57.751010Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = os.path.join(\"/kaggle/working/train/\")\ntest_data = os.path.join(\"/kaggle/working/test1/\")","metadata":{"execution":{"iopub.status.busy":"2022-07-25T22:32:57.756059Z","iopub.execute_input":"2022-07-25T22:32:57.757085Z","iopub.status.idle":"2022-07-25T22:32:57.768717Z","shell.execute_reply.started":"2022-07-25T22:32:57.757046Z","shell.execute_reply":"2022-07-25T22:32:57.766456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir dataset/\n!mkdir dataset/cats\n!mkdir dataset/dogs","metadata":{"execution":{"iopub.status.busy":"2022-07-25T22:32:57.770791Z","iopub.execute_input":"2022-07-25T22:32:57.771967Z","iopub.status.idle":"2022-07-25T22:33:00.017723Z","shell.execute_reply.started":"2022-07-25T22:32:57.771916Z","shell.execute_reply":"2022-07-25T22:33:00.016481Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\nimport glob\n\nfor img in os.listdir(train_data):\n    if img[:3] == 'cat':\n        shutil.copy(\"/kaggle/working/train/\"+str(img), \"/kaggle/working/dataset/cats/\")\n    if img[:3] == 'dog':\n        shutil.copy(\"/kaggle/working/train/\"+str(img), \"/kaggle/working/dataset/dogs/\")\n        ","metadata":{"execution":{"iopub.status.busy":"2022-07-25T22:33:00.020530Z","iopub.execute_input":"2022-07-25T22:33:00.021727Z","iopub.status.idle":"2022-07-25T22:33:04.778460Z","shell.execute_reply.started":"2022-07-25T22:33:00.021684Z","shell.execute_reply":"2022-07-25T22:33:04.777465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dir = os.path.join(\"/kaggle/working/dataset/\")\nvalidation_dir = os.path.join(\"/kaggle/working/val_dataset/\")\n\ntrain_cats_dir = os.path.join(\"/kaggle/working/dataset/cats/\")\ntrain_dogs_dir = os.path.join(\"/kaggle/working/dataset/dogs/\")\n","metadata":{"execution":{"iopub.status.busy":"2022-07-25T22:33:10.019229Z","iopub.execute_input":"2022-07-25T22:33:10.020209Z","iopub.status.idle":"2022-07-25T22:33:10.026329Z","shell.execute_reply.started":"2022-07-25T22:33:10.020169Z","shell.execute_reply":"2022-07-25T22:33:10.025069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Total Cat images in training Data: \", len(os.listdir(train_cats_dir)))\nprint(\"Total Dog images in training Data: \", len(os.listdir(train_dogs_dir)))","metadata":{"execution":{"iopub.status.busy":"2022-07-25T22:33:13.209953Z","iopub.execute_input":"2022-07-25T22:33:13.210298Z","iopub.status.idle":"2022-07-25T22:33:13.230620Z","shell.execute_reply.started":"2022-07-25T22:33:13.210268Z","shell.execute_reply":"2022-07-25T22:33:13.229628Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_cat_fnames = os.listdir( train_cats_dir )\ntrain_dog_fnames = os.listdir( train_dogs_dir )\n\nprint(train_cat_fnames[:10])\nprint(train_dog_fnames[:10])","metadata":{"execution":{"iopub.status.busy":"2022-07-25T22:33:14.719352Z","iopub.execute_input":"2022-07-25T22:33:14.719716Z","iopub.status.idle":"2022-07-25T22:33:14.740735Z","shell.execute_reply.started":"2022-07-25T22:33:14.719686Z","shell.execute_reply":"2022-07-25T22:33:14.739643Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport PIL\nimport cv2\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Conv2D, MaxPool2D\n\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2022-07-25T22:33:16.257497Z","iopub.execute_input":"2022-07-25T22:33:16.258209Z","iopub.status.idle":"2022-07-25T22:33:16.270652Z","shell.execute_reply.started":"2022-07-25T22:33:16.258173Z","shell.execute_reply":"2022-07-25T22:33:16.269419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Parameters for our graph; we'll output images in a 4x4 configuration\nnrows = 8\nncols = 8\n\npic_index = 0\n\n# Set up matplotlib fig, and size it to fit 4x4 pics\nfig = plt.gcf()\nfig.set_size_inches(ncols*3, nrows*3)\n\npic_index+=8\n\nnext_cat_pix = [os.path.join(train_cats_dir, fname) \n                for fname in train_cat_fnames[ pic_index-8:pic_index] \n               ]\n\nnext_dog_pix = [os.path.join(train_dogs_dir, fname) \n                for fname in train_dog_fnames[ pic_index-8:pic_index]\n               ]\n\nfor i, img_path in enumerate(next_cat_pix+next_dog_pix):\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    img = mpimg.imread(img_path)\n    plt.imshow(img)\n\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2022-07-25T22:33:17.890267Z","iopub.execute_input":"2022-07-25T22:33:17.891085Z","iopub.status.idle":"2022-07-25T22:33:19.023556Z","shell.execute_reply.started":"2022-07-25T22:33:17.891037Z","shell.execute_reply":"2022-07-25T22:33:19.022489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Normalization\ntrain_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(\n    train_dir,\n    batch_size = 200,\n    target_size = (150,150),\n    class_mode = 'binary'\n)","metadata":{"execution":{"iopub.status.busy":"2022-07-25T22:33:22.723565Z","iopub.execute_input":"2022-07-25T22:33:22.724211Z","iopub.status.idle":"2022-07-25T22:33:23.408325Z","shell.execute_reply.started":"2022-07-25T22:33:22.724171Z","shell.execute_reply":"2022-07-25T22:33:23.406733Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#callbacks\nclass myCallbacks(tf.keras.callbacks.Callback):\n    def onepoch_end(self, epoch, logs={}):\n        if logs.get('accuracy') >= 0.999:\n            print(\"\\nTraining Stopped Accuracy Reached 99.9%\")\n            self.model.stop_training = True","metadata":{"execution":{"iopub.status.busy":"2022-07-25T22:33:28.170497Z","iopub.execute_input":"2022-07-25T22:33:28.171644Z","iopub.status.idle":"2022-07-25T22:33:28.178056Z","shell.execute_reply.started":"2022-07-25T22:33:28.171598Z","shell.execute_reply":"2022-07-25T22:33:28.176917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = tf.keras.models.Sequential([\n    Conv2D(16, (3,3), activation='relu', input_shape=(150,150,3)),\n    MaxPool2D(2,2),\n    Conv2D(32, (3,3), activation=\"relu\"),\n    MaxPool2D(2,2),\n    Conv2D(64, (3,3), activation=\"relu\"),\n    MaxPool2D(2,2),\n    Conv2D(128, (3,3), activation=\"relu\"),\n    MaxPool2D(2,2),\n    Conv2D(128, (3,3), activation=\"relu\"),\n    MaxPool2D(2,2),\n    Flatten(),\n    Dense(512, activation='relu'),\n    Dense(1, activation=\"sigmoid\")\n    \n])","metadata":{"execution":{"iopub.status.busy":"2022-07-25T22:33:30.702192Z","iopub.execute_input":"2022-07-25T22:33:30.702628Z","iopub.status.idle":"2022-07-25T22:33:30.828324Z","shell.execute_reply.started":"2022-07-25T22:33:30.702595Z","shell.execute_reply":"2022-07-25T22:33:30.827068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(\n    loss = tf.keras.losses.binary_crossentropy,\n    optimizer = tf.keras.optimizers.RMSprop(learning_rate=0.001),\n    metrics = [\"accuracy\"]\n)","metadata":{"execution":{"iopub.status.busy":"2022-07-25T22:33:36.841301Z","iopub.execute_input":"2022-07-25T22:33:36.842347Z","iopub.status.idle":"2022-07-25T22:33:36.853872Z","shell.execute_reply.started":"2022-07-25T22:33:36.842293Z","shell.execute_reply":"2022-07-25T22:33:36.852940Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-07-25T22:33:40.632069Z","iopub.execute_input":"2022-07-25T22:33:40.632441Z","iopub.status.idle":"2022-07-25T22:33:40.639735Z","shell.execute_reply.started":"2022-07-25T22:33:40.632392Z","shell.execute_reply":"2022-07-25T22:33:40.638629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(\n    train_generator,\n    epochs=20,\n    steps_per_epoch=125,\n    callbacks=myCallbacks(),\n)","metadata":{"execution":{"iopub.status.busy":"2022-07-25T22:33:45.211222Z","iopub.execute_input":"2022-07-25T22:33:45.211616Z","iopub.status.idle":"2022-07-25T22:59:01.103583Z","shell.execute_reply.started":"2022-07-25T22:33:45.211584Z","shell.execute_reply":"2022-07-25T22:59:01.102463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing import image\n\nim_count = 0\nfor im in os.listdir(test_data):\n    # predicting images\n    path = '/kaggle/working/test1/' + im\n    img=image.load_img(path, target_size=(150, 150))\n  \n    x=image.img_to_array(img)\n    x /= 255\n    x=np.expand_dims(x, axis=0)\n    images = np.vstack([x])\n  \n    classes = model.predict(images, batch_size=10)\n  \n    print(classes[0])\n    im_count += 1\n  \n    if classes[0]>0.5:\n        print(im + \" is a dog\")\n    else:\n        print(im + \" is a cat\")\n    \n    if im_count == 20:\n        break\n        \n        \n    \n  ","metadata":{"execution":{"iopub.status.busy":"2022-07-25T23:16:27.683190Z","iopub.execute_input":"2022-07-25T23:16:27.683575Z","iopub.status.idle":"2022-07-25T23:16:28.565641Z","shell.execute_reply.started":"2022-07-25T23:16:27.683542Z","shell.execute_reply":"2022-07-25T23:16:28.564570Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import random\nfrom tensorflow.keras.preprocessing.image import img_to_array, load_img\n\n# Define a new Model that will take an image as input, and will output\n# intermediate representations for all layers in the previous model\nsuccessive_outputs = [layer.output for layer in model.layers]\nvisualization_model = tf.keras.models.Model(inputs = model.input, outputs = successive_outputs)\n\n# Prepare a random input image from the training set.\ncat_img_files = [os.path.join(train_cats_dir, f) for f in train_cat_fnames]\ndog_img_files = [os.path.join(train_dogs_dir, f) for f in train_dog_fnames]\nimg_path = random.choice(cat_img_files + dog_img_files)\nimg = load_img(img_path, target_size=(150, 150))  # this is a PIL image\nx   = img_to_array(img)                           # Numpy array with shape (150, 150, 3)\nx   = x.reshape((1,) + x.shape)                   # Numpy array with shape (1, 150, 150, 3)\n\n# Scale by 1/255\nx /= 255.0\n\n# Run the image through the network, thus obtaining all\n# intermediate representations for this image.\nsuccessive_feature_maps = visualization_model.predict(x)\n\n# These are the names of the layers, so you can have them as part of our plot\nlayer_names = [layer.name for layer in model.layers]\n\n# Display the representations\nfor layer_name, feature_map in zip(layer_names, successive_feature_maps):\n  \n  if len(feature_map.shape) == 4:\n    \n    #-------------------------------------------\n    # Just do this for the conv / maxpool layers, not the fully-connected layers\n    #-------------------------------------------\n    n_features = feature_map.shape[-1]  # number of features in the feature map\n    size       = feature_map.shape[ 1]  # feature map shape (1, size, size, n_features)\n    \n    # Tile the images in this matrix\n    display_grid = np.zeros((size, size * n_features))\n    \n    #-------------------------------------------------\n    # Postprocess the feature to be visually palatable\n    #-------------------------------------------------\n    for i in range(n_features):\n        x  = feature_map[0, :, :, i]\n        x -= x.mean()\n        x /= x.std ()\n        x *=  64\n        x += 128\n        x  = np.clip(x, 0, 255).astype('uint8')\n        display_grid[:, i * size : (i + 1) * size] = x # Tile each filter into a horizontal grid\n\n    #-----------------\n    # Display the grid\n    #-----------------\n    scale = 20. / n_features\n    plt.figure( figsize=(scale * n_features, scale) )\n    plt.title ( layer_name )\n    plt.grid  ( False )\n    plt.imshow( display_grid, aspect='auto', cmap='viridis' )","metadata":{"execution":{"iopub.status.busy":"2022-07-25T23:20:22.751026Z","iopub.execute_input":"2022-07-25T23:20:22.751479Z","iopub.status.idle":"2022-07-25T23:20:24.856032Z","shell.execute_reply.started":"2022-07-25T23:20:22.751439Z","shell.execute_reply":"2022-07-25T23:20:24.854914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}