{"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=224\nimg_size=150","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d853c8fa0d081e67d4a1f67a3ebf3e572a460b39"},"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":"0779bf3fbaa250ad1e0ccfb2018d2cb973323413"},"cell_type":"markdown","source":"## Implementation of a pretrained VGG16 model (Conv+Top Train)"},{"metadata":{"trusted":true,"_uuid":"5f85ddce0f7166ad19bab58861576516efd5759f"},"cell_type":"code","source":"print ('Creating model...')\nbase_model = applications.VGG16(include_top=False, weights='imagenet',input_shape=(img_size,img_size, 3))\nfor layer in  base_model.layers[:-4]:\n    layer.trainable = False\nvgg_conv_model = Sequential()\nvgg_conv_model.add(base_model)\nvgg_conv_model.add(Flatten())\nvgg_conv_model.add(Dense(4096, activation='relu'))\nvgg_conv_model.add(Dropout(0.5))\nvgg_conv_model.add(Dense(4096, activation='relu'))\nvgg_conv_model.add(Dropout(0.5))\nvgg_conv_model.add(Dense(2, activation='softmax'))\nprint ('Summary of the model...')\nvgg_conv_model.summary()\nprint ('Compiling model...')\n#vgg_conv_model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])\n#vgg_conv_model.compile(optimizer=SGD(lr=1e-3), loss='categorical_crossentropy', metrics=['accuracy'])\nvgg_conv_model.compile(optimizer=SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True), 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":"f6d421da1b3270cf8c162c7c752b2bb23e0def92"},"cell_type":"code","source":"# Create logs, filepath and checkpoints for the model.\nclass 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('vgg_conv_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":"842cf53af92579e5a0388ba2c8ff7190e2eca96e"},"cell_type":"code","source":"# Fit the model on batches of 20000 samples of training  data and validate on 5000 samples.\nfitted_vgg_conv_model=vgg_conv_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":"4f431704f799695b71b6f62aba9dc5346c6332ab","collapsed":true},"cell_type":"code","source":"# Plot Val_loss,train_loss and val_acc and train_acc.\nacc = fitted_vgg_conv_model.history['acc']\nval_acc = fitted_vgg_conv_model.history['val_acc']\nloss = fitted_vgg_conv_model.history['loss']\nval_loss =fitted_vgg_conv_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,"_uuid":"8090bb4756b7be5862fd8b63fe5f0845c52d8b7b","collapsed":true},"cell_type":"code","source":"# Proces test data to generate predictions on provided test data.\ntest_generator.reset()\npred=vgg_conv_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":"8fec05fd31d40c4350b6d23900b195d6cc9af6d3"},"cell_type":"code","source":"# Display predictions with 25 pictures with their labels.\ndef 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,"_uuid":"af3ebf36b0c7275e3cadd2bcde8b4b4d71078497","collapsed":true},"cell_type":"code","source":"display_testdata(new_preds[7700:7725],filename[7700:7725])","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}