{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Oversample the training dataset\n\nThis notebook shows how to perform oversample. In order to avoid the same images appear too many times, we also use Chris Deotte's data augmentation.\n\n* Reference for oversampling, see [Classification on imbalanced data](https://www.tensorflow.org/tutorials/structured_data/imbalanced_data).\n\n* Why oversampling instead of using sample weights or class weights: (from the above link)\n\n\n\n> If the training process were considering the whole dataset on each gradient update, this oversampling would be basically identical to the class weighting.\n\n> But when training the model batch-wise, as you did here, the oversampled data provides a smoother gradient signal: Instead of each positive example being shown in one batch with a large weight, they're shown in many different batches each time with a small weight.\n\n> This smoother gradient signal makes it easier to train the model.\n"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"import math, re, os\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix, accuracy_score\nimport datetime\nimport tqdm\nimport json\nfrom collections import Counter\nimport gc\ngc.enable()\nprint(\"Tensorflow version \" + tf.__version__)\nAUTO = tf.data.experimental.AUTOTUNE","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Configurations"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\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() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE\n\n# Configuration\nIMAGE_SIZE = [192, 192]\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nEPOCHS = 20","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Directories"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Data access\nGCS_DS_PATH = KaggleDatasets().get_gcs_path()\n\nGCS_PATH_SELECT = { # available image sizes\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]]\n\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec') # predictions on this dataset should be submitted for the competition","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Classes"},{"metadata":{"trusted":true},"cell_type":"code","source":"CLASSES = ['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']                                                                                                                                               # 100 - 102","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Dataset Functions\nFrom starter [kernel][1]\n\n[1]: https://www.kaggle.com/mgornergoogle/getting-started-with-100-flowers-on-tpu"},{"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 # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled = True, ordered = False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # Diregarding data order. Order does not matter since we will be shuffling the data anyway\n    \n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n        \n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads = AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # use data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls = AUTO) # returns a dataset of (image, label) pairs if labeled = True or (image, id) pair if labeld = False\n    return dataset\n\ndef get_training_dataset():\n    \n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    dataset = dataset.repeat() # Since we use custom training loop, we don't need to use repeat() here.\n    dataset = dataset.shuffle(20000)\n    dataset = dataset.batch(BATCH_SIZE, drop_remainder=False)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    \n    return dataset  \n\ndef get_validation_dataset():\n    \n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=True)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\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) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nNUM_TRAINING_IMAGES = int(count_data_items(TRAINING_FILENAMES))\nNUM_VALIDATION_IMAGES = int(count_data_items(VALIDATION_FILENAMES))\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\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":"# Oversample\n### Also include Chris Deotte's data augmentation"},{"metadata":{},"cell_type":"markdown","source":"## 1 - Get labels and their countings"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Get labels and their countings\n\ndef get_training_dataset_raw():\n\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True, ordered=False)\n    return dataset\n\n\nraw_training_dataset = get_training_dataset_raw()\n\nlabel_counter = Counter()\nfor images, labels in raw_training_dataset:\n    label_counter.update([labels.numpy()])\n\ndel raw_training_dataset    \n    \nlabel_counting_sorted = label_counter.most_common()\n\nNUM_TRAINING_IMAGES = sum([x[1] for x in label_counting_sorted])\nprint(\"number of examples in the original training dataset: {}\".format(NUM_TRAINING_IMAGES))\n\nprint(\"labels in the original training dataset, sorted by occurrence\")\nlabel_counting_sorted","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 2 - Define the number of repetitions for each class"},{"metadata":{"trusted":true},"cell_type":"code","source":"# We want each class occur at least (approximately) `TARGET_MIN_COUNTING` times\nTARGET_MIN_COUNTING = 100\n\ndef get_num_of_repetition_for_class(class_id):\n    \n    counting = label_counter[class_id]\n    if counting >= TARGET_MIN_COUNTING:\n        return 1.0\n    \n    num_to_repeat = TARGET_MIN_COUNTING / counting\n    \n    return num_to_repeat\n\nnumbers_of_repetition_for_classes = {class_id: get_num_of_repetition_for_class(class_id) for class_id in range(104)}\n\nprint(\"number of repetitions for each class (if > 1)\")\n{k: v for k, v in sorted(numbers_of_repetition_for_classes.items(), key=lambda item: item[1], reverse=True) if v > 1}","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 3 - Define the number of repetitions for each training example"},{"metadata":{"trusted":true},"cell_type":"code","source":"# This will be called later in `get_training_dataset_with_oversample()`\n\nkeys_tensor = tf.constant([k for k in numbers_of_repetition_for_classes])\nvals_tensor = tf.constant([numbers_of_repetition_for_classes[k] for k in numbers_of_repetition_for_classes])\ntable = tf.lookup.StaticHashTable(tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor), -1)\n\ndef get_num_of_repetition_for_example(training_example):\n    \n    _, label = training_example\n    \n    num_to_repeat = table.lookup(label)\n    num_to_repeat_integral = tf.cast(int(num_to_repeat), tf.float32)\n    residue = num_to_repeat - num_to_repeat_integral\n    \n    num_to_repeat = num_to_repeat_integral + tf.cast(tf.random.uniform(shape=()) <= residue, tf.float32)\n    \n    return tf.cast(num_to_repeat, tf.int64)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 4 - Use data augmentation to avoid (exactly) same images appear too many times"},{"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":"## 5 - A method to get oversampled training dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_training_dataset_with_oversample(repeat_dataset=True, oversample=False, augumentation=False):\n\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n\n    if oversample:\n        dataset = dataset.flat_map(lambda image, label: tf.data.Dataset.from_tensors((image, label)).repeat(get_num_of_repetition_for_example((image, label))))\n\n    if augumentation:\n        dataset = dataset.map(transform, num_parallel_calls=AUTO)\n    \n    if repeat_dataset:\n        dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    \n    dataset = dataset.shuffle(20000)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    \n    return dataset","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 6 - Check oversampled dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"oversampled_training_dataset = get_training_dataset_with_oversample(repeat_dataset=False, oversample=True, augumentation=False)\n\nlabel_counter_2 = Counter()\nfor images, labels in oversampled_training_dataset:\n    label_counter_2.update(labels.numpy())\n\ndel oversampled_training_dataset\n\nlabel_counting_sorted_2 = label_counter_2.most_common()\n\nNUM_TRAINING_IMAGES_OVERSAMPLED = sum([x[1] for x in label_counting_sorted_2])\nprint(\"number of examples in the oversampled training dataset: {}\".format(NUM_TRAINING_IMAGES_OVERSAMPLED))\n\nprint(\"labels in the oversampled training dataset, sorted by occurrence\")\nlabel_counting_sorted_2","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Common things for training"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Learning rate schedule for TPU, GPU and CPU.\n# Using an LR ramp up because fine-tuning a pre-trained model.\n# Starting with a high LR would break the pre-trained weights.\n\nLR_START = 0.00001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 5\nLR_SUSTAIN_EPOCHS = 0\nLR_EXP_DECAY = .8\n\ndef lrfn(epoch):\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    \nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)\n\nrng = [i for i in range(25 if EPOCHS<25 else EPOCHS)]\ny = [lrfn(x) for x in rng]\nplt.plot(rng, y)\nprint(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"valid_ds = get_validation_dataset()\n\nvalid_images_ds = valid_ds.map(lambda image, label: image)\nvalid_labels_ds = valid_ds.map(lambda image, label: label).unbatch()\n\nvalid_labels = next(iter(valid_labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy() # get everything as one batch\n\nvalid_steps = NUM_VALIDATION_IMAGES // BATCH_SIZE\n\nif NUM_VALIDATION_IMAGES % BATCH_SIZE > 0:\n    valid_steps += 1","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train on the original training dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"original_training_dataset = get_training_dataset_with_oversample(repeat_dataset=True, oversample=False, augumentation=False)\n\nwith strategy.scope():\n\n    model = tf.keras.Sequential([\n        tf.keras.applications.DenseNet201(input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3), weights='imagenet', include_top=False),\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n\nmodel.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nhistory = model.fit(\n    original_training_dataset, \n    steps_per_epoch=NUM_TRAINING_IMAGES // BATCH_SIZE,\n    epochs=EPOCHS,\n    callbacks=[lr_callback],\n    validation_data=valid_ds\n)\n\nvalid_probs = model.predict(valid_images_ds, steps=valid_steps)\nvalid_preds = np.argmax(valid_probs, axis=-1)\n\ndel model\ngc.collect()\ntf.keras.backend.clear_session()\n\nval_acc = history.history['val_sparse_categorical_accuracy']\n\nscore = f1_score(valid_labels, valid_preds, labels=range(len(CLASSES)), average='macro')\nacc = accuracy_score(valid_labels, valid_preds)\nprecision = precision_score(valid_labels, valid_preds, labels=range(len(CLASSES)), average='macro')\nrecall = recall_score(valid_labels, valid_preds, labels=range(len(CLASSES)), average='macro')\n\nprint(\"results for training on the original dataset\")\nprint(\"best 10 validation accuracies during training = {}\".format(sorted(val_acc, reverse=True)[:10]))\nprint('f1 score: {:.6f} | recall: {:.6f} | precision: {:.6f} | acc: {:.6f}'.format(score, recall, precision, acc))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train on oversampled dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"oversampled_training_dataset = get_training_dataset_with_oversample(repeat_dataset=True, oversample=True, augumentation=True)\n\n\nwith strategy.scope():\n\n    model = tf.keras.Sequential([\n        tf.keras.applications.DenseNet201(input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3), weights='imagenet', include_top=False),\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n\nmodel.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nhistory = model.fit(\n    oversampled_training_dataset, \n    steps_per_epoch=NUM_TRAINING_IMAGES_OVERSAMPLED // BATCH_SIZE,\n    epochs=EPOCHS,\n    callbacks=[lr_callback],\n    validation_data=valid_ds\n)\n\nvalid_probs = model.predict(valid_images_ds, steps=valid_steps)\nvalid_preds = np.argmax(valid_probs, axis=-1)\n\ndel model\ngc.collect()\ntf.keras.backend.clear_session()\n\nval_acc = history.history['val_sparse_categorical_accuracy']\n\nscore = f1_score(valid_labels, valid_preds, labels=range(len(CLASSES)), average='macro')\nacc = accuracy_score(valid_labels, valid_preds)\nprecision = precision_score(valid_labels, valid_preds, labels=range(len(CLASSES)), average='macro')\nrecall = recall_score(valid_labels, valid_preds, labels=range(len(CLASSES)), average='macro')\n\nprint(\"results for training on the oversampled dataset\")\nprint(\"best 10 validation accuracies during training = {}\".format(sorted(val_acc, reverse=True)[:10]))\nprint('f1 score: {:.6f} | recall: {:.6f} | precision: {:.6f} | acc: {:.6f}'.format(score, recall, precision, acc))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Results from my own training"},{"metadata":{"trusted":true},"cell_type":"code","source":"result_1 = {\n    \"EfficientNetB7\": {\n        \"oversampling\": {\n            \"1\": {\n                \"f1\": 0.9163497711078313,\n                \"recall\": 0.9205266060440362,\n                \"precision\": 0.919277486006819,\n                \"acc\": 0.9240301724137931\n            },\n            \"100\": {\n                \"f1\": 0.9306967499560146,\n                \"recall\": 0.9385304126936429,\n                \"precision\": 0.9277303112649578,\n                \"acc\": 0.9296875\n            },\n            \"300\": {\n                \"f1\": 0.9361016120193594,\n                \"recall\": 0.9394270473352216,\n                \"precision\": 0.939168918056952,\n                \"acc\": 0.9366918103448276\n            },\n            \"800\": {\n                \"f1\": 0.9404645585115528,\n                \"recall\": 0.9427588505810944,\n                \"precision\": 0.9440889947725051,\n                \"acc\": 0.9391163793103449\n            }\n        }\n    }\n}\n\nprint(json.dumps(result_1, ensure_ascii=False, indent=4))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result_2 = {\n    \"DenseNet201\": {\n        \"oversampling\": {\n            \"1\": {\n                \"f1\": 0.9249583259975988,\n                \"recall\": 0.9147673084901355,\n                \"precision\": 0.9413584080076393,\n                \"acc\": 0.9275323275862069\n            },\n            \"100\": {\n                \"f1\": 0.9335555346943241,\n                \"recall\": 0.934321682931082,\n                \"precision\": 0.9383416676577636,\n                \"acc\": 0.9337284482758621\n            },\n            \"300\": {\n                \"f1\": 0.9343192665802171,\n                \"recall\": 0.9355079525776551,\n                \"precision\": 0.9384803240387035,\n                \"acc\": 0.9331896551724138\n            },\n            \"800\": {\n                \"f1\": 0.9389981148396047,\n                \"recall\": 0.9403390782293726,\n                \"precision\": 0.9426095000332035,\n                \"acc\": 0.9348060344827587\n            }\n        }\n    }\n}\n\nprint(json.dumps(result_2, ensure_ascii=False, indent=4))","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":4}