{"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 in \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 \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\n#print(os.listdir(\"../input/train\"))\n#cat.11679.jpg\n#dog.2578.jpg\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"#Get label from image name, for Cat, return 0 nd for dog, return 1\ndef get_label(img_name):\n    idx = img_name.find('.')\n    label = img_name[:idx]\n    #return label\n    if label == 'cat':\n        return 0\n    else:\n        return 1   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"423dfee63d9c30142a09ee5c011bfc2ae6332116"},"cell_type":"code","source":"from skimage.io import imread\nimport cv2 as cv\n#This function reads images from path given and resize it\ndef get_img_files(img_path,name):\n    file_name = img_path+'/'+str(name)\n    img = imread(file_name)\n    img = cv.resize(img,(img_cols,img_rows),3)\n    return img        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"28662ea51023fe0a91209320ae263ad3bb2a7f9a"},"cell_type":"code","source":"img_path = '../input/train'\n#This function is to create custom datagenerator\ndef get_data(batch_size = 64):\n    img_files = os.listdir(\"../input/train\")\n    while True:\n        # get files as per batch size\n        files = np.random.choice(a = img_files, size = batch_size)\n        ite_input = []\n        ite_output = []           \n        #Read each input image and get labels\n        for file in files:\n            dog_cat = get_img_files(img_path,file)\n            label = get_label(file)            \n            ite_input.append(dog_cat)\n            ite_output.append(label)\n            \n        # Return a tuple of (input,output) to feed the network\n        x = np.array( ite_input)\n        y = np.array( ite_output )\n        y=keras.utils.to_categorical(y, num_classes=num_classes)\n        yield(x, y)        \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"72bcfcb966ac978e03a03b8863cc7a3d8aff3758"},"cell_type":"code","source":"from tensorflow.python.keras.applications import ResNet50\nfrom tensorflow.python.keras.models import Sequential\nfrom tensorflow.python.keras.layers import Activation,Dense, Flatten, Conv2D, Dropout,MaxPooling2D\nfrom tensorflow.python import keras\nfrom tensorflow.python.keras.optimizers import RMSprop\nopti = RMSprop(lr=1e-4)\nloss_function = 'binary_crossentropy'\nact_last = 'sigmoid'\n#act_last = 'softmax'\nact = 'relu'\n\nnum_classes = 2\nimg_rows = 64\nimg_cols = 64\nimg_depth = 3\n\n#Create a model\ndef get_model():\n    model = Sequential()\n    model.add(Conv2D(32, kernel_size=(3, 3),padding='same',\n                      activation=act,\n                      input_shape=(img_cols, img_rows, img_depth)))\n    model.add(Conv2D(32, kernel_size=(3, 3), padding='same',activation=act))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    \n    model.add(Conv2D(64, kernel_size=(3, 3), padding='same',activation=act))\n    model.add(Conv2D(64, kernel_size=(3, 3), padding='same',activation=act))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    \n    model.add(Conv2D(128, kernel_size=(3, 3), padding='same',activation=act))\n    model.add(Conv2D(128, kernel_size=(3, 3), padding='same',activation=act))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    \n    model.add(Conv2D(256, kernel_size=(3, 3), padding='same',activation=act))\n    model.add(Conv2D(256, kernel_size=(3, 3), padding='same',activation=act))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    \n    model.add(Flatten())    \n    model.add(Dense(256, activation=act))    \n    model.add(Dropout(0.5))\n    model.add(Dense(256, activation=act))    \n    model.add(Dropout(0.5))\n    model.add(Dense(num_classes, activation=act_last))\n\n    model.compile(loss=loss_function,\n                  optimizer=opti,\n                  metrics=['accuracy'])    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"bce8f80802bb421ce95d4ad462ff7fca737bd022"},"cell_type":"code","source":"from keras.applications.resnet50 import preprocess_input\ndef _load_image(img_path):\n    img = image.load_img(img_path, target_size=(64, 64))\n    img = image.img_to_array(img)\n    img = np.expand_dims(img, axis=0)\n    img = preprocess_input(img)\n    return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b7745a9f28980f3f429b7196041b930a8414c1a8"},"cell_type":"code","source":"# #get new model and train with new data\nmy_new_model = get_model()\nmy_new_model.fit_generator(\n        get_data(),\n        steps_per_epoch=500,\n        epochs=6,\n        #validation_data=validation_generator,\n        #validation_steps=1\n        )\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c651bce48384ff5ab90d7535dc5090dc7c0a4043"},"cell_type":"code","source":"#read test images and capture predictions\ntest_dir = '../input/test/'\ntest_img_files = os.listdir(test_dir)\ntest_files = np.random.choice(a = test_img_files, size = 20)\nite_input_test = []\n#Read each input image and get labels\nfor test_file in test_files:\n    test_dog_cat = get_img_files(test_dir,test_file)\n    ite_input_test.append(test_dog_cat)\n\n# Return a tuple of (input,output) to feed the network\ntest_x = np.array( ite_input_test)\n\npredictions = my_new_model.predict(test_x, verbose=0)\nprint(predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"336233199efa6cbae521e7748defae377d66a221"},"cell_type":"code","source":"#check for first 20 predictions\nimport matplotlib.pyplot as plt\nfor i in range(0,20):\n    if predictions[i, 0] >= 0.5: \n        print('I am {:.2%} sure this is a cat'.format(predictions[i][0]))\n    else: \n        print('I am {:.2%} sure this is a Dog'.format(1-predictions[i][0]))\n    \n    plt.imshow(ite_input_test[i])\n    plt.show()    \n    ","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"}},"nbformat":4,"nbformat_minor":1}