{"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\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 read-only \"../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\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import os, cv2, re, random\nimport numpy as np\nimport pandas as pd\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing.image import img_to_array, load_img\nfrom keras import layers, models, optimizers\nfrom keras import backend as K\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils.np_utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, AvgPool2D, BatchNormalization, Reshape\nfrom keras.callbacks import LearningRateScheduler\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import zipfile\n\nDataset = \"dogs-vs-cats-redux-kernels-edition\"\n\n# Will unzip the files so that you can see them..\nwith zipfile.ZipFile(\"/kaggle/input/\"+Dataset+\"/train\"+\".zip\",\"r\") as z:\n    z.extractall(\".\")\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with zipfile.ZipFile(\"/kaggle/input/\"+Dataset+\"/test\"+\".zip\",\"r\") as z:\n    z.extractall(\".\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from subprocess import check_output\nprint(check_output([\"ls\", \"./\"]).decode(\"utf8\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAIN_DIR='./train/'\nTEST_DIR='./test/'\ntrain_images_dogs_cats = [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR)]\ntest_images_dogs_cats = [TEST_DIR+i for i in os.listdir(TEST_DIR)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from matplotlib.image import imread\n\nfolder = './train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tplt.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'cat.' + str(i) + '.jpg'\n\t#print(filename)\n\timage = imread(filename)\n\t#print(image)\n\tplt.imshow(image)\n# show the figure\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def atoi(text):\n    return int(text) if text.isdigit() else text\n\ndef natural_keys(text):\n    return [ atoi(c) for c in re.split('(\\d+)', text) ]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_images_dogs_cats.sort(key=natural_keys)\ntrain_images_dogs_cats = train_images_dogs_cats[0:1300] + train_images_dogs_cats[12500:13800] \n\ntest_images_dogs_cats.sort(key=natural_keys)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train_images_dogs_cats)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_width = 150\nimg_height = 150\ndef prepare_data(list_of_images):\n    \"\"\"\n    Returns two arrays: \n        x is an array of resized images\n        y is an array of labels\n    \"\"\"\n    x = [] # images as arrays\n    y = [] # labels\n    \n    for image in list_of_images:\n        #i=cv2.imread(image)\n        #print(i)\n        #cv2.imshow('test',i)\n        x.append(cv2.resize(cv2.imread(image), (img_width,img_height), interpolation=cv2.INTER_CUBIC))\n    \n    for i in list_of_images:\n        if 'dog' in i:\n            y.append(1)\n        elif 'cat' in i:\n            y.append(0)\n        #else:\n            #print('neither cat nor dog name present in images')\n            \n    return x, y","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X, Y = prepare_data(train_images_dogs_cats)\nprint(K.image_data_format())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_val, Y_train, Y_val = train_test_split(X,Y, test_size=0.2, random_state=1)\nnb_train_samples = len(X_train)\nnb_validation_samples = len(X_val)\nbatch_size = 16","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.applications.vgg16 import VGG16\nfrom keras.models import Model\nfrom keras.optimizers import SGD\nmodel = VGG16(include_top=False, input_shape=(img_width, img_height, 3))\nfor layer in model.layers:\n    layer.trainable = False\n# add new classifier layers\nflat1 = Flatten()(model.layers[-1].output)\nclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\noutput = Dense(1, activation='sigmoid')(class1)\n# define new model\nmodel = Model(inputs=model.inputs, outputs=output)\n# compile model\nopt = SGD(lr=0.001, momentum=0.9)\nmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\nmodel.summary()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rescale=1. / 255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True)\n\nval_datagen = ImageDataGenerator(\n    rescale=1. / 255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True)\ntrain_generator = train_datagen.flow(np.array(X_train), Y_train, batch_size=batch_size)\nvalidation_generator = val_datagen.flow(np.array(X_val), Y_val, batch_size=batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(\n    train_generator, \n    steps_per_epoch=nb_train_samples // batch_size,\n    epochs=7,\n    validation_data=validation_generator,\n    validation_steps=nb_validation_samples // batch_size\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save_weights('model_wieghts.h5')\nmodel.save('model_keras.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_test, Y_test = prepare_data(test_images_dogs_cats)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1. / 255)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_generator = val_datagen.flow(np.array(X_test), batch_size=batch_size)\nprediction_probabilities = model.predict_generator(test_generator, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"counter = range(1, len(test_images_dogs_cats) + 1)\nsolution = pd.DataFrame({\"id\": counter, \"label\":list(prediction_probabilities)})\ncols = ['label']\n\nfor col in cols:\n    solution[col] = solution[col].map(lambda x: str(x).lstrip('[').rstrip(']')).astype(float)\n\nsolution.to_csv(\"dogsVScats.csv\", index = False)","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}