{"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\n#for 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":{},"cell_type":"markdown","source":"## Links\n\n#### Dice coefficient\n- https://towardsdatascience.com/how-accurate-is-image-segmentation-dd448f896388\n\n#### Keras data generators and how to use them\n- https://towardsdatascience.com/keras-data-generators-and-how-to-use-them-b69129ed779c\n\n#### How to Configure Image Data Augmentation in Keras\n- https://machinelearningmastery.com/how-to-configure-image-data-augmentation-when-training-deep-learning-neural-networks/\n\n#### Deep dive into multi-label classification..! (With detailed Case Study)\n- https://towardsdatascience.com/journey-to-the-center-of-multi-label-classification-384c40229bff\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"#_______________________________________________\n# Charegement des libraries Keras \n#\nfrom tensorflow.keras.models import Sequential\n### Conv2d pour des photos - 2D si Video ou coleur alors 3D \nfrom  tensorflow.keras.layers import Conv2D\n### Pour la phse de Pooling 2D si  couleur ou Videos alors 3D\nfrom  tensorflow.keras.layers import MaxPooling2D\n### Etape 3 - Applatir dans un vector Vertical \nfrom  tensorflow.keras.layers import Flatten\n### Dense pour ajouter des couches connectées.\nfrom  tensorflow.keras.layers import Dense\n### Droput si necessaire\nfrom tensorflow.keras.layers import MaxPool2D,Dropout\n### import Metrics\nfrom  tensorflow.keras.metrics import *\n#import keras","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#from tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras import backend\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.optimizers import Adam,RMSprop\nfrom  tensorflow.keras.metrics import *\nfrom tensorflow.keras import Model\n#from keras import backend as \nfrom tensorflow.keras.callbacks import Callback, ReduceLROnPlateau, ModelCheckpoint, EarlyStopping\n\n## With Regularization\nfrom tensorflow.keras import regularizers, optimizers","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras import Input\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import BatchNormalization\nfrom keras.models import Model\nfrom tensorflow.keras.layers import Activation","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras \nfrom keras import backend as K","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.python.client import device_lib\nprint(device_lib.list_local_devices())","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## DICE Coefficient \n- https://towardsdatascience.com/how-accurate-is-image-segmentation-dd448f896388"},{"metadata":{"trusted":true},"cell_type":"code","source":"def dice_metric(inputs, target):\n    intersection = 2.0 * (target * inputs).sum()\n    union = target.sum() + inputs.sum()\n    if target.sum() == 0 and inputs.sum() == 0:\n        return 1.0\n\n    return intersection / union\n\ndef dice_loss(inputs, target):\n    num = target.size(0)\n    inputs = inputs.reshape(num, -1)\n    target = target.reshape(num, -1)\n    smooth = 1.0\n    intersection = (inputs * target)\n    dice = (2. * intersection.sum(1) + smooth) / (inputs.sum(1) + target.sum(1) + smooth)\n    dice = 1 - dice.sum() / num\n    return dice\n\ndef bce_dice_loss(inputs, target):\n    dicescore = dice_loss(inputs, target)\n    bcescore = nn.BCELoss()\n    bceloss = bcescore(inputs, target)\n\n    return bceloss + dicescore","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def dice_coeff(y1, y2):\n    y1 = Flatten(y1)\n    y2 = Flatten(y2)\n    return (2 * tf.sum(y1 * y2) + smothness) / (tf.sum(y1) + tf.sum(y2) + smothness)\n\ndef dice_coeff_loss(y1, y2):\n    return -dice_coeff(y1, y2)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## IOU - Intersection over Union (Jacard Index)\n- https://towardsdatascience.com/metrics-to-evaluate-your-semantic-segmentation-model-6bcb99639aa2#:~:text=Simply%20put%2C%20the%20IoU%20is,the%20image%20to%20the%20left."},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nfrom keras import backend as K\ndef iou_coef(y_true, y_pred, smooth=1):\n    intersection = K.sum(K.abs(y_true * y_pred), axis=[1,2,3])\n    union = K.sum(y_true,[1,2,3])+K.sum(y_pred,[1,2,3])-intersection\n    iou = K.mean((intersection + smooth) / (union + smooth), axis=0)\n    return iou","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nimport os, sys, math\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport cv2\nfrom imgaug import augmenters as iaa\nfrom tqdm import tqdm\nfrom tqdm import tqdm_notebook\nimport random","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Load datasets X_train, X_Val, X_test"},{"metadata":{"trusted":true},"cell_type":"code","source":"#30*16/60 = 8h\n#x_test = np.load('../input/x-test-numpy/x_test.npy')\n#x_train_sample_hflip = np.load('../input/trainvalsamplehflip/x_train_sample_hflip.npy' )\n#y_train_sample = np.load('../input/trainvalsamplehflip/y_train_sample.npy' )\nx_train_sample = np.load('../input/train-sample-stack/X_train_stack.npy' )\ny_train_sample = np.load('../input/train-sample-stack/y_train_stack.npy' )\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_val_sample  = np.load('../input/trainvalsamplehflip/x_val_sample_hflip.npy')\ny_val_sample = np.load('../input/trainvalsamplehflip/y_val_sample.npy')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train_rgby = pd.read_csv('../input/train-data-rgby/train_data_rgby.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.set_option('display.max_colwidth', None) \ndf_train_rgby.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def reduce_mem_usage(df):\n    \"\"\" iterate through all the columns of a dataframe and modify the data type\n        to reduce memory usage.        \n    \"\"\"\n    start_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n    \n    for col in df.columns:\n        col_type = df[col].dtype\n        \n        if col_type != object:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n        else:\n            df[col] = df[col].astype('category')\n\n    end_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n    \n    return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train_rgby = reduce_mem_usage(df_train_rgby)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data_sample = df_train_rgby.sample(frac=0.12, replace=True, random_state = 10)\ntrain_data_sample.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train_sample.shape, y_train_sample.shape, ##x_val_sample.shape, y_val_sample.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#mean = np.mean(x_train_sample_hflip)\n#std = np.std(x_train_sample_hflip)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#x_train_sample_hflip -= mean\n#x_train_sample_hflip /= std","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import gc\n%who DataFrame\n#del training_set\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#y_train_mask.shape\n#np.save('./y_train_mask_all.npy', y_train_mask)\n#y_train_mask_5000 = np.load('../input/np-train-5000/y_train_mask_5000.npy')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#img = cv2.imread('../input/hpa-single-cell-image-classification/train/fa8b0e78-bbb1-11e8-b2ba-ac1f6b6435d0_blue.png')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#('../input/hpa-single-cell-image-classification/train/fa8b0e78-bbb1-11e8-b2ba-ac1f6b6435d0_blue.png')[-7:]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inp = Input(shape = (128,128,4))\nx = tf.keras.layers.BatchNormalization( momentum=0.98, epsilon=0.0001,)(inp)\nx = Conv2D(128, (3, 3), padding = 'same')(x)\nx = Activation('relu')(x)\nx = Dropout(0.15)(x)\nx = Conv2D(32, (3, 3))(x)\nx = Activation('relu')(x)\nx = MaxPooling2D(pool_size = (2, 2))(x)\nx = Dropout(0.25)(x)\nx = Conv2D(64, (3, 3), padding = 'same')(x)\n#x = BatchNormalization()(x)\nx = Activation('relu')(x)\nx = Conv2D(64, (3, 3))(x)\nx = Activation('relu')(x)\nx = MaxPooling2D(pool_size = (2, 2))(x)\nx = Dropout(0.25)(x)\nx = Flatten()(x)\nx = Dense(32)(x)\nx = Activation('relu')(x)\nx = Dropout(0.2)(x)\noutput0 = Dense(19, activation = 'sigmoid')(x)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"output1 = Dense(1, activation = 'sigmoid')(x)\noutput2 = Dense(1, activation = 'sigmoid')(x)\noutput3 = Dense(1, activation = 'sigmoid')(x)\noutput4 = Dense(1, activation = 'sigmoid')(x)\noutput5 = Dense(1, activation = 'sigmoid')(x)\noutput6 = Dense(1, activation = 'sigmoid')(x)\noutput7 = Dense(1, activation = 'sigmoid')(x)\noutput8 = Dense(1, activation = 'sigmoid')(x)\noutput9 = Dense(1, activation = 'sigmoid')(x)\noutput10 = Dense(1, activation = 'sigmoid')(x)\noutput11 = Dense(1, activation = 'sigmoid')(x)\noutput12 = Dense(1, activation = 'sigmoid')(x)\noutput13 = Dense(1, activation = 'sigmoid')(x)\noutput14 = Dense(1, activation = 'sigmoid')(x)\noutput15 = Dense(1, activation = 'sigmoid')(x)\noutput16 = Dense(1, activation = 'sigmoid')(x)\noutput17 = Dense(1, activation = 'sigmoid')(x)\noutput18 = Dense(1, activation = 'sigmoid')(x)"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Model(inp,[output0])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"model = Model(inp,[output0,\noutput1,\noutput2,\noutput3,\noutput4,\noutput5,\noutput6,\noutput7,\noutput8,\noutput9,\noutput10,\noutput11,\noutput12,\noutput13,\noutput14,\noutput15,\noutput16,\noutput17,\noutput18])"},{"metadata":{"trusted":true},"cell_type":"code","source":"rlr = ReduceLROnPlateau(monitor = 'val_loss', factor = 0.1, patience = 20, verbose = 0, \n                            min_delta = 1e-4, mode = 'max')\nes = EarlyStopping(monitor = 'val_loss', min_delta = 1e-4, patience = 2, mode = 'max', \n                       baseline = None, restore_best_weights = True, verbose = 0)\nckp = ModelCheckpoint('./model_100.hdf5', monitor = 'val_loss', verbose = 0, \n                        save_best_only = True, save_weights_only = False, mode = 'max')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer = RMSprop(lr = 0.01, decay = 1e-6),\n              loss = tf.keras.losses.BinaryCrossentropy(label_smoothing = 1e-3), \n              #metrics = [BinaryAccuracy(name='binary_accuracy', dtype=None, threshold=0.5), Precision(name='precision'), Recall(name='recall')] \n              metrics = [tf.keras.metrics.CategoricalCrossentropy(name='categorical_crossentropy'),\\\n                         tf.keras.metrics.CategoricalAccuracy(name='categorical_accuracy'), \\\n                         #Precision(name='precision'), Recall(name='recall')\n                        ]\n              #metrics = ['categorical_accuracy', 'accuracy'],\n             )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Show a summary of the model. Check the number of trainable parameters\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def dice_coeff(y1, y2):\n    y1 = Flatten(y1)\n    y2 = Flatten(y2)\n    return (2 * sum(y1 * y2) + smothness) / (sum(y1) + sum(y2) + smothness)\n\ndef dice_coeff_loss(y1, y2):\n    return -dice_coeff(y1, y2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def generator_wrapper(generator):\n    for batch_x,batch_y in generator:\n        yield (batch_x,[batch_y[:,i] for i in range(19)])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#training_set = np.copy(x_train_sample)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#gc.collect()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Flows Methods\n- https://medium.com/swlh/keras-imagedatagenerators-flow-methods-and-when-to-use-them-b9314489d591"},{"metadata":{},"cell_type":"markdown","source":"## Using Flow from Dataframe"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data_sample.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cols = ['ID','image_path','Label','Nucleoplasm', 'Nuclear membrane', 'Nucleoli', 'Nucleoli fibrillar center', \n           'Nuclear speckles', 'Nuclear bodies', 'Endoplasmic reticulum', 'Golgi apparatus', \n           'Intermediate filaments', 'Actin filaments', 'Microtubules', 'Mitotic spindle', \n           'Centrosome', 'Plasma membrane', 'Mitochondria', 'Aggresome', 'Cytosol', \n           'Vesicles and punctate cytosolic patterns', 'Negative']\ntype(classes)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data_sample.columns = cols","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data_sample.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classes = ['Nucleoplasm', 'Nuclear membrane', 'Nucleoli', 'Nucleoli fibrillar center', \n           'Nuclear speckles', 'Nuclear bodies', 'Endoplasmic reticulum', 'Golgi apparatus', \n           'Intermediate filaments', 'Actin filaments', 'Microtubules', 'Mitotic spindle', \n           'Centrosome', 'Plasma membrane', 'Mitochondria', 'Aggresome', 'Cytosol', \n           'Vesicles and punctate cytosolic patterns', 'Negative']\ntype(classes)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n#datagen = ImageDataGenerator(rescale=1./255.,validation_split=0.2)\ndatagen = ImageDataGenerator(validation_split=0.2)\n\ntrain_generator = datagen.flow_from_dataframe(dataframe=train_data_sample,\n                               x_col='image_path',\n                               #label_mode=\"int\"\n                               y_col=classes,\n                               batch_size=32,\n                               shuffle=True,\n                               seed=42,\n                                class_mode='multi_output',\n                                target_size=(32,32),\n                               subset='training')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n##### USINg IMAGE GENERATOR with Numpy Array\n#STEP_SIZE_TRAIN=training_set.n//training_set.batch_size\n#STEP_SIZE_VALID=valid_generator.n//valid_generator.batch_size\n#STEP_SIZE_TEST=test_set.n//test_set.batch_size\nhist_1 = model.fit(train_generator, \n          batch_size = 64, \n          epochs=40,\n          #validation_data = (valid_generator),\n          #validation_split = .3,\n          shuffle=False,\n          verbose = 2\n         )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n#STEP_SIZE_TRAIN=training_set.n//training_set.batch_size\n#STEP_SIZE_VALID=valid_generator.n//valid_generator.batch_size\n#STEP_SIZE_TEST=test_set.n//test_set.batch_size\nmodel.fit(generator_wrapper(training_set),\n                  #(np.asarray(training_set).astype(\"float32\")),\n                    #steps_per_epoch=STEP_SIZE_TRAIN,\n                    #validation_data=generator_wrapper(test_set),\n                    batch_size=4096, \n                    #validation_steps=STEP_SIZE_VALID,\n                    validation_split = .3,\n                    epochs=3,\n                   #verbose=2\n         )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Flow from Numpy Array"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n#datagen = ImageDataGenerator(rescale=1./255.,validation_split=0.2)\ndatagen = ImageDataGenerator(validation_split=0.2)\n\ntrain_generator = datagen.flow(x_train_sample,\n                               y_train_sample,\n                               batch_size=32,\n                               color_mode = 'rgb'  ### ADDED Now\n                               shuffle=True,\n                               seed=42,\n                               subset='training')\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"valid_generator = datagen.flow(x_val_sample,\n                               y_val_sample,\n                               batch_size=32,\n                               seed=42,\n                               subset='validation')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n##### USINg IMAGE GENERATOR with Numpy Array\n#STEP_SIZE_TRAIN=training_set.n//training_set.batch_size\n#STEP_SIZE_VALID=valid_generator.n//valid_generator.batch_size\n#STEP_SIZE_TEST=test_set.n//test_set.batch_size\nhist_1 = model.fit(train_generator, \n          batch_size = 64, \n          epochs=40,\n          validation_data = (valid_generator),\n          #validation_split = .3,\n          shuffle=False,\n          verbose = 2\n         )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n##### USINg IMAGE GENERATOR with Numpy Array\n#STEP_SIZE_TRAIN=training_set.n//training_set.batch_size\n#STEP_SIZE_VALID=valid_generator.n//valid_generator.batch_size\n#STEP_SIZE_TEST=test_set.n//test_set.batch_size\nhist_1 = model.fit(train_generator, \n          batch_size = 16, \n          epochs=10,\n          validation_data = (valid_generator),\n          #validation_split = .3,\n          shuffle=False,\n          verbose = 2\n         )","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## NO FLOW "},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n### WITh NUMPY ARRAY \n#STEP_SIZE_TRAIN=training_set.n//training_set.batch_size\n#STEP_SIZE_VALID=valid_generator.n//valid_generator.batch_size\n#STEP_SIZE_TEST=test_set.n//test_set.batch_size\nhist_1 = model.fit(x_train_sample, y_train_sample, \n          batch_size = 16, \n          epochs=10,\n          validation_data = (x_val_sample, y_val_sample),\n          #validation_split = .3,\n          shuffle=False,\n          verbose = 2\n         )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import seaborn as sns\ndef plot_model_acc(history, model):\n    plt.rcParams.update({'font.size': 16, 'font.weight':'bold'})\n    sns.set_style('whitegrid')\n    plt.figure(figsize=(10,6))\n    plt.plot(history.history['categorical_accuracy'])\n    plt.plot(history.history['val_categorical_accuracy'])\n    plt.title('Model Accuracy', fontsize=22, fontweight=\"bold\")\n    plt.ylabel('Accuracy',fontsize=18, fontweight=\"bold\")\n    plt.xlabel('Epoch', fontsize=18, fontweight=\"bold\")\n    plt.legend(['Train', 'Val'], loc='upper left')\n    plt.savefig('Keras_Model_Accuracy_'+str(model)+'.png', bbox_inches = 'tight')\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#___________________________________________\n# Plot Model Accuracy\ndef plot_model_loss(history, model): \n    plt.rcParams.update({'font.size': 16, 'font.weight':'bold'})\n    sns.set_style('whitegrid')\n    plt.figure(figsize=(10,6))\n    plt.plot(history.history['loss'])\n    plt.plot(history.history['val_loss'])\n    plt.title('Model Loss', fontsize=22, fontweight=\"bold\")\n    plt.ylabel('Loss', fontsize=18, fontweight=\"bold\")\n    plt.xlabel('Epoch', fontsize=18, fontweight=\"bold\")\n    plt.legend(['Train', 'Val'], loc='upper left')\n    plt.savefig('Keras_model_loss_'+str(model)+'.png', bbox_inches = 'tight')\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_model_acc(hist_1,'model1')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_model_loss(hist_1,'model1')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_model_loss(hist_1,'model1')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras import Model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_name = 'model1_10_hflip_sample'\nprint(model_name)\nmodel.save('./'+model_name+'.hdf5')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = keras.models.load_model('./'+model_name+'.hdf5')\nmodel.load_weights('./'+model_name+'.hdf5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ny_pred = model.predict(x_val_sample)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.DataFrame(np.asarray(y_pred))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Segmentation is calculated using IoU with a threshold of 0.6.\ndef clean_prediction(prediction):\n    #predictions = prediction.copy()\n    predictions = np.copy(prediction)\n    for batch_index in range(len(predictions)):\n        for class_index in range(len(predictions[batch_index])):\n            predictions[batch_index][class_index] = 1 if predictions[batch_index][class_index] >= 0.45 else 0\n    return np.array(predictions).astype(np.int) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = np.copy(y_pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classes = ['Nucleoplasm', 'Nuclear membrane', 'Nucleoli', 'Nucleoli fibrillar center', \n           'Nuclear speckles', 'Nuclear bodies', 'Endoplasmic reticulum', 'Golgi apparatus', \n           'Intermediate filaments', 'Actin filaments', 'Microtubules', 'Mitotic spindle', \n           'Centrosome', 'Plasma membrane', 'Mitochondria', 'Aggresome', 'Cytosol', \n           'Vesicles and punctate cytosolic patterns', 'Negative']\ntype(classes)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"clean_pred = clean_prediction(preds)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.DataFrame(clean_pred, columns=(classes))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Submissions are evaluated by computing [mAP], with the mean taken over the 19 segmentable classes of the challenge.\nfrom sklearn.metrics import average_precision_score","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"mAP = average_precision_score(y_val_sample, y_pred)\nmAP","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"mAP","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_val[:1], y_pred[:1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"average_precision_score(y_test[:1], y_pred[:1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}