{"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 20GB 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":{"trusted":true},"cell_type":"code","source":"!pip install segmentation_models -q\n%env SM_FRAMEWORK=tf.keras","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nimport segmentation_models as sm\nimport os\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom zipfile import ZipFile\nfrom PIL import Image\nfrom sklearn.model_selection import train_test_split\nimport albumentations as A\nimport gc","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Import tiled images"},{"metadata":{"trusted":true},"cell_type":"code","source":"# import data tiles (iafoss 512x512)\n\nimage_zip = '../input/iafoss-512x512/train.zip'\nmask_zip = '../input/iafoss-512x512/masks.zip'\n\nimage_store = '../kaggle/working/train/'\nmask_store = '../kaggle/working/masks/'\n\nwith ZipFile(image_zip, 'r') as imgs:\n    imgs.extractall(image_store)\n\nwith ZipFile(mask_zip, 'r') as masks:\n    masks.extractall(mask_store)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAIN_TILES = []\nTRAIN_MASKS = []\n\nfor tile in os.listdir(image_store):\n    TRAIN_TILES.append(np.asarray(Image.open(image_store + tile)))\n\nfor mask in os.listdir(mask_store):\n    TRAIN_MASKS.append(np.asarray(Image.open(mask_store + mask)))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data augmentation"},{"metadata":{"trusted":true},"cell_type":"code","source":"# define image augmentation steps\naug = A.Compose([# A.Normalize(mean=(0.6627, 0.5120, 0.6972), std=(0.1804, 0.2560, 0.1648),\n                 #             max_pixel_value=255.0, always_apply=False, p=1.0),\n                 A.OneOf([A.RandomRotate90(),\n                          A.HorizontalFlip(),\n                          A.VerticalFlip()], p=0.8),\n                 A.OneOf([A.RandomBrightnessContrast(),\n                          A.HueSaturationValue()], p=0.3)])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"aug = [aug(image=img, mask=mask) for (img, mask) in list(zip(TRAIN_TILES, TRAIN_MASKS))]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = [img['image'] for img in aug]\nY = [mask['mask'] for mask in aug]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = np.asarray(X)\nY = np.asarray(Y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del TRAIN_TILES, TRAIN_MASKS, aug\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Build Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"BACKBONE = 'resnet34'\nBATCH_SIZE = 16\nEPOCHS = 30","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preprocess_input = sm.get_preprocessing(BACKBONE)","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=15)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del X, Y\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_TRAIN = preprocess_input(X_TRAIN)\nX_VAL = preprocess_input(X_VAL)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def dice_coe(output, target, axis = None, smooth=1e-10):\n    output = tf.dtypes.cast( tf.math.greater(output, 0.5), tf. float32 )\n    target = tf.dtypes.cast( tf.math.greater(target, 0.5), tf. float32 )\n    inse = tf.reduce_sum(output * target, axis=axis)\n    l = tf.reduce_sum(output, axis=axis)\n    r = tf.reduce_sum(target, axis=axis)\n\n    dice = (2. * inse + smooth) / (l + r + smooth)\n    dice = tf.reduce_mean(dice, name='dice_coe')\n    return dice","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = sm.Unet(BACKBONE, encoder_weights='imagenet')\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=[dice_coe])\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"check = tf.keras.callbacks.ModelCheckpoint(filepath='/kaggle/working/alina_resnet34.h5', verbose=1,\n                                           save_best_only=True)\n\nearly_stop = tf.keras.callbacks.EarlyStopping(patience=7, monitor='val_dice_coe', mode='max',\n                                              restore_best_weights=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(X_TRAIN, Y_TRAIN, batch_size=BATCH_SIZE, epochs=EPOCHS,\n                    callbacks=[check, early_stop], validation_data=(X_VAL, Y_VAL))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot training and validation loss\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(loss)+1)\nplt.plot(epochs, loss, 'y', label='Training Loss')\nplt.plot(epochs, val_loss, 'r', label='Validation Loss')\nplt.title('Training and Validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save('alina_resnet34.h5')","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}