{"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\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","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport zipfile\nimport random\nimport shutil\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom shutil import copyfile\nfrom os import getcwd\nimport tqdm\nimport shutil\nfrom tensorflow.python.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.python.keras.models import Sequential\nfrom tensorflow.python.keras.layers import Conv2D, MaxPooling2D\nfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras import layers","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_path = '../input/dogs-vs-cats/train.zip'\ntest_path = '../input/dogs-vs-cats/test1.zip'\n\n# save all files to kaggle/files/images\ndestination = '/kaggle/files/images'\n\nfrom zipfile import ZipFile as zipper\nwith zipper(train_path, 'r') as zipp:\n    zipp.extractall(destination)\n    \nwith zipper(test_path, 'r') as zipp:\n    zipp.extractall(destination)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.DataFrame({'file': os.listdir('/kaggle/files/images/train')})\n\ncategories = []\nfor i in os.listdir('/kaggle/files/images/train'):\n    if 'dog' in i:\n        categories.append(1)\n    else:\n        categories.append(0)\n        \ntrain['categories'] = categories\ntrain['categories'] = train['categories'].replace({0: 'cat', 1: 'dog'})\ntrain_set, val_set = train_test_split(train, test_size=0.2, random_state = 0)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator, load_img\nfrom tensorflow.keras.utils import to_categorical\n\ntrain_gen_scaled = ImageDataGenerator(rescale=1./255)\nval_gen_scaled = ImageDataGenerator(rescale=1./255)\n\nbatch_size = 64\n\n# generating from data frame \ntrain_generator_scaled = train_gen_scaled.flow_from_dataframe(\n    dataframe = train_set,\n    directory = destination + '/train/', # file path format\n    x_col = 'file',\n    y_col = 'categories',\n    class_mode = 'categorical',\n    target_size = (224,224),\n    batch_size = 64\n)\n\nvalidation_generator_scaled = val_gen_scaled.flow_from_dataframe(\n    dataframe = val_set,\n    directory = destination + '/train/',\n    x_col = 'file',\n    y_col = 'categories',\n    class_mode = 'categorical',\n    target_size = (224,224),\n    batch_size = batch_size,\n    shuffle = False )# ensure the validation and prediction are not random)\n\ndef mini_batch_example_plot(df):\n    '''\n    This function creates 8 examples plots.\n    \n    df - the dataframe containing examples \n    '''\n    # create an another generator for training set\n    example_generator = train_gen_scaled.flow_from_dataframe(\n        dataframe = df,\n        directory = destination + '/train/',\n        x_col = 'file',\n        y_col = 'categories',\n        class_mode = 'categorical',\n        target_size = (224,224)\n    )\n    \n    fig, ax  = plt.subplots(2,4,figsize=(12, 12))\n    ax = ax.flatten()\n    \n    for i in range(8):\n        X, Y = next(example_generator)\n        image = X[0]\n        ax[i].imshow(image)\n        ax[i].axis('off')\n    \n    \nmini_batch_example_plot(train_set)\npre_trained_model = tf.keras.applications.InceptionResNetV2(\n    include_top=False,\n    weights=None,\n    input_shape=(224,224,3),\n    \n)\n\npre_trained_model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras import Model\nlast_layer = pre_trained_model.get_layer('conv_7b_ac')\nlast_output = last_layer.output\nmodel=keras\nmodel=layers.Flatten()(last_output)\nmodel=layers.Dense(1024,activation='relu')(model)\nmodel=layers.Dropout(0.2)(model)\nmodel=layers.Dense (2,activation='softmax')(model)\nmodel = Model(pre_trained_model.input, model)\nmodel.compile(loss='binary_crossentropy',\n              optimizer='adam',\n              metrics=['accuracy'])\n\nmodel.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit_generator(\n    train_generator_scaled,\n    epochs=100,\n   validation_data = validation_generator_scaled,\n     validation_steps = 64,\n    steps_per_epoch=64\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}