{"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)\nimport cv2\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport random\nimport gc\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 all files under the input directory\n\nimport os\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_dir = '../input/dogs-vs-cats-redux-kernels-edition/train'\ntest_dir = '../input/dogs-vs-cats-redux-kernels-edition/test'\n\ntrain_dogs = ['../input/dogs-vs-cats-redux-kernels-edition/train/{}'.format(i) for i in os.listdir(train_dir) if 'dog' in i] # get dog images\ntrain_cats = ['../input/dogs-vs-cats-redux-kernels-edition/train/{}'.format(i) for i in os.listdir(train_dir) if 'cat' in i] # get cat images\n\ntest_imgs = ['../input/dogs-vs-cats-redux-kernels-edition/test/{}'.format(i) for i in os.listdir(test_dir)] # get test images\n\ntrain_imgs = train_dogs[:2000] + train_cats[:2000] #slicing the dataset and using 2000 imges from each class\n\nrandom.shuffle(train_imgs) # shuffle the images randomly\n\n#delete the extra stuff to clean up the memory\ndel train_dogs\ndel train_cats\n# collect garbage to save memory\ngc.collect()\n\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.image as mpimg\n\nfor ima in train_imgs[0:3]:\n    img = mpimg.imread(ima)\n    imgplot = plt.imshow(img)\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Lets declare image dimensions and reshape the images\n# 3 channles for R G B\nnrows = 150\nncols = 150\nchannels = 3\n\n# declare a function to read and process our images to a suitable format\n\ndef read_and_process_image(list_of_images):\n    X = [] #images\n    y = []#labels\n    \n    for image in list_of_images:\n        #print(image)\n        X.append(cv2.resize(cv2.imread(image, cv2.IMREAD_COLOR), (nrows, ncols), interpolation=cv2.INTER_CUBIC))\n        if 'dog.' in image:\n            y.append(1)\n        elif 'cat.' in image:\n            y.append(0)\n        \n        \n    return X,y","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Processing pur images\n\nX,y = read_and_process_image(train_imgs)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(20,10))\ncolumns =5\nfor i in range (columns):\n    plt.subplot(5 / columns+1, columns, i+1)\n    plt.imshow(X[i])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Just to check if we really have 0's and 1's labelled properly\nimport seaborn as sns\ndel train_imgs\ngc.collect()\n\n# convert list to numpy array\nX = np.array(X)\ny = np.array(y)\n\nsns.countplot(y)\nplt.title('Labels for cats and dogs')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Shape of train images is ',X.shape )\nprint('Shape of labels is ',y.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Preparing train and dev sets using sklearn library\nfrom sklearn.model_selection import train_test_split\nX_train, X_dev, y_train, y_dev =  train_test_split(X, y, test_size=0.20, random_state=2)\n\nprint('Shape of train images is: ',X_train.shape)\nprint('Shape of dev train images is: ',X_dev.shape)\nprint('Shape of train labels is: ', y_train.shape)\nprint('Shape of dev labels is: ',y_dev.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del X\ndel y\ngc.collect()\n\n# get the length of train and dev sets\nntrain = len(X_train)\nndev = len(X_dev)\n# we will use a batch size of 32\nbatch_size = 32","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# We will be using ConvNets (CNN's) with Keras\nfrom keras import layers\nfrom keras import models\nfrom keras import optimizers\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing.image import img_to_array, load_img\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# We will be using the nn architecture of vggnet - Sequetial model\n\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(32, (3,3), activation='relu', input_shape=(150,150,3)))\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Conv2D(65, (3,3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Conv2D(128, (3,3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Conv2D(128, (3,3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dropout(0.5)) # Dropout for regularization\nmodel.add(layers.Dense(512, activation='relu')) \nmodel.add(layers.Dense(1, activation='sigmoid')) # Sigmoid at the end because, binary classification\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# We'll use RMS prop optimizer with a learning rate of 0.0001\n# We'll use binary_crossentropy loss function cuz its a binary classification\n# We'll use accuracy (acc) metric to evaluate the performance after training since it's a classification problem\n\nmodel.compile(loss='binary_crossentropy', optimizer=optimizers.RMSprop(lr=1e-4), metrics=['acc'])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# we are going to create 2 ImageDataGenerators -> Train, dev # Converts IMG to RGB and floating points to tensors -> easy to feed to a NN\n# Augmeting train_dataset: this helps preventingg overfitting, since we are using a relatively small dataset ## Normalization ##\ntrain_datagen = ImageDataGenerator(rescale=1./255, #Scale the image b/w 0 and 1 --> norm\n                                   rotation_range=40,\n                                   width_shift_range=0.2,\n                                   height_shift_range=0.2,\n                                   shear_range=0.2,\n                                   zoom_range=0.2,\n                                   horizontal_flip=True,\n                                  )\ndev_datagen = ImageDataGenerator(rescale=1./255) # No data augmentation in dev set, only rescaling","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Create Image generators\ntrain_generator = train_datagen.flow(X_train, y_train, batch_size=batch_size)\ndev_generator = dev_datagen.flow(X_dev, y_dev, batch_size=batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# The Training\n# Lets train for epochs and 100 steps per epoch and we use .fit() for training\n\nhistory = model.fit_generator(train_generator,\n                             steps_per_epoch = ntrain // batch_size,\n                             epochs=100,\n                             validation_data = dev_generator,\n                             validation_steps = ndev // batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Save the model to reuse it later\nmodel.save_weights('model_weights.h5')\nmodel.save('model_keras.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#lets plot graphs to get insights into accuracy and loss\n#get details from history object\n\nacc = history.history['acc']\ndev_acc = history.history['val_acc']\nloss = history.history['loss']\ndev_loss = history.history['val_loss']\n\nepochs = range(1, len(acc)+1)\n\n#train and dev accuaracy\nplt.plot(epochs, acc, 'b', label='Training accuracy')\nplt.plot(epochs, dev_acc, 'r', label='Dev accuracy')\nplt.title('Training and Dev accuracy')\nplt.legend()\nplt.figure()\n\n#train and dev loss\nplt.plot(epochs, loss, 'b', label='Training loss')\nplt.plot(epochs, dev_loss, 'r', label='Dev loss')\nplt.title('Training and Dev loss')\nplt.legend()\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Now lets predict first 10 images from test set\nX_test, y_test = read_and_process_image(test_imgs[70:80]) #y_test will be empty here cuz, test set has no label\nx = np.array(X_test)\n\ntest_datagen = ImageDataGenerator(rescale=1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Iterate through the images in test set and make predictions\ni=0\ntext_labels=[]\nplt.figure(figsize=(30,20))\nfor batch in test_datagen.flow(x, batch_size=1):\n    pred = model.predict(batch)\n    if pred > 0.5:\n        text_labels.append('dog')\n    else:\n        text_labels.append('cat')\n    plt.subplot(5 / columns+1, columns, i+1)\n    plt.title('This is a '+text_labels[i])\n    imgplot = plt.imshow(batch[0])\n    i += 1\n    if i%10==0:\n        break\nplt.show()","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":1}