{"cells":[{"metadata":{"_uuid":"5e0c8a1e-8bd8-4943-b684-44ac9cdc6620","_cell_guid":"786eeb32-4ef5-4c81-9c87-cd079077ce2e","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":{"trusted":true},"cell_type":"code","source":"!pip install --quiet /kaggle/input/kerasapplications\n!pip install --quiet /kaggle/input/efficientnet-git","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"aeec83f6-c83a-43f9-8f11-55a573f7836c","_cell_guid":"6e283b85-2177-4105-bc80-ecf576db7083","trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport json\n\nfrom PIL import Image\nimport cv2\nimport seaborn as sb\n\n# Seb 06-01-21\nimport tensorflow as tf\nfrom tensorflow import keras\nimport json\nimport math, re, os\nfrom math import sqrt\n\nfrom kaggle_datasets import KaggleDatasets\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom functools import partial\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"main_dir = '../input/cassava-leaf-disease-classification/'\nos.listdir(main_dir) \ntrain_img_path = '../input/cassava-leaf-disease-classification/train_images'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Detect TPU\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Device:', tpu.master())\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nexcept:\n    strategy = tf.distribute.get_strategy()\nprint('Number of replicas:', strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# set up variables\nAUTOTUNE = tf.data.experimental.AUTOTUNE\nGCS_PATH = KaggleDatasets().get_gcs_path('cassava-leaf-disease-classification')\n\nGCS_NewTFPure512 = KaggleDatasets().get_gcs_path('cassava-leaf-disease-tfrecords-512x512')\nGCS_NewTFCenter512 = KaggleDatasets().get_gcs_path('cassava-leaf-disease-tfrecords-center-512x512')\n                                                 \nIMAGE_SIZE = [512,512]\nCLASSES = ['0', '1', '2', '3', '4']\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Model variables\nnets = 5\nmodel = [0] * nets\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nEPOCHS = 70\ninput_shape = (512,512,3)\ndropout_rate = 0.5\n\nlr_scheduler = keras.optimizers.schedules.ExponentialDecay(\n    initial_learning_rate=1e-5, \n    decay_steps=10000, \n    decay_rate=0.90)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames = [[0,0],[0,0],[0,0],[0,0],[0,0]]\nseeds = [1,2,105,103,108]\n\nfor split in range(nets):\n    filenames[split][0], filenames[split][1]= train_test_split(\n    tf.io.gfile.glob(GCS_NewTFPure512+ '/Id_train*.tfrec'),\n    test_size=0.3, random_state = seeds[split])\n\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test_tfrecords/ld_test00-1.tfrec')\n\nfilenames[0][1], filenames[1][1], filenames[2][1], filenames[3][1], filenames[4][1]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Functions for datasets"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Decode the data\n#turn the images into tensors\n#normalize the image (get every pixel to have a value between 0 and 1)\ndef decode_image(image):\n    image = tf.image.decode_jpeg(image, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#setting up variables X and y; in this case image and prediction (for images with no label)\ndef read_tfrecord(example, labeled):\n    tfrecord_format = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"target\": tf.io.FixedLenFeature([], tf.int64)\n    } if labeled else {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"image_name\": tf.io.FixedLenFeature([], tf.string)\n    }\n    example = tf.io.parse_single_example(example, tfrecord_format)\n    image = decode_image(example['image'])\n    if labeled:\n        label = tf.cast(example['target'], tf.int32)\n        return image, label\n    idnum = example['image_name']\n    return image, idnum","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# the following code will load the dataset using the TPU\ndef load_dataset(filenames, labeled=True, ordered=False):\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTOTUNE) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(partial(read_tfrecord, labeled=labeled), num_parallel_calls=AUTOTUNE)\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#The following functions will be used to load our training, validation, and test datasets, as well as print out the number of images in each dataset.\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)  \n    dataset = dataset.map(data_augment, num_parallel_calls=AUTOTUNE)  \n    dataset = dataset.repeat()\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTOTUNE)\n    return dataset\n\n\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(VALID_FILENAMES, labeled=True, ordered=ordered) \n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTOTUNE)\n    return dataset\n\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(AUTOTUNE)\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\n\n\n# NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\n# NUM_VALIDATION_IMAGES = count_data_items(VALID_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\n\n\n# print('Dataset: {} training images, {} validation images, {} (unlabeled) test images'.format(\n#     NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n#adding in augmentations\ndef data_augment(image, label):\n    # Thanks to the dataset.prefetch(AUTO) statement in the following function this happens essentially for free on TPU. \n    # Data pipeline code is executed on the \"CPU\" part of the TPU while the TPU itself is computing gradients.\n#    image = tf.image.random_flip_left_right(image)\n#     image = tf.image.random_contrast(image)\n#     image = tf.image.random_jpeg_quality(image)\n    return image, label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# # # load data\n# train_dataset = get_training_dataset()\n# valid_dataset = get_validation_dataset()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n# VALID_STEPS = NUM_VALIDATION_IMAGES // BATCH_SIZE","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"# from keras.optimizers import RMSprop, Adam\n# from keras.layers import DepthwiseConv2D, Reshape, Activation\n# import efficientnet.keras as efn\n# from tensorflow.keras import models\n# from tensorflow.keras import layers\n\n# for j in range(nets):\n#     with strategy.scope(): \n#         conv_base = efn.EfficientNetB3(weights='imagenet', include_top = False, input_shape = input_shape)\n#         model[j] = models.Sequential()\n#         model[j].add(conv_base)\n#         model[j].add(layers.GlobalMaxPooling2D(name=\"gap\"))\n#         model[j].add(layers.Dropout(dropout_rate, name=\"dropout_out\"))\n#         model[j].add(layers.Dense(5, activation=\"softmax\", name=\"fc_out\"))\n#         model[j].compile(\n#             optimizer=tf.keras.optimizers.Adam(learning_rate=lr_scheduler, epsilon=0.001),loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])  ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# for i in range(nets):\n#     model[i].summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# train_set = [0,0,0,0,0]\n# valid_set = [0,0,0,0,0]\n\n# for i in range(nets):\n#     TRAINING_FILENAMES = filenames[i][0]\n#     VALID_FILENAMES = filenames[i][1]\n    \n#     train_set[i] = get_training_dataset()\n#     valid_set[i] = get_validation_dataset()\n    \n    \n# print(train_set)\n# print(valid_set)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# # train for 20 epochs\n# history = [0] * nets\n# EPOCHS = 70\n\n# for j in range(nets):\n#     STEPS_PER_EPOCH = count_data_items(filenames[i][0]) // BATCH_SIZE\n#     VALID_STEPS = count_data_items(filenames[i][1]) // BATCH_SIZE\n#     print(f'Individual Net : {j+1}')   \n#     history[j] = model[j].fit(train_set[j], \n#                     steps_per_epoch=STEPS_PER_EPOCH, \n#                     epochs=EPOCHS,\n#                     validation_data=valid_set[j],\n#                     validation_steps=VALID_STEPS)\n\n#     print(\"CNN Model {0:d}: Epochs={1:d}, Training accuracy={2:.5f}, Validation accuracy={3:.5f}\".format(j+1,EPOCHS,max(history[j].history['sparse_categorical_accuracy']),max(history[j].history['val_sparse_categorical_accuracy']) ))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# for index in range (nets):\n#     model[index].save('model{}.h5'.format(index))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Predictions "},{"metadata":{"trusted":true},"cell_type":"code","source":"# def to_float32(image, label):\n#     return tf.cast(image, tf.float32), label\n\n# test_dataset = get_test_dataset()\n\n# test_ds = get_test_dataset(ordered=True) \n# test_ds = test_ds.map(to_float32)\n\n# test_images_ds = test_dataset\n# test_images_ds = test_ds.map(lambda image, idnum: image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# import sys\n# import numpy\n# numpy.set_printoptions(threshold=sys.maxsize)\n\n# #Result\n# results = np.zeros( (int(NUM_TEST_IMAGES),5) ) \n# for j in range(nets):\n#     #each model gives its predictions\n#     results = results + model[j].predict(test_images_ds)\n \n# #Finding the best prediction\n# predictions = np.argmax(results,axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# import matplotlib.pyplot as plt\n# test_dataset = get_test_dataset()\n\n\n# print('done')\n\n# for element in test_dataset.as_numpy_iterator(): \n#     plt.imshow(element[0][0])\n#     plt.title(predictions[0])\n#     print(element[1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# #Printing some images with predictions as titles - used only for visualization\n\n# L = 4\n# W = 4\n\n# fig, axes = plt.subplots(L, W, figsize = (12,12))\n# axes = axes.ravel()\n\n# for element in test_dataset.as_numpy_iterator(): \n#     for i in np.arange(0, L * W):  \n#         axes[i].imshow(element[0][i])\n#         axes[i].set_title(predictions[i])\n#         axes[i].axis('off')\n\n# plt.subplots_adjust(wspace=0.5)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Everything down below is not important"},{"metadata":{"trusted":true},"cell_type":"code","source":"# import efficientnet.keras as efn\n# from tensorflow.keras import models\n# from tensorflow.keras import layers\n\n# #model\n# # with strategy.scope():       \n# # #    img_adjust_layer = tf.keras.layers.Lambda(tf.keras.applications.efficientnet.preprocess_input, input_shape=[*IMAGE_SIZE, 3])\n    \n# # #     base_model = efn.EfficientNetB3(weights='imagenet')\n# #     conv_base = efn.EfficientNetB3(weights='imagenet', include_top = False, input_shape = input_shape)\n# #     model = models.Sequential()\n# #     model.add(conv_base)\n# #     model.add(layers.GlobalMaxPooling2D(name=\"gap\"))\n# #     model.add(layers.Dropout(dropout_rate, name=\"dropout_out\"))\n# #     model.add(layers.Dense(5, activation=\"softmax\", name=\"fc_out\"))\n\n# def evaluate_model(trainX, testX):\n# #     trainy_enc = to_categorical(trainy)\n# #     testy_enc = to_categorical(testy)\n#     # define model\n#     with strategy.scope():           \n#             conv_base = efn.EfficientNetB3(weights='imagenet', include_top = False, input_shape = input_shape)\n#             model = models.Sequential()\n#             model.add(conv_base)\n#             model.add(layers.GlobalMaxPooling2D(name=\"gap\"))\n#             model.add(layers.Dropout(dropout_rate, name=\"dropout_out\"))\n#             model.add(layers.Dense(5, activation=\"softmax\", name=\"fc_out\"))\n#             model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lr_scheduler, epsilon=0.001),loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])    \n\n#     #trainX is train_dataset; trainy_enc is valid_dataset\n#     model.fit(trainX, epochs=EPOCHS, verbose=0, steps_per_epoch=STEPS_PER_EPOCH)\n#     _, test_acc = model.evaluate(testX, verbose=0)\n#     return model, test_acc","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Because we're using a pre-trained model, we expect there to be a large number of non-trainable parameters (because the weights have already been assigned in the pre-trained model).\n\n# model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# #Evaluating our model\n# # print out variables available to us\n# print(history.history.keys())\n\n\n# # create learning curves to evaluate model performance\n# history_frame = pd.DataFrame(history.history)\n# history_frame.loc[:, ['loss', 'val_loss']].plot()\n# history_frame.loc[:, ['sparse_categorical_accuracy', 'val_sparse_categorical_accuracy']].plot();","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# def to_float32(image, label):\n#     return tf.cast(image, tf.float32), label\n\n# testing_dataset = get_test_dataset()\n# test_ds = get_test_dataset(ordered=True) \n# test_ds = test_ds.map(to_float32)\n\n# print('Computing predictions...')\n# test_images_ds = testing_dataset\n# test_images_ds = test_ds.map(lambda image, idnum: image)\n# probabilities = model.predict(test_images_ds)\n# predictions = np.argmax(probabilities, axis=-1)\n# print(predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# def dataset_to_numpy_util(dataset, N):\n#     dataset = dataset.unbatch().batch(N)\n#     for images, labels in dataset:\n#         numpy_images = images.numpy()\n#         numpy_labels = labels.numpy()\n#         break;  \n#     return numpy_images, numpy_labels\n\n# def title_from_label_and_target(label, correct_label):\n#     label = np.argmax(label, axis=-1)\n#     correct = (label == correct_label)\n#     return \"{} [{}{}{}]\".format(label, str(correct), ', shoud be ' if not correct else '',\n#                                 correct_label if not correct else ''), correct\n\n# def display_one_flower_eval(image, title, subplot, red=False):\n#     plt.subplot(subplot)\n#     plt.axis('off')\n#     plt.imshow(image)\n#     plt.title(title, fontsize=14, color='red' if red else 'black')\n#     return subplot+1\n\n# def display_9_images_with_predictions(images, predictions, labels):\n#     subplot=331\n#     plt.figure(figsize=(13,13))\n#     for i, image in enumerate(images):\n#         title, correct = title_from_label_and_target(predictions[i], labels[i])\n#         subplot = display_one_flower_eval(image, title, subplot, not correct)\n#         if i >= 8:\n#             break;\n              \n#     plt.tight_layout()\n#     plt.subplots_adjust(wspace=0.1, hspace=0.1)\n#     plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# x_samp, y_samp = dataset_to_numpy_util(testingg_dataset, 27)\n\n# x_samp_1, y_samp_1 = x_samp[:9,:,:,:], y_samp[:9]\n# samp_preds_1 = model.predict(x_samp_1, batch_size=9)\n# display_9_images_with_predictions(x_samp_1, samp_preds_1, y_samp_1)\n\n# x_samp_2, y_samp_2 = x_samp[9:,:,:,:], y_samp[9:]\n# samp_preds_2 = model.predict(x_samp_2, batch_size=9)\n# display_9_images_with_predictions(x_samp_2, samp_preds_2, y_samp_2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# def dataset_to_numpy(dataset):\n#     for images, labels in dataset:\n#         numpy_images = images.numpy()\n#         numpy_labels = labels.numpy()\n#         break;  \n#     return numpy_images, numpy_labels\n\n# def div(prediction, correct_labels, images):\n#     totalCount = NUM_TESTING_IMAGES\n#     hits = 0\n    \n#     for i, image in enumerate(images):\n#         prediction[i] = np.argmax(prediction[i], axis=-1)\n#         if ((prediction[i] == correct_labels[i]).any()):\n#             hits+=1\n\n# #     for index in range(0,totalCount-1):\n# #         if prediction[index] == correct_labels[index]:\n# #             hits+=1\n#     return'The amount of correct predictions is {} out of {} which means that the model has an accuracy of {}%'.format(hits,totalCount,round((hits/totalCount)*100),2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# print(testingg_dataset)\n# for images, labels in testingg_dataset:\n#         print(images.numpy())\n#         print(labels.numpy())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# samp_preds = model.predict(x_samp)\n# for predictions in samp_preds:\n#     print(predictions)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# #images = x_samp\n# #predictions = samp_preds\n# #labels = y_samp\n\n# # x_samp img, y_samp labels, samp_preds predictions\n# x_samp, y_samp = dataset_to_numpy(testingg_dataset)\n# samp_preds = model.predict(x_samp)\n# div(samp_preds,y_samp,x_samp)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# import efficientnet.keras as efn\n# from tensorflow.keras import models\n# from tensorflow.keras import layers\n\n# #model\n# with strategy.scope():       \n# #    img_adjust_layer = tf.keras.layers.Lambda(tf.keras.applications.efficientnet.preprocess_input, input_shape=[*IMAGE_SIZE, 3])\n    \n# #     base_model = efn.EfficientNetB3(weights='imagenet')\n#     conv_base = efn.EfficientNetB3(weights='imagenet', include_top = False, input_shape = input_shape)\n#     model = models.Sequential()\n#     model.add(conv_base)\n#     model.add(layers.GlobalMaxPooling2D(name=\"gap\"))\n#     model.add(layers.Dropout(dropout_rate, name=\"dropout_out\"))\n#     model.add(layers.Dense(5, activation=\"softmax\", name=\"fc_out\"))\n    \n\n\n#     model.compile(\n#         optimizer=tf.keras.optimizers.Adam(learning_rate=lr_scheduler, epsilon=0.001),\n#         loss='sparse_categorical_crossentropy',  \n#         metrics=['sparse_categorical_accuracy'])\n    \n#     model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# history = model.fit(train_dataset, \n#                     steps_per_epoch=STEPS_PER_EPOCH, \n#                     epochs=EPOCHS,\n#                     validation_data=valid_dataset,\n#                     validation_steps=VALID_STEPS)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# import efficientnet.keras as efn\n# from tensorflow.keras import models\n# from tensorflow.keras import layers\n\n# #model\n# # with strategy.scope():       \n# # #    img_adjust_layer = tf.keras.layers.Lambda(tf.keras.applications.efficientnet.preprocess_input, input_shape=[*IMAGE_SIZE, 3])\n    \n# # #     base_model = efn.EfficientNetB3(weights='imagenet')\n# #     conv_base = efn.EfficientNetB3(weights='imagenet', include_top = False, input_shape = input_shape)\n# #     model = models.Sequential()\n# #     model.add(conv_base)\n# #     model.add(layers.GlobalMaxPooling2D(name=\"gap\"))\n# #     model.add(layers.Dropout(dropout_rate, name=\"dropout_out\"))\n# #     model.add(layers.Dense(5, activation=\"softmax\", name=\"fc_out\"))\n\n# def evaluate_model(trainX, testX):\n# #     trainy_enc = to_categorical(trainy)\n# #     testy_enc = to_categorical(testy)\n#     # define model\n#     with strategy.scope():           \n#             conv_base = efn.EfficientNetB3(weights='imagenet', include_top = False, input_shape = input_shape)\n#             model = models.Sequential()\n#             model.add(conv_base)\n#             model.add(layers.GlobalMaxPooling2D(name=\"gap\"))\n#             model.add(layers.Dropout(dropout_rate, name=\"dropout_out\"))\n#             model.add(layers.Dense(5, activation=\"softmax\", name=\"fc_out\"))\n#             model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lr_scheduler, epsilon=0.001),loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])    \n\n#     #trainX is train_dataset; trainy_enc is valid_dataset\n#     model.fit(trainX, epochs=EPOCHS, verbose=0, steps_per_epoch=STEPS_PER_EPOCH)\n#     _, test_acc = model.evaluate(testX, verbose=0)\n#     return model, test_acc","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# def ensemble_predictions(members, testX):\n#     test_images_ds = testX\n#     test_images_ds = test_ds.map(lambda image, idnum: image)\n#     # make predictions\n#     yhats = [model.predict(test_images_ds) for model in members]\n#     yhats = array(yhats)\n#     # sum across ensemble members\n#     summed = numpy.sum(yhats, axis=0)\n#     # argmax across classes\n#     result = argmax(summed, axis=1)\n#     return result","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# from sklearn.metrics import accuracy_score\n# def evaluate_n_members(members, n_members, testX, testy):\n# \t# select a subset of members\n# \tsubset = members[:n_members]\n# \t# make prediction\n# \tyhat = ensemble_predictions(subset, testX)\n# \t# calculate accuracy\n# \treturn accuracy_score(testy, yhat)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# from sklearn.datasets import make_blobs\n\n# # generate 2d classification dataset\n# dataX, datay = make_blobs(n_samples=1427, centers=3, n_features=4, cluster_std=2, random_state=2)\n# X, newX = dataX[:5000, :], dataX[5000:, :]\n# y, newy = datay[:5000], datay[:]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# from matplotlib import pyplot\n# from numpy import mean\n# from numpy import std\n# import numpy\n# from numpy import array\n# from numpy import argmax\n\n# scores, members = list(), list()\n# model, test_acc = evaluate_model(train_dataset, valid_dataset)\n\n# print('>%.3f' % test_acc)\n# scores.append(test_acc)\n# members.append(model)\n    \n# print('Estimated Accuracy %.3f (%.3f)' % (mean(scores), std(scores)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# from keras.utils import to_categorical\n\n# single_scores, ensemble_scores = list(), list()\n\n# ensemble_score = evaluate_n_members(members, 1, testing_dataset, newy)\n# newy_enc = to_categorical(newy)\n# _, single_score = members[1-1].evaluate(newX, newy_enc, verbose=0)\n# print('> %d: single=%.3f, ensemble=%.3f' % (1, single_score, ensemble_score))\n# ensemble_scores.append(ensemble_score)\n# single_scores.append(single_score)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# print('Accuracy %.3f (%.3f)' % (mean(single_scores), std(single_scores)))\n# x_axis = [i for i in range(1, 0+1)]\n# pyplot.plot(x_axis, single_scores, marker='o', linestyle='None')\n# pyplot.plot(x_axis, ensemble_scores, marker='o')\n# pyplot.show()","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}