{"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":{"trusted":true},"cell_type":"code","source":"print(os.listdir(\"../input/train\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg16 import preprocess_input\nfrom keras.preprocessing import image\nfrom keras.models import Sequential, Model, load_model\nfrom keras.layers import Input, Dropout, Flatten, Convolution2D, MaxPooling2D, Dense, Activation\nimport numpy as np\nfrom keras.datasets import mnist\n\nimport os, cv2, random\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import ticker\nimport seaborn as sns\n%matplotlib inline \n\nfrom keras.optimizers import RMSprop\nfrom keras.callbacks import ModelCheckpoint, Callback, EarlyStopping\nfrom keras.utils import np_utils\n\nfrom keras import backend as K","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = VGG16(include_top=True, weights='imagenet', input_tensor=None)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def read_image(file_path):\n    img = cv2.imread(file_path, cv2.IMREAD_COLOR) #cv2.IMREAD_GRAYSCALE\n    img =cv2.resize(img, (224, 224), interpolation=cv2.INTER_CUBIC)\n    img=cv2.cvtColor(file, cv2.COLOR_BGR2RGB)\n\n    return np.array(img).reshape((3,224,224))\n\n\ndef prep_data(images):\n    count = len(images)\n    data = np.ndarray((count, ROWS, COLS,CHANNELS), dtype=np.uint8)\n\n    for i, image_file in enumerate(images):\n        image = read_image(image_file)\n        data[i] = image.T\n        if i%250 == 0: print('Processed {} of {}'.format(i, count))\n    \n    return data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAIN_DIR = \"../input/train/\"\nTEST_DIR = '../input/test/'\nROWS = 224\nCOLS = 224\nCHANNELS = 3\ntrain_images = [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR)] # use this for full dataset\ntrain_dogs =   [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR) if 'dog.' in i]\ntrain_cats =   [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR) if 'cat.' in i]\n\ntest_images =  [TEST_DIR+i for i in os.listdir(TEST_DIR)]\n\n# slice datasets for memory efficiency on Kaggle Kernels, delete if using full dataset\ntrain_images = train_dogs[:1000] + train_cats[:1000]\nrandom.shuffle(train_images)\ntest_images =  test_images[:25]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def read_image(file_path):\n    img = cv2.imread(file_path, cv2.IMREAD_COLOR) #cv2.IMREAD_GRAYSCALE\n    img =cv2.resize(img, (224, 224), interpolation=cv2.INTER_CUBIC)\n    img=cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n    return np.array(img).reshape((3,224,224))\n\n\ndef prep_data(images):\n    count = len(images)\n    data = np.ndarray((count, ROWS, COLS,CHANNELS), dtype=np.uint8)\n\n    for i, image_file in enumerate(images):\n        image = read_image(image_file)\n        data[i] = image.T\n        if i%250 == 0: print('Processed {} of {}'.format(i, count))\n    \n    return data\n\n\ntrain = prep_data(train_images)\ntest = prep_data(test_images)\n\nprint(\"Train shape: {}\".format(train.shape))\nprint(\"Test shape: {}\".format(test.shape))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.input_shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels = []\nfor i in train_images:\n    if 'dog.' in i:\n        labels.append(1)\n    else:\n        labels.append(0)\n\nsns.countplot(labels)\nplt.title('Cats and Dogs')\nfrom keras.utils import to_categorical\nlabels = to_categorical(labels)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def show_cats_and_dogs(idx):\n    dog = read_image(train_dogs[idx])\n    dog = np.array(dog).reshape((224,224,3))\n\n    cat = read_image(train_cats[idx])\n    cat = np.array(cat).reshape((224,224,3))\n\n    pair = np.concatenate((cat, dog), axis=1)\n    plt.figure(figsize=(10,5))\n    plt.imshow(pair)\n    plt.show()\n    \nfor idx in range(0,2):\n    show_cats_and_dogs(idx)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Create a New Model based on ResNEt50 \ninput_shape = (224, 224, 3)\n\nK.set_learning_phase(1)\nbase_model = VGG16(weights='imagenet', include_top=True, input_shape=input_shape)\nbase_model.layers.pop() #ILIMINA LA ULTIMA CAPA\nbase_model.outputs = [base_model.layers[-1].output] #LE DEFINO QUE LA ULTIMA CAPA AHORA ES SALIDA\nbase_model.layers[-1].outbound_nodes = []\n\nx = base_model.layers[-1].output\n#x = Flatten(name='flatten')(x)\npredictions = Dense(2, activation='softmax', name='predictions')(x)\nmodel_01 = Model(inputs=base_model.input, outputs=predictions)\n\noptimizer = RMSprop(lr=1e-4)\nmodel_01.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nb_epoch = 15\nbatch_size = 10\n\n## Callback for loss logging per epoch\nclass LossHistory(Callback):\n    def on_train_begin(self, logs={}):\n        self.losses = []\n        self.val_losses = []\n        \n    def on_epoch_end(self, batch, logs={}):\n        self.losses.append(logs.get('loss'))\n        self.val_losses.append(logs.get('val_loss'))\n\nearly_stopping = EarlyStopping(monitor='val_loss', patience=2, verbose=1, mode='auto')        \n        \ndef run_catdog():\n    \n    history = LossHistory()\n    model_01.fit(x=train, y=labels, batch_size=batch_size, nb_epoch=nb_epoch,\n              validation_split=0.25, verbose=0, shuffle=True, callbacks=[history, early_stopping])\n    \n\n    predictions = model_01.predict(test, verbose=0)\n    return predictions, history\n\npredictions, history = run_catdog()","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}