{"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":"from zipfile import ZipFile\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nimport random\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.optimizers import RMSprop\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\",\"r\").extractall()\nZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\", \"r\").extractall()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dir = \"./train/\"\ntest_dir = \"./test1/\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_names = os.listdir(train_dir)\ncategories = []\nfor filename in train_names:\n    category = filename.split(\".\")[0]\n    if category == \"dog\":\n        categories.append(\"dog\")\n    else:\n        categories.append(\"cat\")\ndf = pd.DataFrame({\n    \"filename\" : train_names,\n    \"category\" : categories\n})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.category.value_counts().plot.bar()\nplt.title(str(len(df[df['category'] == 'cat']))+\" cats\" + \" | \" +str(len(df[df['category'] == 'dog']))+\" dogs\")\nplt.ylabel(len(df))\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.models.Sequential([\n    tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(120, 120, 3)),\n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Conv2D(32, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2), \n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'), \n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Flatten(), \n    tf.keras.layers.Dense(1024, activation='relu'),\n    tf.keras.layers.Dense(2048, activation='relu'),\n    tf.keras.layers.Dense(2048, activation='relu'),\n    # Only 1 output neuron. It will contain a value from 0-1 where 0 for 1 class ('cats') and 1 for the other ('dogs')\n    tf.keras.layers.Dense(1, activation='sigmoid')  \n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"load_img(train_dir+random.choice(df.filename))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df, validate_df = train_test_split(df, test_size = 0.2, random_state = 42)\ntrain_df = train_df.reset_index(drop=True)\nvalidate_df = validate_df.reset_index(drop=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(rotation_range=40,\n    rescale=1./255,\n    shear_range=0.2,\n    zoom_range=0.5,\n    horizontal_flip=True,\n    width_shift_range=0.2,\n    height_shift_range=0.2\n)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    train_df, \n    \"./train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=(120,120),\n    class_mode='binary',\n    batch_size=64,\n    color_mode=\"rgb\",\n    shuffle=True\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"validation_datagen = ImageDataGenerator(rescale=1./255)\n\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df, \n    \"./train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=(120,120),\n    class_mode='binary',\n    batch_size=64,\n    color_mode=\"rgb\",\n    shuffle=True\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer=RMSprop(lr=0.001),\n              loss='binary_crossentropy',\n              metrics = ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(\n    train_generator,\n    steps_per_epoch=len(train_df)/64,\n    epochs=100,\n    validation_data=validation_generator,\n    validation_steps=len(validate_df)/64\n)\n\n#-----------------------------------------------------------\n# Retrieve a list of list results on training and test data\n# sets for each training epoch\n#-----------------------------------------------------------\nacc      = history.history[     'accuracy' ]\nval_acc  = history.history[ 'val_accuracy' ]\nloss     = history.history[    'loss' ]\nval_loss = history.history['val_loss' ]\n\nepochs   = range(len(acc)) # Get number of epochs\n\n#------------------------------------------------\n# Plot training and validation accuracy per epoch\n#------------------------------------------------\nplt.plot  ( epochs,     acc )\nplt.plot  ( epochs, val_acc )\nplt.title ('Training and validation accuracy')\nplt.figure()\n\n#------------------------------------------------\n# Plot training and validation loss per epoch\n#------------------------------------------------\nplt.plot  ( epochs,     loss )\nplt.plot  ( epochs, val_loss )\nplt.title ('Training and validation loss'   )","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}