{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install -q efficientnet","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os, random, re, math, time\nrandom.seed(a=42)\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport pandas as pd\n\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nimport efficientnet.tfkeras as efn\n\nimport PIL\n\nfrom kaggle_datasets import KaggleDatasets\n\nfrom tqdm import tqdm","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DEVICE = \"TPU\"\n\nCFG = dict(\n    net_count         =   7,\n    batch_size        =  32,\n    \n    read_size         = 256, \n    crop_size         = 256, \n    net_size          = 256, \n    \n    LR_START          =   0.000005,\n    LR_MAX            =   0.000020,\n    LR_MIN            =   0.000001,\n    LR_RAMPUP_EPOCHS  =   5,\n    LR_SUSTAIN_EPOCHS =   0,\n    LR_EXP_DECAY      =   0.8,\n    epochs            =   15,\n    \n    rot               = 180.0,\n    shr               =   2.0,\n    hzoom             =   8.0,\n    wzoom             =   8.0,\n    hshift            =   8.0,\n    wshift            =   8.0,\n\n    optimizer         = 'adam',\n    label_smooth_fac  =   0.05,\n    \n    tta_steps         =  25    \n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BASEPATH = \"../input/siim-isic-melanoma-classification\"\ndf_train = pd.read_csv(os.path.join(BASEPATH, 'train.csv'))\ndf_test  = pd.read_csv(os.path.join(BASEPATH, 'test.csv'))\ndf_sub   = pd.read_csv(os.path.join(BASEPATH, 'sample_submission.csv'))\n\nGCS_PATH    = KaggleDatasets().get_gcs_path('melanoma-256x256')\nfiles_train = np.sort(np.array(tf.io.gfile.glob(GCS_PATH + '/train*.tfrec')))\nfiles_test  = np.sort(np.array(tf.io.gfile.glob(GCS_PATH + '/test*.tfrec')))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# with validation data\nfiles_train, files_val = train_test_split(files_train,test_size=0.2, random_state=42)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if DEVICE == \"TPU\":\n    print(\"connecting to TPU...\")\n    try:\n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n        print('Running on TPU ', tpu.master())\n    except ValueError:\n        print(\"Could not connect to TPU\")\n        tpu = None\n\n    if tpu:\n        try:\n            print(\"initializing  TPU ...\")\n            tf.config.experimental_connect_to_cluster(tpu)\n            tf.tpu.experimental.initialize_tpu_system(tpu)\n            strategy = tf.distribute.experimental.TPUStrategy(tpu)\n            print(\"TPU initialized\")\n        except _:\n            print(\"failed to initialize TPU\")\n    else:\n        DEVICE = \"GPU\"\n\nif DEVICE != \"TPU\":\n    print(\"Using default strategy for CPU and single GPU\")\n    strategy = tf.distribute.get_strategy()\n\nif DEVICE == \"GPU\":\n    print(\"Num GPUs Available: \", len(tf.config.experimental.list_physical_devices('GPU')))\n    \n\nAUTO     = tf.data.experimental.AUTOTUNE\nREPLICAS = strategy.num_replicas_in_sync\nprint(f'REPLICAS: {REPLICAS}')","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):\n    # returns 3x3 transformmatrix which transforms indicies\n        \n    # CONVERT DEGREES TO RADIANS\n    rotation = math.pi * rotation / 180.\n    shear    = math.pi * shear    / 180.\n\n    def get_3x3_mat(lst):\n        return tf.reshape(tf.concat([lst],axis=0), [3,3])\n    \n    # ROTATION MATRIX\n    c1   = tf.math.cos(rotation)\n    s1   = tf.math.sin(rotation)\n    one  = tf.constant([1],dtype='float32')\n    zero = tf.constant([0],dtype='float32')\n    \n    rotation_matrix = get_3x3_mat([c1,   s1,   zero, \n                                   -s1,  c1,   zero, \n                                   zero, zero, one])    \n    # SHEAR MATRIX\n    c2 = tf.math.cos(shear)\n    s2 = tf.math.sin(shear)    \n    \n    shear_matrix = get_3x3_mat([one,  s2,   zero, \n                                zero, c2,   zero, \n                                zero, zero, one])        \n    # ZOOM MATRIX\n    zoom_matrix = get_3x3_mat([one/height_zoom, zero,           zero, \n                               zero,            one/width_zoom, zero, \n                               zero,            zero,           one])    \n    # SHIFT MATRIX\n    shift_matrix = get_3x3_mat([one,  zero, height_shift, \n                                zero, one,  width_shift, \n                                zero, zero, one])\n    \n    return K.dot(K.dot(rotation_matrix, shear_matrix), \n                 K.dot(zoom_matrix,     shift_matrix))\n\n\ndef transform(image, cfg):    \n    # input image - is one image of size [dim,dim,3] not a batch of [b,dim,dim,3]\n    # output - image randomly rotated, sheared, zoomed, and shifted\n    DIM = cfg[\"read_size\"]\n    XDIM = DIM%2 #fix for size 331\n    \n    rot = cfg['rot'] * tf.random.normal([1], dtype='float32')\n    shr = cfg['shr'] * tf.random.normal([1], dtype='float32') \n    h_zoom = 1.0 + tf.random.normal([1], dtype='float32') / cfg['hzoom']\n    w_zoom = 1.0 + tf.random.normal([1], dtype='float32') / cfg['wzoom']\n    h_shift = cfg['hshift'] * tf.random.normal([1], dtype='float32') \n    w_shift = cfg['wshift'] * tf.random.normal([1], dtype='float32') \n\n    # GET TRANSFORMATION MATRIX\n    m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift) \n\n    # LIST DESTINATION PIXEL INDICES\n    x   = tf.repeat(tf.range(DIM//2, -DIM//2,-1), DIM)\n    y   = tf.tile(tf.range(-DIM//2, DIM//2), [DIM])\n    z   = tf.ones([DIM*DIM], dtype='int32')\n    idx = tf.stack( [x,y,z] )\n    \n    # ROTATE DESTINATION PIXELS ONTO ORIGIN PIXELS\n    idx2 = K.dot(m, tf.cast(idx, dtype='float32'))\n    idx2 = K.cast(idx2, dtype='int32')\n    idx2 = K.clip(idx2, -DIM//2+XDIM+1, DIM//2)\n    \n    # FIND ORIGIN PIXEL VALUES           \n    idx3 = tf.stack([DIM//2-idx2[0,], DIM//2-1+idx2[1,]])\n    d    = tf.gather_nd(image, tf.transpose(idx3))\n        \n    return tf.reshape(d,[DIM, DIM,3])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_labeled_tfrecord(example):\n    tfrec_format = {\n        'image'                        : tf.io.FixedLenFeature([], tf.string),\n        'image_name'                   : tf.io.FixedLenFeature([], tf.string),\n#         'patient_id'                   : tf.io.FixedLenFeature([], tf.int64),\n#         'sex'                          : tf.io.FixedLenFeature([], tf.int64),\n#         'age_approx'                   : tf.io.FixedLenFeature([], tf.int64),\n#         'anatom_site_general_challenge': tf.io.FixedLenFeature([], tf.int64),\n#         'diagnosis'                    : tf.io.FixedLenFeature([], tf.int64),\n        'target'                       : tf.io.FixedLenFeature([], tf.int64)\n    }           \n    example = tf.io.parse_single_example(example, tfrec_format)\n    return example['image'], example['target']\n\n\ndef read_unlabeled_tfrecord(example, return_image_name):\n    tfrec_format = {\n        'image'                        : tf.io.FixedLenFeature([], tf.string),\n        'image_name'                   : tf.io.FixedLenFeature([], tf.string),\n    }\n    example = tf.io.parse_single_example(example, tfrec_format)\n    return example['image'], example['image_name'] if return_image_name else 0\n\n \ndef prepare_image(img, cfg=None, augment=True):    \n    img = tf.image.decode_jpeg(img, channels=3)\n    img = tf.image.resize(img, [cfg['read_size'], cfg['read_size']])\n    img = tf.cast(img, tf.float32) / 255.0\n    \n    if augment:\n        img = transform(img, cfg)\n        img = tf.image.random_crop(img, [cfg['crop_size'], cfg['crop_size'], 3])\n        img = tf.image.random_flip_left_right(img)\n        img = tf.image.random_hue(img, 0.01)\n        img = tf.image.random_saturation(img, 0.7, 1.3)\n        img = tf.image.random_contrast(img, 0.8, 1.2)\n        img = tf.image.random_brightness(img, 0.1)\n\n    else:\n        img = tf.image.central_crop(img, cfg['crop_size'] / cfg['read_size'])\n                                   \n    img = tf.image.resize(img, [cfg['net_size'], cfg['net_size']])\n    img = tf.reshape(img, [cfg['net_size'], cfg['net_size'], 3])\n    return img\n\ndef count_data_items(filenames):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) \n         for filename in filenames]\n    return np.sum(n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_dataset(files, cfg, augment = False, shuffle = False, repeat = False, \n                labeled=True, return_image_names=True):\n    \n    ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)\n    ds = ds.cache()\n    \n    if repeat:\n        ds = ds.repeat()\n    \n    if shuffle: \n        ds = ds.shuffle(1024*8)\n        opt = tf.data.Options()\n        opt.experimental_deterministic = False\n        ds = ds.with_options(opt)\n        \n    if labeled: \n        ds = ds.map(read_labeled_tfrecord, num_parallel_calls=AUTO)\n    else:\n        ds = ds.map(lambda example: read_unlabeled_tfrecord(example, return_image_names), \n                    num_parallel_calls=AUTO)      \n    \n    ds = ds.map(lambda img, imgname_or_label: (prepare_image(img, augment=augment, cfg=cfg), \n                                               imgname_or_label), \n                num_parallel_calls=AUTO)\n    \n    ds = ds.batch(cfg['batch_size'] * REPLICAS)\n    ds = ds.prefetch(AUTO)\n    return ds","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Test the input pipeline\nBefore calling any neural net I always test the input pipeline.\nHere are images from the train data.","metadata":{}},{"cell_type":"code","source":"def show_dataset(thumb_size, cols, rows, ds):\n    mosaic = PIL.Image.new(mode='RGB', size=(thumb_size*cols + (cols-1), \n                                             thumb_size*rows + (rows-1)))\n   \n    for idx, data in enumerate(iter(ds)):\n        img, target_or_imgid = data\n        ix  = idx % cols\n        iy  = idx // cols\n        img = np.clip(img.numpy() * 255, 0, 255).astype(np.uint8)\n        img = PIL.Image.fromarray(img)\n        img = img.resize((thumb_size, thumb_size), resample=PIL.Image.BILINEAR)\n        mosaic.paste(img, (ix*thumb_size + ix, \n                           iy*thumb_size + iy))\n\n    display(mosaic)\n    \nds = get_dataset(files_train, CFG).unbatch().take(12*5)   \nshow_dataset(64, 12, 5, ds)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Test of image augmentation","metadata":{}},{"cell_type":"code","source":"ds = tf.data.TFRecordDataset(files_train, num_parallel_reads=AUTO)\nds = ds.take(1).cache().repeat()\nds = ds.map(read_labeled_tfrecord, num_parallel_calls=AUTO)\nds = ds.map(lambda img, target: (prepare_image(img, cfg=CFG, augment=True), target), \n            num_parallel_calls=AUTO)\nds = ds.take(12*5)\nds = ds.prefetch(AUTO)\n\nshow_dataset(64, 12, 5, ds)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Images from the test data","metadata":{}},{"cell_type":"code","source":"ds = get_dataset(files_test, CFG, labeled=False).unbatch().take(12*5)   \nshow_dataset(64, 12, 5, ds)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndef model_f0(dim):\n    inp = tf.keras.layers.Input(shape=(dim,dim,3))\n    base = efn.EfficientNetB0(input_shape=(dim,dim,3),weights='imagenet',include_top=False)\n    x = base(inp)\n    x = tf.keras.layers.GlobalAveragePooling2D()(x)\n    x = tf.keras.layers.Dense(1,activation='sigmoid')(x)\n    model = tf.keras.Model(inputs=inp,outputs=x)\n    opt = tf.keras.optimizers.Adam(learning_rate=0.001)\n    loss = tf.keras.losses.BinaryCrossentropy(label_smoothing=0.05) \n    model.compile(optimizer=opt,loss=loss,metrics=['AUC'])\n    return model\n\n\ndef model_f1(dim):\n    inp = tf.keras.layers.Input(shape=(dim,dim,3))\n    base = efn.EfficientNetB1(input_shape=(dim,dim,3),weights='imagenet',include_top=False)\n    x = base(inp)\n    x = tf.keras.layers.GlobalAveragePooling2D()(x)\n    x = tf.keras.layers.Dense(1,activation='sigmoid')(x)\n    model = tf.keras.Model(inputs=inp,outputs=x)\n    opt = tf.keras.optimizers.Adam(learning_rate=0.001)\n    loss = tf.keras.losses.BinaryCrossentropy(label_smoothing=0.05) \n    model.compile(optimizer=opt,loss=loss,metrics=['AUC'])\n    return model\n\n\ndef model_f2(dim):\n    inp = tf.keras.layers.Input(shape=(dim,dim,3))\n    base = efn.EfficientNetB2(input_shape=(dim,dim,3),weights='imagenet',include_top=False)\n    x = base(inp)\n    x = tf.keras.layers.GlobalAveragePooling2D()(x)\n    x = tf.keras.layers.Dense(1,activation='sigmoid')(x)\n    model = tf.keras.Model(inputs=inp,outputs=x)\n    opt = tf.keras.optimizers.Adam(learning_rate=0.001)\n    loss = tf.keras.losses.BinaryCrossentropy(label_smoothing=0.05) \n    model.compile(optimizer=opt,loss=loss,metrics=['AUC'])\n    return model\n\ndef model_f3(dim):\n    inp = tf.keras.layers.Input(shape=(dim,dim,3))\n    base = efn.EfficientNetB3(input_shape=(dim,dim,3),weights='imagenet',include_top=False)\n    x = base(inp)\n    x = tf.keras.layers.GlobalAveragePooling2D()(x)\n    x = tf.keras.layers.Dense(1,activation='sigmoid')(x)\n    model = tf.keras.Model(inputs=inp,outputs=x)\n    opt = tf.keras.optimizers.Adam(learning_rate=0.001)\n    loss = tf.keras.losses.BinaryCrossentropy(label_smoothing=0.05) \n    model.compile(optimizer=opt,loss=loss,metrics=['AUC'])\n    return model\n\n\ndef model_f4(dim):\n    inp = tf.keras.layers.Input(shape=(dim,dim,3))\n    base = efn.EfficientNetB4(input_shape=(dim,dim,3),weights='imagenet',include_top=False)\n    x = base(inp)\n    x = tf.keras.layers.GlobalAveragePooling2D()(x)\n    x = tf.keras.layers.Dense(1,activation='sigmoid')(x)\n    model = tf.keras.Model(inputs=inp,outputs=x)\n    opt = tf.keras.optimizers.Adam(learning_rate=0.001)\n    loss = tf.keras.losses.BinaryCrossentropy(label_smoothing=0.05) \n    model.compile(optimizer=opt,loss=loss,metrics=['AUC'])\n    return model\n\ndef model_f5(dim):\n    inp = tf.keras.layers.Input(shape=(dim,dim,3))\n    base = efn.EfficientNetB5(input_shape=(dim,dim,3),weights='imagenet',include_top=False)\n    x = base(inp)\n    x = tf.keras.layers.GlobalAveragePooling2D()(x)\n    x = tf.keras.layers.Dense(1,activation='sigmoid')(x)\n    model = tf.keras.Model(inputs=inp,outputs=x)\n    opt = tf.keras.optimizers.Adam(learning_rate=0.001)\n    loss = tf.keras.losses.BinaryCrossentropy(label_smoothing=0.05) \n    model.compile(optimizer=opt,loss=loss,metrics=['AUC'])\n    return model\n\ndef model_f6(dim):\n    inp = tf.keras.layers.Input(shape=(dim,dim,3))\n    base = efn.EfficientNetB6(input_shape=(dim,dim,3),weights='imagenet',include_top=False)\n    x = base(inp)\n    x = tf.keras.layers.GlobalAveragePooling2D()(x)\n    x = tf.keras.layers.Dense(1,activation='sigmoid')(x)\n    model = tf.keras.Model(inputs=inp,outputs=x)\n    opt = tf.keras.optimizers.Adam(learning_rate=0.001)\n    loss = tf.keras.losses.BinaryCrossentropy(label_smoothing=0.05) \n    model.compile(optimizer=opt,loss=loss,metrics=['AUC'])\n    return model","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    model_f0 = model_f0(dim=256)\n    model_f1 = model_f1(dim=256)\n    model_f2 = model_f2(dim=256)\n    model_f3 = model_f3(dim=256)\n    model_f4 = model_f4(dim=256)\n    model_f5 = model_f5(dim=256)\n    model_f6 = model_f6(dim=256)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds_train     = get_dataset(files_train, CFG, augment=True, shuffle=True, repeat=True)\nds_train     = ds_train.map(lambda img, label: (img, tuple([label] * CFG['net_count'])))\n\nds_val     = get_dataset(files_val, CFG, augment=True, shuffle=True, repeat=False)\nds_val     = ds_val.map(lambda img, label: (img, tuple([label] * CFG['net_count'])))\n\nsteps_train  = count_data_items(files_train) / (CFG['batch_size'] * REPLICAS)\n\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_lr_callback(cfg):\n    lr_start   = cfg['LR_START']\n    lr_max     = cfg['LR_MAX'] * strategy.num_replicas_in_sync\n    lr_min     = cfg['LR_MIN']\n    lr_ramp_ep = cfg['LR_RAMPUP_EPOCHS']\n    lr_sus_ep  = cfg['LR_SUSTAIN_EPOCHS']\n    lr_decay   = cfg['LR_EXP_DECAY']\n   \n    def lrfn(epoch):\n        if epoch < lr_ramp_ep:\n            lr = (lr_max - lr_start) / lr_ramp_ep * epoch + lr_start\n            \n        elif epoch < lr_ramp_ep + lr_sus_ep:\n            lr = lr_max\n            \n        else:\n            lr = (lr_max - lr_min) * lr_decay**(epoch - lr_ramp_ep - lr_sus_ep) + lr_min\n            \n        return lr\n\n    lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=False)\n    return lr_callback","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"=========== Model_f0 =============\")\nhistory0 = model_f0.fit(ds_train, verbose = 1, steps_per_epoch  = steps_train, epochs = CFG['epochs'], callbacks = [get_lr_callback(CFG)],validation_data=ds_val)\nmodel_f0.save('model_f0.hdf5')\nprint(\"=========== Model_f1 =============\")\nhistory1 = model_f1.fit(ds_train, verbose = 1, steps_per_epoch  = steps_train, epochs = CFG['epochs'], callbacks = [get_lr_callback(CFG)],validation_data=ds_val)\nmodel_f1.save('model_f1.hdf5')\nprint(\"=========== Model_f2 =============\")\nhistory2 = model_f2.fit(ds_train, verbose = 1, steps_per_epoch  = steps_train, epochs = CFG['epochs'], callbacks = [get_lr_callback(CFG)],validation_data=ds_val)\nmodel_f2.save('model_f2.hdf5')\nprint(\"=========== Model_f3 =============\")\nhistory3 = model_f3.fit(ds_train, verbose = 1, steps_per_epoch  = steps_train, epochs = CFG['epochs'], callbacks = [get_lr_callback(CFG)],validation_data=ds_val)\nmodel_f3.save('model_f3.hdf5')\nprint(\"=========== Model_f4 =============\")\nhistory4 = model_f4.fit(ds_train, verbose = 1, steps_per_epoch  = steps_train, epochs = CFG['epochs'], callbacks = [get_lr_callback(CFG)],validation_data=ds_val)\nmodel_f4.save('model_f4.hdf5')\nprint(\"=========== Model_f5 =============\")\nhistory5 = model_f5.fit(ds_train, verbose = 1, steps_per_epoch  = steps_train, epochs = CFG['epochs'], callbacks = [get_lr_callback(CFG)],validation_data=ds_val)\nmodel_f5.save('model_f5.hdf5')\nprint(\"=========== Model_f6 =============\")\nhistory6 = model_f6.fit(ds_train, verbose = 1, steps_per_epoch  = steps_train, epochs = CFG['epochs'], callbacks = [get_lr_callback(CFG)], validation_data=ds_val)\nmodel_f6.save('model_f6.hdf5')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### predict the test set using augmented images","metadata":{}},{"cell_type":"code","source":"test_ds = get_dataset(files_test, CFG, augment=True, repeat=False, labeled=False, return_image_names=False)\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\n\nmodel_list = [model_f0,model_f1,model_f2,model_f3,model_f4,model_f5,model_f6]\n\n\nens_probabilities = [model.predict(test_images_ds) for model in model_list]\n\nprint(\"========================  Done  ============================\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Average the predictions of models\naverage_prob = np.sum(ens_probabilities, axis=0)/len(model_list)\n\n# weight the prediction of models\n\n# weights = [0.3, 0.3, 0.4]\n# #Use tensordot to sum the products of all elements over specified axes.\n# weighted_prob = np.tensordot(ens_probabilities, weights, axes=((0),(0)))\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds = get_dataset(files_test, CFG, augment=False, repeat=False, \n                 labeled=False, return_image_names=True)\n\nimage_names = np.array([img_name.numpy().decode(\"utf-8\") \n                        for img, img_name in iter(ds.unbatch())])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_average = pd.DataFrame({'image_name': image_names, 'target': np.concatenate(average_prob)})\n\nef0 = pd.DataFrame({'image_name': image_names, 'target': np.concatenate(ens_probabilities[0])})\nef1 = pd.DataFrame({'image_name': image_names, 'target': np.concatenate(ens_probabilities[1])})\nef2 = pd.DataFrame({'image_name': image_names, 'target': np.concatenate(ens_probabilities[2])})\nef3 = pd.DataFrame({'image_name': image_names, 'target': np.concatenate(ens_probabilities[3])})\nef4 = pd.DataFrame({'image_name': image_names, 'target': np.concatenate(ens_probabilities[4])})\nef5 = pd.DataFrame({'image_name': image_names, 'target': np.concatenate(ens_probabilities[5])})\nef6 = pd.DataFrame({'image_name': image_names, 'target': np.concatenate(ens_probabilities[6])})","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_average.to_csv('pred_average.csv', index=False)\nef0.to_csv('ef0.csv', index=False)\nef1.to_csv('ef1.csv', index=False)\nef2.to_csv('ef2.csv', index=False)\nef3.to_csv('ef3.csv', index=False)\nef4.to_csv('ef4.csv', index=False)\nef5.to_csv('ef5.csv', index=False)\nef6.to_csv('ef6.csv', index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# load models\nfrom keras.models import load_model\n\nm0 = load_model('./model_f0.hdf5')\nm1 = load_model('./model_f1.hdf5')\nm2 = load_model('./model_f3.hdf5')\nm3 = load_model('./model_f3.hdf5')\nm4 = load_model('./model_f4.hdf5')\nm5 = load_model('./model_f5.hdf5')\nm6 = load_model('./model_f6.hdf5')\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"models = [m1,m2,m3,m4,m5,m6]\ntest1 = test_ds.take(1)\ntest10 = test_ds.take(10)\ntest50 = test_ds.take(50)\ntest100 = test_ds.take(100)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import time\n\nst = time.time()\npr = m6.predict(test10)\ned = time.time()\nprint(\"Single model time for 10 data: \", (ed - st))\n\nstart10 = time.time()\nens = [model.predict(test10) for model in models]\nav = np.sum(ens, axis=0)/len(models)\nend10 = time.time()\nprint(\"ensemble time for 10 data: \", (end10 - start10))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"st = time.time()\npr = m6.predict(test1)\ned = time.time()\nprint(\"Single model time for 1 data: \", (ed - st))\n\nstart1 = time.time()\nens = [model.predict(test1) for model in models]\nav = np.sum(ens, axis=0)/len(models)\nend1 = time.time()\nprint(\"ensemble time for 1 data: \", (end1 - start1))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"st = time.time()\npr = m6.predict(test50)\ned = time.time()\nprint(\"Single model time for 50 data: \", (ed - st))\n\nstart50 = time.time()\nens = [model.predict(test50) for model in models]\nav = np.sum(ens, axis=0)/len(models)\nend50 = time.time()\nprint(\"ensemble time for 50 data: \", (end50 - start50))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}