{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"'''\nUnzip Commands:\n!unzip ../input/dogs-vs-cats-redux-kernels-edition/test.zip\n!unzip ../input/dogs-vs-cats-redux-kernels-edition/train.zip\n'''\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport os\nimport random\nimport gc\nimport matplotlib.image as mpimg\n\ntrainDir = './train'\ntestDir = './test'\n\ntrainDogs = ['./train/{}'.format(i) for i in os.listdir(trainDir) if 'dog' in i]\ntrainCats = ['./train/{}'.format(i) for i in os.listdir(trainDir) if 'cat' in i]\n\ntestImages = ['./test/{}'.format(i) for i in os.listdir(testDir)]\n\ntrainImages = trainDogs[:2000] + trainCats[:2000]\nrandom.shuffle(trainImages)\n\ndel trainDogs\ndel trainCats\ngc.collect()\n\ndef displayUnprocessedimages():\n    for image in trainImages[0:3]:\n        image = mpimg.imread(image)\n        imagePlot = plt.imshow(image)\n        plt.show()\n    \nnrows = 150\nncolumns = 150\nchannels = 3\n\ndef readAndProcess(imagesListInput):\n    imagesListOutput = []\n    labelsListOutput = []\n    \n    for image in imagesListInput:\n        imagesListOutput.append(cv2.cvtColor((cv2.resize(cv2.imread(image, cv2.IMREAD_COLOR), (nrows, ncolumns), interpolation = cv2.INTER_CUBIC)), cv2.COLOR_BGR2RGB))\n        if 'dog' in image:\n            labelsListOutput.append(1)\n        elif 'cat' in image:\n            labelsListOutput.append(0)\n            \n    return imagesListOutput, labelsListOutput\n\nx, y = readAndProcess(trainImages)\n\nplt.figure(figsize = (20, 10))\ncolumns = 5\n\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":"#Output number of labels (1, 0), should be 2000 of each\n\nimport seaborn as sns\ndel trainImages\ngc.collect()\n\nx = np.array(x)\ny = np.array(y)\n\nsns.countplot(y)\nplt.title('Labels for Cats & Dogs')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Output array shape, for Keras model\n#e.g. (4000, 150, 150, 3) = 400 Images, with resolution of 150x150, with RGB channels\nprint (\"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":"#Split data into train and test sets\nfrom sklearn.model_selection import train_test_split\nxTrain, xVal, yTrain, yVal = train_test_split(x, y, test_size = 0.2, random_state = 2)\n\nprint (\"Shape of train images is:\", xTrain.shape)\nprint (\"Shape of validation images is:\", xVal.shape)\nprint (\"Shape of labels is:\", yTrain.shape)\nprint (\"Shape of labels is:\", yVal.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del x\ndel y\ngc.collect()\n\nnTrain = len(xTrain)\nnVal = len(xVal)\n\nbatchSize = 32\n\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\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(64, (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))\nmodel.add(layers.Dense(512, activation = 'relu'))\nmodel.add(layers.Dense(1, activation = 'sigmoid'))\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss = 'binary_crossentropy', optimizer = optimizers.RMSprop(lr = 1e-4), metrics = ['acc'])\n\ntrainDatagen = ImageDataGenerator(rescale = 1./255,\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\nval_datagen = ImageDataGenerator(rescale = 1./255)","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}