{"cells":[{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPool2D, Dropout, Dense, Flatten\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split\nfrom keras.preprocessing.image import ImageDataGenerator\nimport matplotlib.pyplot as plt\nimport os, cv2, random\nimport pandas as pd\nimport numpy as np\ntf.random.set_seed(1)\nnp.random.seed(1)\n\nTRAIN_DIR = 'train/'\nTEST_DIR = 'test/'\nIMG_SIZE = 64\nCHANNELS = 3  # 1 for cv2.IMREAD_GRAYSCALE\nBATCH_SIZE = 32\n\nclass_names = ('cat', 'dog')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Unzip data\nos.system('unzip ../input/dogs-vs-cats-redux-kernels-edition/train.zip')\nos.system('unzip ../input/dogs-vs-cats-redux-kernels-edition/test.zip')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# For full dataset uncomment\ntrain_images = [TRAIN_DIR + i for i in os.listdir(TRAIN_DIR)]\ntest_images = [TEST_DIR + i for i in os.listdir(TEST_DIR)]\n\n#train_images = [TRAIN_DIR + i for i in os.listdir(TRAIN_DIR)[:100]]\n#test_images = [TEST_DIR + i for i in os.listdir(TEST_DIR)[:100]]\n\nrandom.shuffle(train_images)\n\nprint(f'Loaded {len(train_images)} train images')\nprint(f'Loaded {len(test_images)} test images')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def read_img(path):\n    img = cv2.imread(path, cv2.IMREAD_COLOR)  # cv2.IMREAD_GRAYSCALE\n    return cv2.resize(img, (IMG_SIZE, IMG_SIZE), interpolation=cv2.INTER_CUBIC)\n\n\ndef prep_data(images, test_data=False):\n    count = len(images)\n    if test_data:\n        data = np.ndarray((count, IMG_SIZE, IMG_SIZE, CHANNELS), dtype=np.float16)\n    else:\n        data = np.ndarray((count, IMG_SIZE, IMG_SIZE, CHANNELS), dtype=np.uint8)\n\n    for i, image_file in enumerate(images):\n        img = read_img(image_file)\n        data[i] = img\n\n    return data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train = prep_data(train_images)\ny_train = [1 if 'dog' in image_path else 0 for image_path in train_images]\n\ndel train_images\n\ny_train = np.array(y_train, dtype=np.uint8)\n\nx_train, x_test, y_train, y_test = train_test_split(x_train, y_train, test_size=0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu', input_shape=x_train.shape[1:]))\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(128, (3, 3), padding='same', activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(128, (3, 3), padding='same', activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(256, (3, 3), padding='same', activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dropout(0.4))\nmodel.add(Dense(1, activation='sigmoid'))\n\n\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n\nhistory = model.fit(x_train, y_train, batch_size=BATCH_SIZE, epochs=40, validation_data=(x_test, y_test), verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Save model\n#model.save('my_model_image_generated')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Load model\n#model = keras.models.load_model('my_model_image_generated')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot val & acc\nfig, ax = plt.subplots(2,1)\n\nax[0].plot(history.history['loss'], color='b', label=\"Training loss\")\nax[0].plot(history.history['val_loss'], color='r', label=\"Validation loss\")\nlegend = ax[0].legend(loc='best', shadow=True)\n\nax[1].plot(history.history['accuracy'], color='b', label=\"Training accuracy\")\nax[1].plot(history.history['val_accuracy'], color='r', label=\"Validation accuracy\")\nlegend = ax[1].legend(loc='best', shadow=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(\n        featurewise_center=False,  # set input mean to 0 over the dataset\n        samplewise_center=False,  # set each sample mean to 0\n        featurewise_std_normalization=False,  # divide inputs by std of the dataset\n        samplewise_std_normalization=False,  # divide each input by its std\n        zca_whitening=False,  # apply ZCA whitening\n        rotation_range=25,  # randomly rotate images in the range (degrees, 0 to 180)\n        zoom_range = 0.2, # Randomly zoom image\n        width_shift_range=0.2,  # randomly shift images horizontally (fraction of total width)\n        height_shift_range=0.2,  # randomly shift images vertically (fraction of total height)\n        horizontal_flip=True,  # randomly flip images\n        vertical_flip=False)  # randomly flip images\n\ndatagen.fit(x_train)\n\nhistory = model.fit_generator(\n    datagen.flow(x_train, y_train, batch_size=BATCH_SIZE),\n    epochs=40,\n    validation_data=(x_test, y_test),\n    verbose=1,\n    steps_per_epoch=x_train.shape[0] // BATCH_SIZE)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_test = prep_data(test_images)\nresults = model.predict(x_test)\n\nresults = np.round(results)\nseries = pd.Series(results[i][0] for i in range(len(results)))\nseries = pd.Series(series, name='label')\n\nsubmission = pd.concat([pd.Series(range(1,12501), name = \"id\"), series], axis = 1)\n\nsubmission.to_csv(\"submission.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":1}