{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"collapsed":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\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"975ec57d056fe10261cd1b3638f34491300bae7f","collapsed":true},"cell_type":"code","source":"ls ../input/smalldata/smalldata/smalldata","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","collapsed":true,"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":false},"cell_type":"markdown","source":"## Dataset\n\nProvided dataset contains 25000 images of dogs and cats in  'train.zip'  folder and image files are named based on whether the image is of dog or cat. Dataset also contains 'test .zip'  folder which contains 12,500 images and image files are named with a number.Our goal is to create a CNN model which generates a probability that the image is a dog (1 = dog, 0 = cat) for each image in the test set."},{"metadata":{"_uuid":"881055b5d1b6edc20d4f578b01ae57b126dc87f9"},"cell_type":"markdown","source":"## Load general packages"},{"metadata":{"_uuid":"5f16a6a0848f46d8d551ee76c22dd761c8190f46","trusted":true,"collapsed":true},"cell_type":"code","source":"%matplotlib inline\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nfrom PIL import ImageFile \nimport numpy as np\nimport os \nimport cv2\nfrom tqdm import tqdm_notebook\nfrom random import shuffle\nimport pandas as pd\nimport random\nfrom tqdm import tqdm\nimport seaborn as sns\nimport math","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"b732a5082bcd1b3986fcad10e0fffb842017e86a"},"cell_type":"markdown","source":"## Load Keras packages"},{"metadata":{"trusted":true,"_uuid":"64ebeb06a96cb0643ae24bd0f277360a9cd2eacd"},"cell_type":"code","source":"import keras\nfrom keras import applications\nfrom keras import optimizers\nfrom keras import backend as K\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D,GlobalMaxPooling2D\nfrom keras.layers import Activation, Dropout, Flatten, Dense\nfrom keras.constraints import maxnorm\nfrom keras.optimizers import SGD\nfrom keras.utils import np_utils\nfrom keras.callbacks import Callback,ModelCheckpoint\nfrom keras.applications import VGG16\nfrom keras.applications import ResNet50\nfrom keras.models import load_model\nfrom keras.preprocessing.image import load_img","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"cba4b4b3e9743e6a8ec11eb02b2ea25ec8f1c118"},"cell_type":"markdown","source":"## Intialize variables\nThe image size is 224.The images are stored in two folders, train and test and there are two image classes: Dog and Cat.\nMy plan is to use all training data (25,000 images) of which 20,000 imgaes for  traning and 5000 for valdation of the models.\nWe will use a subset of the training data set (20,000 images). From the training set,80% will be used for training, 20% for validation."},{"metadata":{"trusted":true,"_uuid":"977057f5a6c4a36864ad0cca7c094dafaea07c9e","collapsed":true},"cell_type":"code","source":"batch_size = 32\nepochs =10\nnum_classes = 2\nnum_t_samples = 20000\nnum_v_samples = 5000\npath='../input/dogs-vs-cats-redux-kernels-edition/'\ndir= '../input/dogscats/data/data/'\ntrain_data_path = path+'train/'\ntest_data_path =  path+'test/'\ntrain_data_dir = dir+'train/'\nvalidation_data_dir=dir+'validation/'\ntest_dir='../input/dogscatstest/test1/test1/'\n#img_size=197\nimg_size=224","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a38dda5fcb6fcd84600d34d13a1f0ee87790ebfd"},"cell_type":"code","source":"#Process training data to make it ready for fitting.\ntrain_datagen = ImageDataGenerator(rescale=1. / 255,shear_range=0.2,zoom_range=0.2,horizontal_flip=True)\nval_datagen = ImageDataGenerator(rescale=1. / 255)\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(train_data_dir,target_size=(img_size, img_size),\n                                                    batch_size=batch_size,class_mode='categorical')\nvalidation_generator = val_datagen.flow_from_directory(validation_data_dir,target_size=(img_size, img_size),\n                                                        batch_size=batch_size,class_mode='categorical') \ntest_generator = test_datagen.flow_from_directory(test_dir,target_size=(img_size, img_size),batch_size=batch_size,\n                                                  class_mode='categorical',shuffle=False)\nfilename=test_generator.filenames","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"286b095492b9daf06da5a0970453760b6403269b"},"cell_type":"markdown","source":"## Implementation of pretrained ResNet-50 Model (Transfer Learning)"},{"metadata":{"trusted":true,"_uuid":"b50a3894d3062ca64cf96d09c1ee28accf5998c8"},"cell_type":"code","source":"print ('Creating model...')\nresnet50_model = Sequential()\nresnet50_model.add(ResNet50(include_top=False, pooling='max', weights='imagenet'))\nresnet50_model.add(Dense(num_classes, activation='softmax'))\nresnet50_model.layers[0].trainable = True\nprint ('Summary of the model...')\nresnet50_model.summary()\nprint ('Compiling model...')\n#resnet50_model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])\nresnet50_model.compile(optimizer=SGD(lr=1e-3), loss='categorical_crossentropy', metrics=['accuracy'])\nprint ('Model is ready to be fit with training data.')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"dfbc2f317195ab290a6d01b47340ddda05e3c11d"},"cell_type":"code","source":"class LossHistory(Callback):\n    def on_train_begin(self, logs={}):\n        self.losses = []\n        self.val_losses = []\n    def on_epoch_end(self, batch, logs={}):\n        self.losses.append(logs.get('loss'))\n        self.val_losses.append(logs.get('val_loss'))\nhistory = LossHistory()\nearly_stopping = keras.callbacks.EarlyStopping(monitor='val_loss',min_delta=0,patience=20,verbose=0, mode='auto')\ncheckpoint = ModelCheckpoint('resnet50_model.h5',monitor='val_loss', verbose=1, save_best_only=True,mode='auto')\ncallbacks_list = [checkpoint,history,early_stopping]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"515feca7156a42fddb8fe41d667ef36f704ba55f"},"cell_type":"code","source":"fitted_resnet50_model=resnet50_model.fit_generator(train_generator,\n    steps_per_epoch=math.ceil(train_generator.samples/train_generator.batch_size),\n    epochs=epochs,validation_data=validation_generator,\n    validation_steps=math.ceil(validation_generator.samples/validation_generator.batch_size),callbacks=callbacks_list,verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7f1ac860a37368859a6622cd460399e36914a475","collapsed":true},"cell_type":"code","source":"acc = fitted_resnet50_model.history['acc']\nval_acc = fitted_resnet50_model.history['val_acc']\nloss = fitted_resnet50_model.history['loss']\nval_loss =fitted_resnet50_model.history['val_loss']\nepochs = range(len(acc)) \nplt.plot(epochs, acc, 'b', label='Training acc')\nplt.plot(epochs, val_acc, 'r', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\nplt.figure()\nplt.plot(epochs, loss, 'b', label='Training loss')\nplt.plot(epochs, val_loss, 'r', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"cb074063483a37a33ae5dfcfe7281af49522ff65"},"cell_type":"code","source":"# Create a generator for prediction\nvalidation_generator = validation_datagen.flow_from_directory(\n        validation_dir,\n        target_size=(img_size, img_size),\n        batch_size=batch_size,\n        class_mode='categorical',\n        shuffle=False)\n \n# Get the filenames from the generator\nfnames = validation_generator.filenames\n \n# Get the ground truth from generator\nground_truth = validation_generator.classes\n \n# Get the label to class mapping from the generator\nlabel2index = validation_generator.class_indices\n \n# Getting the mapping from class index to class label\nidx2label = dict((v,k) for k,v in label2index.items())\n \n# Get the predictions from the model using the generator\npredictions = resnet50_model.predict_generator(validation_generator, steps=validation_generator.samples/validation_generator.batch_size,\n                                               verbose=1)\npredicted_classes = np.argmax(predictions,axis=1)\n \nerrors = np.where(predicted_classes != ground_truth)[0]\nprint(\"No of errors = {}/{}\".format(len(errors),validation_generator.samples))\n \n# Show the errors\nfor i in range(len(errors)):\n    pred_class = np.argmax(predictions[errors[i]])\n    pred_label = idx2label[pred_class]\n     \n    title = 'Original label:{}, Prediction :{}, confidence : {:.3f}'.format(\n        fnames[errors[i]].split('/')[0],\n        pred_label,\n        predictions[errors[i]][pred_class])\n     \n    original = load_img('{}/{}'.format(validation_dir,fnames[errors[i]]))\n    plt.figure(figsize=[7,7])\n    plt.axis('off')\n    plt.title(title)\n    plt.imshow(original)\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"346b5cc4233ef267a3879d11aeb53ddbf89c8ee9"},"cell_type":"code","source":"model=load_model('../input/resnet50-all/resnet50_model.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cab76c493a0abd0fba89c9ecfda1b032a220009e","collapsed":true},"cell_type":"code","source":"test_generator.reset()\npred=model.predict_generator(test_generator,steps=math.ceil(test_generator.samples/test_generator.batch_size),verbose=1)\npredicted_class_indices=np.argmax(pred,axis=1)\nlabels = (train_generator.class_indices)\nlabels = dict((v,k) for k,v in labels.items())\npredictions = [labels[k] for k in predicted_class_indices]\nnew_preds=[]\nfor i in range(len(predictions)):\n    if predictions[i]=='dogs':\n        new_preds.append('dog')\n    else:\n        new_preds.append('cat')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"14e8789d42def9c714aea66b322ea968b0adb3ce"},"cell_type":"code","source":"def display_testdata(testdata,filenames):\n    f, ax = plt.subplots(5,5, figsize=(15,15))\n    i=0\n    for a,b in zip(testdata,filenames):\n        pred_label=a\n        fname=b\n        title = 'Prediction :{}'.format(pred_label)   \n        original = load_img('{}/{}'.format(test_dir,fname))\n        ax[i//5,i%5].axis('off')\n        ax[i//5,i%5].set_title(title)\n        ax[i//5,i%5].imshow(original)\n        i=i+1\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"f823b4c03e5ac8fd8c10678c682b785830af41bf"},"cell_type":"code","source":"filename.index('test/10.jpg')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8fec05fd31d40c4350b6d23900b195d6cc9af6d3","collapsed":true},"cell_type":"code","source":"display_testdata(new_preds[7700:7725],filename[7700:7725])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"e42662f6f203145941f7f19208b1cc0955403bdd"},"cell_type":"code","source":"def create_submission():\n    lables=[]\n    file_index=[]\n    for a,b in zip(newpreds,filename):\n        pred_label=a\n        fname=b[5:]\n        fname=fname.split('.')[0]\n        labels.append(pred_label)\n        file_index.append(fname)\n    results=pd.DataFrame({\"Filename\":file_index,\n                      \"Predictions\":labels})\n    results.to_csv(\"submission.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8d0819e22e38404800416aa5c34fa77375326898","collapsed":true},"cell_type":"code","source":"create_submission()","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}