{"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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","collapsed":true,"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":false},"cell_type":"code","source":"train_image_dir = 'data/train'\nvalidation_image_dir = 'data/validation'\ntest_image_dir = \"data/test\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMAGE_HEIGHT, IMAGE_WIDTH = 256, 256\nBATCH_SIZE = 128\nTRAIN_IMGS = 20000\nVAL_IMGS = 5000\nMAX_TRAIN_STEPS = 200\nSTEP_COUNT = min(MAX_TRAIN_STEPS, TRAIN_IMGS//BATCH_SIZE)\nNB_EPOCHS = 30\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Flatten, Dense\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras import backend as K\n\nfrom tensorflow.keras.applications.vgg16 import VGG16\n\nif K.image_data_format() == 'channels_first':\n    input_shape = (3, IMAGE_WIDTH, IMAGE_HEIGHT)\nelse:\n    input_shape = (IMAGE_HEIGHT, IMAGE_WIDTH, 3)\n    \nmodel = Sequential()\n\nmodel = VGG16(include_top=False, input_shape=(256, 256, 3))\nfor layer in model.layers:\n    layer.trainable = False\n    \nflat1 = Flatten()(model.layers[-1].output)\nclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\noutput = Dense(1, activation='sigmoid')(class1)\nmodel = Model(inputs=model.inputs, outputs=output)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\npd.options.display.max_rows = 4000\ntf.keras.utils.plot_model(model,'arch.png', show_shapes=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"SGD_OPTIMIZER = tf.keras.optimizers.SGD(lr=0.001, momentum=0.9)\n\nmodel.compile(loss='binary_crossentropy',\n            optimizer=SGD_OPTIMIZER,\n            metrics=['accuracy'])\nreduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5,\n                              patience=3, verbose=1, mode='min', epsilon=0.0001, cooldown=2, min_lr=1e-6)\nearly = tf.keras.callbacks.EarlyStopping(monitor=\"val_loss\", \n                      mode=\"min\", \n                      patience=10)\ncallbacks_list = [early, reduce_lr]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rescale=1. / 255,\n    rotation_range = 15, \n    width_shift_range = 0.1, \n    height_shift_range = 0.1, \n    shear_range = 0.01,\n    zoom_range = [0.9, 1.25],  \n    horizontal_flip = True, \n   vertical_flip = False)\n\nvalidation_datagen = ImageDataGenerator(rescale=1./255)\n\ntest_datagen = ImageDataGenerator(rescale=1. / 255)\n\ntrain_generator = train_datagen.flow_from_directory(\n    train_image_dir,\n    target_size=(IMAGE_WIDTH, IMAGE_HEIGHT),\n    batch_size=BATCH_SIZE,\n    shuffle=True,\n    class_mode='binary')\nprint(train_generator.class_indices)\n\nvalidation_generator = test_datagen.flow_from_directory(\n    validation_image_dir,\n    target_size=(IMAGE_WIDTH, IMAGE_HEIGHT),\n    batch_size=BATCH_SIZE,\n    shuffle=True,\n    class_mode='binary')\nprint(validation_generator.class_indices)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"loss_history=[model.fit_generator(\n    train_generator,\n    steps_per_epoch=STEP_COUNT,\n    epochs=NB_EPOCHS,\n    validation_data=validation_generator,\n    validation_steps=VAL_IMGS // BATCH_SIZE,\n    callbacks=callbacks_list)]\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save('vgg_model_best.h5')\nmodel.save_weights('vgg_model_best_w.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def show_loss(loss_history):\n    epich = np.cumsum(np.concatenate(\n        [np.linspace(0.5, 1, len(mh.epoch)) for mh in loss_history]))\n    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 12))\n    _ = ax1.plot(epich,\n                 np.concatenate([mh.history['loss'] for mh in loss_history]),\n                 'b-',\n                 epich, np.concatenate(\n            [mh.history['val_loss'] for mh in loss_history]), 'r-')\n    ax1.legend(['Training', 'Validation'])\n    ax1.set_title('Loss')\n\n    _ = ax2.plot(epich, np.concatenate(\n        [mh.history['accuracy'] for mh in loss_history]), 'b-',\n                     epich, np.concatenate(\n            [mh.history['val_accuracy'] for mh in loss_history]),\n                     'r-')\n    ax2.legend(['Training', 'Validation'])\n    ax2.set_title('Accuracy')\n\nshow_loss(loss_history)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import load_model\nfrom keras.preprocessing import image\nimport numpy as np\nfrom os import listdir\nfrom os.path import isfile, join\nimport matplotlib.pyplot as plt\nfrom skimage.io import imread\nimport tensorflow as tf\nimport glob\nfrom matplotlib.pyplot import figure, imshow, axis\nfrom matplotlib.image import imread\nfrom PIL import Image, ImageDraw, ImageFont\n\nIMAGE_WIDTH, IMAGE_HEIGHT = 256, 256\n\nmodel = tf.keras.models.load_model('vgg_model_best.h5')\n\nfile_path = \"data/test/\"\n\nall_files = [f for f in listdir(file_path) if isfile(join(file_path, f))]\n\ndogs_counter = 0 \ncats_counter  = 0\nfor file in all_files:\n    img = image.load_img(file_path+file, target_size=(IMAGE_WIDTH, IMAGE_HEIGHT))\n    \n    x = image.img_to_array(img)\n    x = np.expand_dims(x, axis=0)\n    \n    images = np.vstack([x])\n    classes = model.predict(images, batch_size=20)\n    classes = classes[0][0]\n    \n    fontPath = \"/Users/Admin/Downloads/open-sans/OpenSans-Semibold.ttf\"\n    font  =  ImageFont.truetype(fontPath,50)\n    size = 400, 300\n    \n    if classes == 0:\n        res_image = Image.open('data/test/'+file)\n        draw = ImageDraw.Draw(res_image)\n        draw.text((100, 100),\"Kitty\", font=font, fill=(255,0,0,128))\n        res_image.thumbnail(size)\n        display(res_image)\n        cats_counter += 1\n    else:\n        res_image = Image.open('data/test/'+file)\n        draw = ImageDraw.Draw(res_image)\n        draw.text((100, 100),\"Doggo\", font=font, fill=(255,0,0,128))\n        res_image.thumbnail(size)\n        display(res_image)\n        dogs_counter += 1\nprint(\"Total number of Dogs: \",dogs_counter)\nprint(\"Total number of Cats: \",cats_counter)","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}