{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Import packages","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport tensorflow as tf\nimport pandas as pd\nimport random, re, math\nfrom tensorflow import keras\nimport matplotlib.pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nfrom keras.callbacks import LearningRateScheduler\nfrom keras import backend as K\nfrom keras import layers\nfrom sklearn.model_selection import KFold","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Detect TPU and specify file paths","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver() \n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n    \nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() \n\n# In order to train on TPU we need to store in Google Cloud Storage\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\nAUTO = tf.data.experimental.AUTOTUNE\nIMAGE_SIZE = [192, 192] \nGCS_PATH_SELECT = { \n    192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',\n    224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',\n    331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',\n    512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'\n}\n\nGCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec') #Training dataset\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec') #Validation dataset\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec') #Test dataset\n\n# Set Batch Size\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Define Helper Functions\n(Courtesy: Petal Helper)","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = tf.cast(example['class'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"id\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['id']\n    return image, idnum \n\ndef load_dataset(filenames, labeled = True, ordered = False):\n    \n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False\n        \n    #automatically interleaves reads from multiple files\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)\n    \n    #uses data as soon as it streams in instead of original order\n    dataset = dataset.with_options(ignore_order)\n    \n    #returns (image, label) if labeled == True else(image, id)\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    \n    return dataset\n\ndef data_augment(image, label):\n\n    image = tf.image.random_flip_left_right(image)\n    return image, label   \n\ndef get_training_dataset(dataset,do_aug=True):\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    if do_aug: dataset = dataset.map(transform, num_parallel_calls=AUTO)\n    dataset = dataset.repeat() \n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) \n    return dataset\n\ndef get_validation_dataset(dataset):\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) \n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) \n    return dataset\n\ndef count_data_items(filenames):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nCLASSES = ['pink primrose',    'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea',     'wild geranium',     'tiger lily',           'moon orchid',              'bird of paradise', 'monkshood',        'globe thistle',         # 00 - 09\n           'snapdragon',       \"colt's foot\",               'king protea',      'spear thistle', 'yellow iris',       'globe-flower',         'purple coneflower',        'peruvian lily',    'balloon flower',   'giant white arum lily', # 10 - 19\n           'fire lily',        'pincushion flower',         'fritillary',       'red ginger',    'grape hyacinth',    'corn poppy',           'prince of wales feathers', 'stemless gentian', 'artichoke',        'sweet william',         # 20 - 29\n           'carnation',        'garden phlox',              'love in the mist', 'cosmos',        'alpine sea holly',  'ruby-lipped cattleya', 'cape flower',              'great masterwort', 'siam tulip',       'lenten rose',           # 30 - 39\n           'barberton daisy',  'daffodil',                  'sword lily',       'poinsettia',    'bolero deep blue',  'wallflower',           'marigold',                 'buttercup',        'daisy',            'common dandelion',      # 40 - 49\n           'petunia',          'wild pansy',                'primula',          'sunflower',     'lilac hibiscus',    'bishop of llandaff',   'gaura',                    'geranium',         'orange dahlia',    'pink-yellow dahlia',    # 50 - 59\n           'cautleya spicata', 'japanese anemone',          'black-eyed susan', 'silverbush',    'californian poppy', 'osteospermum',         'spring crocus',            'iris',             'windflower',       'tree poppy',            # 60 - 69\n           'gazania',          'azalea',                    'water lily',       'rose',          'thorn apple',       'morning glory',        'passion flower',           'lotus',            'toad lily',        'anthurium',             # 70 - 79\n           'frangipani',       'clematis',                  'hibiscus',         'columbine',     'desert-rose',       'tree mallow',          'magnolia',                 'cyclamen ',        'watercress',       'canna lily',            # 80 - 89\n           'hippeastrum ',     'bee balm',                  'pink quill',       'foxglove',      'bougainvillea',     'camellia',             'mallow',                   'mexican petunia',  'bromelia',         'blanket flower',        # 90 - 99\n           'trumpet creeper',  'blackberry lily',           'common tulip',     'wild rose'] ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Scripts for Data Augmentation \n(Courtesy: Chris Deotte)","execution_count":null},{"metadata":{"trusted":true},"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    # 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    rotation_matrix = tf.reshape( tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3] )\n        \n    # SHEAR MATRIX\n    c2 = tf.math.cos(shear)\n    s2 = tf.math.sin(shear)\n    shear_matrix = tf.reshape( tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3] )    \n    \n    # ZOOM MATRIX\n    zoom_matrix = tf.reshape( tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3] )\n    \n    # SHIFT MATRIX\n    shift_matrix = tf.reshape( tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3] )\n    \n    return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))\n\n\ndef transform(image,label):\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 = IMAGE_SIZE[0]\n    XDIM = DIM%2 #fix for size 331\n    \n    rot = 15. * tf.random.normal([1],dtype='float32')\n    shr = 5. * tf.random.normal([1],dtype='float32') \n    h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.\n    w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.\n    h_shift = 16. * tf.random.normal([1],dtype='float32') \n    w_shift = 16. * 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]),label","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Compute the number of examples in each dataset and number of output classes","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\n\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Load datasets","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dataset = load_dataset(TRAINING_FILENAMES, labeled = True)\nvalid_dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=True)\ntest_dataset = get_test_dataset(ordered=True)\nprint('Loaded Datasets....')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Import pre-trained Network ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.applications import ResNet50, Xception, DenseNet201 #change here if you want to change the network\nfrom tensorflow.keras import Sequential\nfrom keras.layers import Dense, GlobalAveragePooling2D","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Customize the Neural Networks for this competition","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def build_xception_network():\n    with strategy.scope():\n        #change the class if you want to change the network\n        network = Xception(input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),weights='imagenet',include_top=False)\n        network.trainable = True\n        model = Sequential([network, GlobalAveragePooling2D(), Dense(len(CLASSES), activation = 'softmax', dtype = 'float32')])\n        \n        opt = 'Adam'\n        model.compile(optimizer = opt, loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])\n        return model\n    \ndef build_resnet_network():\n    with strategy.scope():\n        #change the class if you want to change the network\n        network = ResNet50(input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),weights='imagenet',include_top=False)\n        network.trainable = True\n        model = Sequential([network, GlobalAveragePooling2D(), Dense(len(CLASSES), activation = 'softmax', dtype = 'float32')])\n        \n        opt = 'Adam'\n        model.compile(optimizer = opt, loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])\n        return model\n    \ndef build_densenet_network():\n    with strategy.scope():\n        #change the class if you want to change the network\n        network = DenseNet201(input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),weights='imagenet',include_top=False)\n        network.trainable = True\n        model = Sequential([network, GlobalAveragePooling2D(), Dense(len(CLASSES), activation = 'softmax', dtype = 'float32')])\n        \n        opt = 'Adam'\n        model.compile(optimizer = opt, loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])\n        return model","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Setup for training the Deep Neural Network","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"EPOCHS = 15\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nSEED = 7\n\n# Define a customized learning rate schedule\ndef scheduler(epoch, lr):\n    lr_start = 0.00001\n    lr_min = 0.00001\n    lr_max = 0.00005 * strategy.num_replicas_in_sync\n    lr_rampup_epochs = 5\n    lr_sustain_epochs = 0\n    lr_exp_decay = .8\n    if epoch < lr_rampup_epochs:\n        lr = (lr_max - lr_start) / lr_rampup_epochs * epoch + lr_start\n    elif epoch < lr_rampup_epochs + lr_sustain_epochs:\n        lr = lr_max\n    else:\n        lr = (lr_max - lr_min) * lr_exp_decay**(epoch - lr_rampup_epochs - lr_sustain_epochs) + lr_min\n    return lr\n\n#example plot for learning rate\nepoch_range = [i for i in range(25)]\nlr_schedule = [scheduler(epoch, 0) for epoch in epoch_range] #the second arg in scheduler doesn't matter\nplt.plot(epoch_range, lr_schedule)\nplt.xlabel('Epochs')\nplt.ylabel('Learning Rate')\nplt.title('Learning Rate Schedule')\nplt.show()\n\n#Add learning rate scheduler to callback list\nlr_schedule = LearningRateScheduler(scheduler)\ncallback_list = [lr_schedule]\n\ndef train(num):\n    if num == 1:\n        print('Training Xception....')\n        model = build_xception_network()\n        history = model.fit(get_training_dataset(train_dataset), validation_data = get_validation_dataset(valid_dataset), epochs = EPOCHS, batch_size = BATCH_SIZE,steps_per_epoch = STEPS_PER_EPOCH, callbacks = callback_list)\n        print('Training completed....')\n    elif num == 2:\n        print('Training ResNet50....')\n        model = build_resnet_network()\n        history = model.fit(get_training_dataset(train_dataset), validation_data = get_validation_dataset(valid_dataset), epochs = EPOCHS, batch_size = BATCH_SIZE,steps_per_epoch = STEPS_PER_EPOCH, callbacks = callback_list)\n        print('Training completed....')\n    elif num == 3:\n        print('Training DenseNet201....')\n        model = build_densenet_network()\n        history = model.fit(get_training_dataset(train_dataset), validation_data = get_validation_dataset(valid_dataset), epochs = EPOCHS, batch_size = BATCH_SIZE,steps_per_epoch = STEPS_PER_EPOCH, callbacks = callback_list)\n        print('Training completed....')\n    else:\n        raise Exception('Add Network')\n    \n    return history, model\n   \ndef plot_train_and_val_stats(history):\n    \n    # Plots training and validation losses\n    plt.figure()\n    plt.plot(history.history['loss'])\n    plt.plot(history.history['val_loss'])\n    plt.xlabel('Epochs')\n    plt.ylabel('Loss')\n    plt.legend(['train loss', 'validation loss'], loc='upper left')\n    plt.show()\n        \n    #Plots training and validation accuracy\n    plt.figure()\n    plt.plot(history.history['sparse_categorical_accuracy'])\n    plt.plot(history.history['val_sparse_categorical_accuracy'])\n    plt.xlabel('Epochs')\n    plt.ylabel('Accuracy')\n    plt.legend(['train accuracy', 'validation accuracy'], loc='upper left')\n    plt.show()\n    return \n    ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train and predict","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"history_xception, model_xception = train(1)\nplot_train_and_val_stats(history_xception)\n\nhistory_resnet, model_resnet = train(2)\nplot_train_and_val_stats(history_resnet)\n\nhistory_densenet, model_densenet = train(3)\nplot_train_and_val_stats(history_densenet)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nprint('Computing predictions....')\ntest_images_ds = test_dataset.map(lambda image, idnum: image)\ntest_ids_ds = test_dataset.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')   \nprobabilities = 0.25*model_resnet.predict(test_images_ds)+0.25*model_xception.predict(test_images_ds)+0.5*model_densenet.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\n    \nprint('Compiling submission file...')\nnp.savetxt('submission.csv',np.rec.fromarrays([test_ids, predictions]),fmt=['%s', '%d'],delimiter=',',header='id,label',comments='')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Generate Confusion Matrix (individually and weighted model)\nCourtesy: Petal Helper & Chris Deotte","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def display_confusion_matrix(cmat, score, precision, recall):\n    plt.figure(figsize=(10,10))\n    ax = plt.gca()\n    ax.matshow(cmat, cmap='Reds')\n    ax.set_xticks(range(len(CLASSES)))\n    ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})\n    plt.setp(ax.get_xticklabels(), rotation=45, ha=\"left\", rotation_mode=\"anchor\")\n    ax.set_yticks(range(len(CLASSES)))\n    ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})\n    plt.setp(ax.get_yticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n    titlestring = \"\"\n    if score is not None:\n        titlestring += 'f1 = {:.3f} '.format(score)\n    if precision is not None:\n        titlestring += '\\nprecision = {:.3f} '.format(precision)\n    if recall is not None:\n        titlestring += '\\nrecall = {:.3f} '.format(recall)\n    if len(titlestring) > 0:\n        ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'#804040'})\n    plt.show()\n    \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Import relevant packages from SkLearn\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\n\ncmdataset = get_validation_dataset(load_dataset(VALIDATION_FILENAMES, labeled = True, ordered = True)) \nimages_ds = cmdataset.map(lambda image, label: image)\nlabels_ds = cmdataset.map(lambda image, label: label).unbatch()\n\n# Compute and display goodness of fit of Xception \ncm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy() \ncm_probabilities = model_xception.predict(images_ds)\ncm_predictions = np.argmax(cm_probabilities, axis=-1)\n\ncmat_1 = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))\nscore_1 = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\nprecision_1 = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\nrecall_1 = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\ncmat_1 = (cmat_1.T / cmat_1.sum(axis=1)).T \ndisplay_confusion_matrix(cmat_1, score_1, precision_1, recall_1)\n\n# Compute and display goodness of fit of ResNet50\ncm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy() \ncm_probabilities = model_resnet.predict(images_ds)\ncm_predictions = np.argmax(cm_probabilities, axis=-1)\n\ncmat_2 = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))\nscore_2 = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\nprecision_2 = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\nrecall_2 = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\ncmat_2 = (cmat_2.T / cmat_2.sum(axis=1)).T \ndisplay_confusion_matrix(cmat_2, score_2, precision_2, recall_2)\n\n# Compute and display goodness of fit of DenseNet201 \ncm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy() \ncm_probabilities = model_densenet.predict(images_ds)\ncm_predictions = np.argmax(cm_probabilities, axis=-1)\n\ncmat_3 = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))\nscore_3 = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\nprecision_3 = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\nrecall_3 = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\ncmat_3 = (cmat_3.T / cmat_3.sum(axis=1)).T \ndisplay_confusion_matrix(cmat_3, score_3, precision_3, recall_3)\n\n\n# Compute and display goodness of fit of the weighted model\ncm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy() \ncm_probabilities = 0.25*model_resnet.predict(images_ds)+0.25*model_xception.predict(images_ds)+0.5*model_densenet.predict(images_ds)\ncm_predictions = np.argmax(cm_probabilities, axis=-1)\n\ncmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))\nscore = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\nprecision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\nrecall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\ncmat = (cmat.T / cmat.sum(axis=1)).T \ndisplay_confusion_matrix(cmat, score, precision, recall)\n","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}