{"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\nprint(os.listdir(\"../input\"))\n\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":"from keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import GlobalAveragePooling2D\nfrom keras.layers import Activation, Dropout, Flatten, Dense, Conv2D, Input, MaxPooling2D\nfrom keras import optimizers\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom keras.models import Model\n\nimport pandas as pd\nimport numpy as np\nimport gc\nimport cv2 as cv\nfrom tqdm import tqdm\nfrom sklearn.utils import shuffle","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"bd140f99d8d1f3d68a6eaa44d44f692092bc9d92"},"cell_type":"code","source":"all_images = os.listdir('../input/train')\ncat = [x for x in all_images if(x.split('.')[0]=='cat')]\ndog = [x for x in all_images if(x.split('.')[0]=='dog')]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c9a559d59b76281e335e75b0924ce8293951d628"},"cell_type":"code","source":"(img_width, img_height) = (200, 200)\ninput_shape = (img_width, img_height, 3)\ndef get_images(files):\n    images = []\n    labels = []\n    #cat = 0, dog = 1\n    for img in tqdm(files):\n        if 'cat' in img:\n            labels.append(0)\n        else:\n            labels.append(1)\n\n        path = os.path.join('../input/train', img)    \n        i = cv.imread(path)\n        i = cv.resize(i, (img_width, img_height))\n        images.append(i)\n    return np.array(images), labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6c336f65559b8343d56c856b80b97778c6441a23"},"cell_type":"code","source":"train = cat[:1000]\ntrain.extend(dog[:1000])\ntrain_images, train_labels = get_images(train)\n\nval = cat[1000:1300]\nval.extend(dog[1000:1300])\nval_images, val_labels = get_images(val)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3d57fa2fade9cdd6d3acb9b46ce53ed406c245bb"},"cell_type":"code","source":"train_images, train_labels = shuffle(train_images, train_labels, random_state = 0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d91af69186809c632842893d641a0401470073fa"},"cell_type":"code","source":"# this is the augmentation configuration we will use for training\ntrain_datagen = ImageDataGenerator(width_shift_range=0.2, height_shift_range=0.2,\n    rescale=1. / 255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True, rotation_range = 20)\n\nval_datagen = ImageDataGenerator(rescale=1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true,"_uuid":"03c7dfef939268f5d4b749379d5023724c3a3bc7"},"cell_type":"code","source":"train_datagen.fit(train_images)\nval_datagen.fit(val_images)\n\ndef conv2d(last_layer, kernels, drop=True, drop_rate=0.2):\n    x = Conv2D(kernels, (3, 3), activation='relu')(last_layer)\n    x = Conv2D(kernels, (3, 3), activation='relu')(x)\n    x = MaxPooling2D(strides=(2,2))(x)\n    if drop:\n        x = Dropout(drop_rate)(x)\n        return x\n    return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"64243f31806e58467d0810f77055d5811cb44215"},"cell_type":"code","source":"input1 = Input(shape=input_shape)\nx = conv2d(input1, 32)\nx = conv2d(x, 64)\n# x = conv2d(x, 128)\nflat = Flatten()(x)\ndense = Dense(32, activation='relu')(flat)\nout = Dense(1, activation='sigmoid')(dense)\n\nmodel = Model(inputs = [input1], outputs = [out])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3d8912306ca535dedd732b70ebec71b390925e4b"},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fa84263afdcae976d03340d1fdfcf5955219238a"},"cell_type":"code","source":"# opt = optimizers.SGD(lr=0.01, decay = 1e-6, momentum = 0.9, nesterov = True)\n# opt = optimizers.Adam(lr=0.01, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\nopt = optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=None, decay=0.0)\nmodel.compile(opt, loss = 'binary_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6c96bbaea2dfdf2b1bdd376d20e6ebeb385cbc0a"},"cell_type":"code","source":"epoch = 50\nbatch_size = 8*2\nmodel.fit_generator(train_datagen.flow(train_images, train_labels, batch_size=batch_size),                     \n                    steps_per_epoch=len(train_images) / batch_size, epochs=epoch,\n                    validation_data=val_datagen.flow(val_images, val_labels, batch_size=batch_size), \n                    validation_steps = len(val_images)/batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b8833696a752e7cd7f3607800836ba3a20b4bbc1"},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}