{"cells":[{"metadata":{"_uuid":"fe76d1d1ded592430e7548feacfa38dc42f085d9"},"cell_type":"markdown","source":"# Import Library"},{"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\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\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":{"_uuid":"7335a579cc0268fba5d34d6f7558f33c187eedb3"},"cell_type":"markdown","source":"# Prepare Traning Data"},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"filenames = os.listdir(\"../input/train/train\")\ncategories = []\nfor filename in filenames:\n    category = filename.split('.')[0]\n    if category == 'dog':\n        categories.append(1)\n    else:\n        categories.append(0)\n\ndf = pd.DataFrame({\n    'filename': filenames,\n    'category': categories\n})\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"400a293df3c8499059d9175f3915187074efd971"},"cell_type":"markdown","source":"# See sample image"},{"metadata":{"trusted":true,"_uuid":"602b40f7353871cb161c60b5237f0da0096b2f47"},"cell_type":"code","source":"sample = random.choice(filenames)\nimage = load_img(\"../input/train/train/\"+sample)\nplt.imshow(image)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"b244e6b7715a04fc6df92dd6dfa3d35c473ca600"},"cell_type":"markdown","source":"# Build Model\n[Reference](https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html)"},{"metadata":{"trusted":true,"_uuid":"8c9f833c1441b657c779844912d0b8028218d454"},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Activation, Dropout, Flatten, Dense\n\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), input_shape=(256, 256, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(32, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(64, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n# the model so far outputs 3D feature maps (height, width, features)\n\nmodel.add(Flatten())  # this converts our 3D feature maps to 1D feature vectors\nmodel.add(Dense(64))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1))\nmodel.add(Activation('sigmoid'))\n\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"a29ebfd697dd7183a1a1345ea41ec138874340b7"},"cell_type":"markdown","source":"### Prepare Test and Train Data"},{"metadata":{"trusted":true,"_uuid":"4eeb7af8dcf02c4ef5ca744c8305c51a2f5cedef"},"cell_type":"code","source":"train_df, validate_df = train_test_split(df, test_size=0.1)\ntrain_df = train_df.reset_index()\nvalidate_df = validate_df.reset_index()\n\n# validate_df = validate_df.sample(n=10).reset_index() # use for fast testing code purpose\n# train_df = train_df.sample(n=100).reset_index() # use for fast testing code purpose\n\ntotal_train = train_df.shape[0]\nbatch_size=15","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"ff760be9104f7d9492467b8d9d3405011aa77d11"},"cell_type":"markdown","source":"# Traning Generator"},{"metadata":{"trusted":true,"_uuid":"4d1c7818703a8a4bac5c036fdea45972aa9e5e9e"},"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    horizontal_flip=True,\n    rescale=1./255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    rotation_range=20\n)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    train_df, \n    \"../input/train/train/\", \n    x_col='filename',\n    y_col='category',\n    class_mode='binary',\n    batch_size=batch_size\n)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"859c7b2857939c19fd2e3bb32839c9f7deb5aa3f"},"cell_type":"markdown","source":"### Validation Generator"},{"metadata":{"trusted":true,"_uuid":"7925e16bcacc89f4484fb6fe47e54d6420af732e"},"cell_type":"code","source":"validation_datagen = ImageDataGenerator(rescale = 1./255)\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df, \n    \"../input/train/train/\", \n    x_col='filename',\n    y_col='category',\n    class_mode='binary',\n    batch_size=batch_size\n)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"6e17fc1f002fedd60febb78fee5e81770640b909"},"cell_type":"markdown","source":"# See sample generated images"},{"metadata":{"trusted":true,"_uuid":"23d923dba747f8b47dc75569244cecc6f70df321"},"cell_type":"code","source":"plt.figure(figsize=(12, 12))\nfor X_batch, y_batch in train_generator:\n    for i in range(0, 9):\n        plt.subplot(3, 3, i+1)\n        image = X_batch[i]\n        plt.imshow(image)\n    plt.tight_layout()\n    plt.show()\n    break","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"5cd8df64e794ed17de326b613a9819e7da977a0e"},"cell_type":"markdown","source":"# Fit Model"},{"metadata":{"trusted":true,"_uuid":"0836a4cc8aa0abf603e0f96573c0c4ff383ad56b"},"cell_type":"code","source":"model.fit_generator(\n    train_generator, \n    epochs=30,\n    validation_data=validation_generator,\n    steps_per_epoch=total_train//batch_size\n)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"aa1fbc4081ae0de2993188b2bf658a0be5bc0687"},"cell_type":"markdown","source":"# Save Model"},{"metadata":{"trusted":true,"_uuid":"67575a4decdaf79a915d23151626b784ffa82642"},"cell_type":"code","source":"model.save_weights(\"model.h5\")","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"764dc66e4b2bc558f3a0f90b80bb802f5b3d45a8"},"cell_type":"markdown","source":"# Prepare Testing Data"},{"metadata":{"trusted":true,"_uuid":"c35e70d3e1e4834dbbf840fa0ea08c049bfcd915"},"cell_type":"code","source":"test_filenames = os.listdir(\"../input/test1/test1\")\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\n# test_df = test_df.sample(n=10).reset_index() \nnb_samples = test_df.shape[0]\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"291bc3996dce8d05e174b27d64f03996d3e8038e"},"cell_type":"markdown","source":"# Create Testing Generator"},{"metadata":{"trusted":true,"_uuid":"52249ec1c35fb1be3adef386be245de3794e55aa"},"cell_type":"code","source":"test_gen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_gen.flow_from_dataframe(\n    test_df, \n    \"../input/test1/test1/\", \n    x_col='filename',\n    class_mode=None,\n    batch_size=batch_size,\n    shuffle=False\n)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"2fa580afca2931ec5ce374e732d8c1789d03f2ed"},"cell_type":"markdown","source":"# Predict"},{"metadata":{"trusted":true,"_uuid":"98b41dc83075e6297137fb45bf703c313dd4ae28"},"cell_type":"code","source":"predict = model.predict_generator(test_generator, steps=np.ceil(nb_samples/batch_size)).astype('int64')\ntest_df['category'] = predict\nsample_test = test_df.sample(n=9).reset_index()\nsample_test.head()\nplt.figure(figsize=(12, 12))\nfor index, row in sample_test.iterrows():\n    filename = row['filename']\n    category = row['category']\n    img = load_img(\"../input/test1/test1/\"+filename, target_size=(256, 256))\n    plt.subplot(3, 3, index+1)\n    plt.imshow(img)\n    plt.xlabel(filename + '(' + \"{}\".format(category) + ')')\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d1ca25943e73aa20a37f9fb8670ee430caeaaf1f"},"cell_type":"markdown","source":"# Submission"},{"metadata":{"trusted":true,"_uuid":"cce9f3e2ffff0693d79d84590ed71fbbca7c3c7c"},"cell_type":"code","source":"submission_df = test_df.copy()\nsubmission_df['id'] = submission_df['filename'].str.split('.').str[0]\nsubmission_df['label'] = submission_df['category']\nsubmission_df.drop(['filename', 'category'], axis=1, inplace=True)\nsubmission_df.to_csv('submission.csv', index=False)","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}