{"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\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split\n\nimport keras\nfrom keras.models import Model\n\nfrom keras.layers import GlobalMaxPooling2D\nfrom keras.layers import Dense, Flatten, Dropout, BatchNormalization, Input\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\n\nfrom keras.applications.mobilenet import MobileNet\nfrom keras.applications.inception_v3 import InceptionV3\n\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras import backend as K\n\nimport os\n\n# Hyperparams\nIMAGE_SIZE = 96\nIMAGE_CHANNELS = 3\n\nSAMPLE_SIZE = 88800\n\nvalidation_split=0.1\n\ntrain_df = pd.read_csv(\"../input/train_labels.csv\")\n# Remove error image\ntrain_df = train_df[train_df['id'] != 'dd6dfed324f9fcb6f93f46f32fc800f2ec196be2']\n# Remove error black image\ntrain_df = train_df[train_df['id'] != '9369c7278ec8bcc6c880d99194de09fc2bd4efbe']\n\ntrain_df['filename'] = train_df['id'] + \".tif\"\ntrain_df['class'] = train_df['label']\ntrain_df['class'] = train_df['class'].apply(str)\n\n# test_df = pd.DataFrame({'filename':os.listdir(test_data_dir)})\n\nnb_train_samples = train_df.shape[0] - train_df.shape[0]*validation_split\nnb_validation_samples = nb_train_samples*validation_split\n\nif K.image_data_format() == 'channels_first':\n    input_shape = (3, IMAGE_SIZE, IMAGE_SIZE)\nelse:\n    input_shape = (IMAGE_SIZE, IMAGE_SIZE, 3)\n    \ntrain_data_dir = '../input/train'\ntest_data_dir = '../input/test'","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"train_batch_size = 64\nval_batch_size = 32\n\ntrain_datagen = ImageDataGenerator(rescale=1./255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    channel_shift_range=0.2,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    horizontal_flip=True,\n    rotation_range=45,\n    fill_mode='reflect',\n    vertical_flip=True,\n    validation_split=validation_split)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe = train_df,\n    directory = train_data_dir,\n    target_size = (IMAGE_SIZE, IMAGE_SIZE),\n    shuffle=True,\n    batch_size=train_batch_size,\n    subset=\"training\",\n    class_mode = 'binary')\n\nvalid_generator = train_datagen.flow_from_dataframe(\n    dataframe=train_df,\n    directory=train_data_dir,\n    target_size = (IMAGE_SIZE, IMAGE_SIZE),\n    shuffle=False,\n    batch_size=val_batch_size,\n    subset=\"validation\",\n    class_mode = 'binary')\n\n\ntrain_steps = np.ceil(train_generator.samples // train_batch_size)\nval_steps = np.ceil(valid_generator.samples // val_batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"70b628390dcf3d9b223164feb388a04672d8caeb","scrolled":true},"cell_type":"code","source":"from keras.layers import GaussianNoise\nfrom keras.layers import Concatenate, GlobalMaxPooling2D, Activation\n\ninput_shape = (IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNELS)\ninput = Input(shape=input_shape)\n# corr_input = GaussianNoise(1.0)(input)\n\nbase_model = MobileNet(input_tensor=input, include_top=False, weights=\"imagenet\")\n# base_model = InceptionV3(input_tensor=input, weights=\"imagenet\", include_top=False)\n\nout = Dropout(0.5)(base_model.output)\nout = Conv2D(1, kernel_size=(3, 3), padding=\"valid\", activation=\"sigmoid\")(out)\nout = Flatten()(out)\n# out = Activation('sigmoid')(out)\n\nmodel = Model(inputs=base_model.inputs, outputs=out)\n\n# serialize model to JSON\nmodel_json = model.to_json()\nwith open(\"model.json\", \"w\") as json_file:\n    json_file.write(model_json)\n    \n    \nprint(\"Done\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cb14a7755382f7689bc36efbddfc71451cade090","scrolled":false},"cell_type":"code","source":"model.compile(loss=keras.losses.binary_crossentropy, optimizer=keras.optimizers.Adam(lr=0.0001), metrics=['accuracy'])\n# model.compile(loss=keras.losses.binary_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"79a98870cbe9c2adaea707797924126654df59ce","scrolled":true},"cell_type":"code","source":"from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau\nreduce_lr = ReduceLROnPlateau(monitor='val_acc', factor=0.5, patience=2, verbose=1, mode='max', min_lr=0.00000001)\ncheckpoint = ModelCheckpoint(\"model_best.h5\", monitor='val_acc', verbose=1, save_best_only=True, mode='max')\nhistory = model.fit_generator(train_generator, steps_per_epoch=train_steps, validation_data=valid_generator, \n                              validation_steps=val_steps, epochs=15, verbose=1, callbacks=[reduce_lr, checkpoint])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"89f4d6b1dfba227bec43ccbd570ccd844ea566a6"},"cell_type":"code","source":"model.load_weights(\"model_best.h5\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ac43c55ef47219f7849480aa606e36bd39597fd1"},"cell_type":"code","source":"df_test = pd.DataFrame({'id':os.listdir(test_data_dir)})\ndf_test['id'] = [f.split(sep='.')[0] for f in df_test['id']]\ndf_test['filename'] = df_test['id'] + \".tif\"\n\ntest_batch_size = 2\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_datagen.flow_from_dataframe(\n    dataframe=df_test,\n    directory=test_data_dir,\n    target_size = (IMAGE_SIZE, IMAGE_SIZE),\n    shuffle=False,\n    batch_size=test_batch_size,\n    class_mode = None)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"58bef9b694d6451169f45ff304e3af9381b6d2f5"},"cell_type":"code","source":"test_steps = test_generator.samples / test_batch_size\ntest_generator.reset()\npred = model.predict_generator(test_generator, steps=test_steps, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"57e59950bdcac7ef12685f654f085799ce2e747a"},"cell_type":"code","source":"df_preds = pd.DataFrame(pred, columns=['label'])\n\ntest_filenames = test_generator.filenames\ndf_preds['file_names'] = test_filenames\n\ndef extract_id(x):\n    # split into a list\n    a = x.split('/')\n    # split into a list\n    b = a[0].split('.')\n    extracted_id = b[0]\n\n    return extracted_id\n\n\ndf_preds['id'] = df_preds['file_names'].apply(extract_id)\ny_pred = df_preds['label']\nimage_id = df_preds['id']\n\nsubmission = pd.DataFrame({'id': image_id, 'label': y_pred, }).set_index('id')\nsubmission.to_csv('preds.csv', columns=['label'])\n\nprint(\"Done\")\n\ndf_preds.head()","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}