{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install efficientnet","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \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 \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n# import os\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\n# # Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import os, re\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nimport efficientnet.tfkeras as enet\nfrom kaggle_datasets import KaggleDatasets\nfrom keras.preprocessing.image import ImageDataGenerator\ndatagen = ImageDataGenerator(zca_whitening=True)\n\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\nimport os, sys, math\nAUTO = tf.data.experimental.AUTOTUNE # used in tf.data.Dataset API\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#tf.debugging.set_log_device_placement(True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# TPU HARDWARE DETECT\n\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":"# TRAIN_IMG_PATH = '../input/flower-classification-with-tpus/tfrecords-jpeg-192x192/train/' \n# VALID_IMG_PATH = '../input/flower-classification-with-tpus/tfrecords-jpeg-192x192/val/' \n# TEST_IMG_PATH = '../input/flower-classification-with-tpus/tfrecords-jpeg-192x192/test/'\n\n\n# Data access\nGCS_DS_PATH = KaggleDatasets().get_gcs_path()\n\n# Configuration\nTARGET_SIZE = [512, 512]\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}\nGCS_PATH = GCS_PATH_SELECT[TARGET_SIZE[0]]\n\nTRAIN_IMG_PATH = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')\nVALID_IMG_PATH = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\nTEST_IMG_PATH = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec') # predictions on this dataset should be submitted for \n\nEPOCHS = 45\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# CLASSES = ['pink primrose',    'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea',     'wild geranium',     'tiger lily', \n#            'moon orchid',              'bird of paradise', 'monkshood',        'globe thistle',         # 00 - 09\n#            'snapdragon',       \"colt's foot\",               'king protea',      'spear thistle', 'yellow iris',       'globe-flower', \n#            'purple coneflower',        'peruvian lily',    'balloon flower',   'giant white arum lily', # 10 - 19\n#            'fire lily',        'pincushion flower',         'fritillary',       'red ginger',    'grape hyacinth',    'corn poppy', \n#            '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',\n#            'cape flower',              'great masterwort', 'siam tulip',       'lenten rose',           # 30 - 39\n#            'barberton daisy',  'daffodil',                  'sword lily',       'poinsettia',    'bolero deep blue',  'wallflower',   \n#            'marigold',                 'buttercup',        'daisy',            'common dandelion',      # 40 - 49\n#            'petunia',          'wild pansy',                'primula',          'sunflower',     'lilac hibiscus',    'bishop of llandaff', \n#            'gaura',                    'geranium',         'orange dahlia',    'pink-yellow dahlia',    # 50 - 59\n#            'cautleya spicata', 'japanese anemone',          'black-eyed susan', 'silverbush',    'californian poppy', 'osteospermum',    \n#            'spring crocus',            'iris',             'windflower',       'tree poppy',            # 60 - 69\n#            'gazania',          'azalea',                    'water lily',       'rose',          'thorn apple',       'morning glory',    \n#            'passion flower',           'lotus',            'toad lily',        'anthurium',             # 70 - 79\n#            'frangipani',       'clematis',                  'hibiscus',         'columbine',     'desert-rose',       'tree mallow',      \n#            'magnolia',                 'cyclamen ',        'watercress',       'canna lily',            # 80 - 89\n#            'hippeastrum ',     'bee balm',                  'pink quill',       'foxglove',      'bougainvillea',     'camellia',     \n#            'mallow',                   'mexican petunia',  'bromelia',         'blanket flower',        # 90 - 99\n#            'trumpet creeper',  'blackberry lily',           'common tulip',     'wild rose']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# tf-record file read\ndef tfrecord_fn(record):\n    columns = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"class\": tf.io.FixedLenFeature([], tf.int64)\n    }\n    \n    # decode the tfrecord\n    example = tf.io.parse_single_example(record, columns)\n    image = tf.image.decode_jpeg(example['image'], channels=3)\n    image = tf.reshape(image, [*TARGET_SIZE, 3])\n    label = tf.cast(example['class'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# set experimental_deterministic = False to read from multiple files\n\noption_no_order = tf.data.Options()\noption_no_order.experimental_deterministic = False\n\nfilenames = tf.io.gfile.glob(TRAIN_IMG_PATH)\ndataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)\ndataset = dataset.with_options(option_no_order)\ndataset = dataset.map(tfrecord_fn, num_parallel_calls=AUTO)\ndataset = dataset.shuffle(2048)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for image, label in dataset.take(4):\n    print(label.numpy())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(15,15))\nsubCount = 1   # # plot number\nrowCount =3      # No of images in row\ncolCount =4      # No of images in columns\n\nfor i, (image, label) in enumerate(dataset):\n    plt.subplot(rowCount, colCount, subCount)\n    plt.axis('off')\n    plt.imshow(image.numpy().astype(np.uint8))\n    plt.title(label.numpy(), fontsize=16)\n    subCount = subCount + 1\n    if i ==11:           # (row*column)-1\n        break\nplt.tight_layout()\nplt.subplots_adjust(wspace=0.1, hspace=0.1)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# tf-record label file read\ndef tfrecord_label_fn(record):\n    columns = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"class\": tf.io.FixedLenFeature([], tf.int64)\n    }\n    \n    # decode the tfrecord\n    example = tf.io.parse_single_example(record, columns)\n    image = tf.image.decode_jpeg(example['image'], channels=3)\n    \n    image = tf.image.convert_image_dtype(image, dtype=tf.float32) # 0-1\n    \n    #image = tf.cast(image, tf.float32)# //255.0            # supported data type tf.float32, tf.int32, tf.bfloat16 \n    image = tf.reshape(image, [*TARGET_SIZE, 3])\n    #image = datagen.fit(image)\n    label = tf.cast(example['class'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# tf-record unlabelled file read\ndef tfrecord_unlabel_fn(record):\n    columns = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"id\": tf.io.FixedLenFeature([], tf.string)\n    }\n    \n    # decode the tfrecord\n    example = tf.io.parse_single_example(record, columns)\n    image = tf.image.decode_jpeg(example['image'], channels=3)\n    image = tf.image.convert_image_dtype(image, dtype=tf.float32) # 0-1\n    \n    #image = tf.cast(image, tf.float32)# //255.0                  # supported data type tf.float32, tf.int32, tf.bfloat16 \n    image = tf.reshape(image, [*TARGET_SIZE, 3])\n    # fit parameters from data\n#    image = datagen.fit(image)\n    idn = example['id']\n    return image, idn # returns a dataset of (image, id) pairs\n\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def data_augment(image, label):\n    # data augmentation. Thanks to the dataset.prefetch(AUTO) statement in the next function (below),\n    # this happens essentially for free on TPU. Data pipeline code is executed on the \"CPU\" part\n    # of the TPU while the TPU itself is computing gradients.\n    image = tf.image.random_flip_left_right(image)\n    #image = tf.image.random_saturation(image, 0, 2)\n    return image, label   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def training_data_fn():\n    # set experimental_deterministic = False to read from multiple files\n\n    option_no_order = tf.data.Options()\n    option_no_order.experimental_deterministic = False\n\n    filenames = tf.io.gfile.glob(TRAIN_IMG_PATH)\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)\n    dataset = dataset.with_options(option_no_order)\n    dataset = dataset.map(tfrecord_label_fn, num_parallel_calls=AUTO)\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def validation_data_fn():\n    # set experimental_deterministic = False to read from multiple files\n\n    option_no_order = tf.data.Options()\n    option_no_order.experimental_deterministic = False\n\n    filenames = tf.io.gfile.glob(VALID_IMG_PATH)\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)\n    dataset = dataset.with_options(option_no_order)\n    dataset = dataset.map(tfrecord_label_fn, num_parallel_calls=AUTO)\n    #dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    #dataset = dataset.shuffle(2048)\n    dataset = dataset.cache()\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def test_data_fn():\n    # set experimental_deterministic = False to read from multiple files \n\n    option_no_order = tf.data.Options()\n    option_no_order.experimental_deterministic = False\n\n    filenames = tf.io.gfile.glob(TEST_IMG_PATH)\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)\n    dataset = dataset.with_options(option_no_order)\n    dataset = dataset.map(tfrecord_unlabel_fn, num_parallel_calls=AUTO)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot function to diaplay the images of the dataset\ndef plot_view_fn(dataset, num_row, num_col):\n    plt.figure(figsize=(13,13))\n    subCount = 1   # # plot number\n    rowCount =num_row      # No of images in row\n    colCount =num_col      # No of images in columns\n\n    for i, (image, label) in enumerate(dataset):\n        plt.subplot(rowCount, colCount, subCount)\n        plt.axis('off')\n        plt.imshow(image.numpy().astype(np.uint8)) \n        plt.title(label.numpy(), fontsize=16)\n        subCount = subCount + 1\n        if i ==(rowCount*colCount)-1:           # (row*column)-1\n            break\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":"# # Plot function to diaplay the images of the dataset\n# def plot_view_fn(dataset, num_row, num_col, label=True):\n#     plt.figure(figsize=(13,13))\n#     subCount = 1   # # plot number\n#     rowCount =num_row      # No of images in row\n#     colCount =num_col      # No of images in columns\n\n#     for i, (image, label) in enumerate(dataset):\n#         plt.subplot(rowCount, colCount, subCount)\n#         plt.axis('off')\n#         plt.imshow(image.numpy().astype(np.uint8))\n#         if label is False:\n#             plt.title('')\n#         else:\n#             plt.title(label.numpy(), fontsize=16)\n#         subCount = subCount + 1\n#         if i ==(rowCount*colCount)-1:           # (row*column)-1\n#             break\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":"# # View the training Dataset\n# training_dataset = training_data_fn()\n# training_dataset = training_dataset.unbatch()\n# train_batch = iter(training_dataset)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot_view_fn(train_batch, 3, 4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# # View the validation Dataset\n# validation_dataset = validation_data_fn()\n# validation_dataset = validation_dataset.unbatch()\n# valid_batch = iter(validation_dataset)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot_view_fn(valid_batch, 4, 4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# # View the test Dataset\n# test_dataset = test_data_fn()\n# test_dataset = test_dataset.unbatch()\n# test_batch = iter(test_dataset)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot_view_fn(test_batch, 4, 4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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 = count_data_items(TRAIN_IMG_PATH)\nNUM_VALIDATION_IMAGES = count_data_items(VALID_IMG_PATH)\nNUM_TEST_IMAGES = count_data_items(TEST_IMG_PATH)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\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":"# Training"},{"metadata":{"trusted":true},"cell_type":"code","source":"# For TPU TRAINING\n\nwith strategy.scope():\n# EfficientNetB7\n    enet = enet.EfficientNetB7(\n        input_shape=(512, 512, 3),\n        weights='imagenet',\n        include_top=False\n    )\n    enet.trainable = True\n\n    model = tf.keras.Sequential([\n        enet,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# For GPU TRAINING\n\n# with tf.device('/GPU:0'): \n    \n#     # EfficientNetB7\n\n#     enet = enet.EfficientNetB7(\n#             input_shape=(192, 192, 3),\n#             weights='imagenet',\n#             include_top=False\n#         )\n\n#     model = tf.keras.Sequential([\n#             enet,\n#             tf.keras.layers.GlobalAveragePooling2D(),\n#             tf.keras.layers.Dense(104, activation='softmax')\n#         ])\n\n\n    \n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# # EfficientNetB7\n\n# enet = enet.EfficientNetB7(\n#         input_shape=(192, 192, 3),\n#         weights='imagenet',\n#         include_top=False\n#     )\n\n# model = tf.keras.Sequential([\n#         enet,\n#         tf.keras.layers.GlobalAveragePooling2D(),\n#         tf.keras.layers.Dense(104, activation='softmax')\n#     ])\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(\n    optimizer=tf.keras.optimizers.Adam(learning_rate=1.5e-05, beta_1=0.9, beta_2=0.99, amsgrad=False),\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#model.get_layer('dense').kernel_regularizer = tf.keras.regularizers.l2(0.0001) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# model.compile(\n#     optimizer=tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.99, amsgrad=False),\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":"# def lr_fn(epoch):\n#     LR_START = 0.00001\n#     LR_MAX = 0.00005 * strategy.num_replicas_in_sync\n#     LR_MIN = 0.00001\n#     LR_RAMPUP_EPOCHS = 10\n#     LR_SUSTAIN_EPOCHS = 0\n#     LR_EXP_DECAY = .8\n    \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# lr_callback = tf.keras.callbacks.LearningRateScheduler(lr_fn, verbose=True)\n# rng = [i for i in range(EPOCHS)]\n# y = [lr_fn(x) for x in rng]\n# plt.plot(rng, y)\n# print(\"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":"# lr_schedule = tf.keras.callbacks.LearningRateScheduler(lr_fn, verbose=1)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Early stopping\ncallback_stop = tf.keras.callbacks.EarlyStopping(min_delta=0, patience=5, verbose=1, mode='auto', restore_best_weights=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(\n    training_data_fn(),\n    steps_per_epoch=STEPS_PER_EPOCH,\n    epochs=EPOCHS, \n    callbacks=[callback_stop],   #callbacks = [tf.keras.callbacks.EarlyStopping(monitor='val_sparse_categorical_accuracy',\n    validation_data=validation_data_fn()\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['loss'], label='train loss')\nplt.plot(history.history['val_loss'], label='val loss')\nplt.xlabel(\"epoch\")\nplt.ylabel(\"Cross-entropy loss\")\nplt.legend();\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['sparse_categorical_accuracy'], label='train accuracy')\nplt.plot(history.history['val_sparse_categorical_accuracy'], label='val accuracy')\nplt.xlabel(\"epoch\")\nplt.ylabel(\"categorical_accuracy\")\nplt.legend();\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cmdataset = validation_data_fn()\nimages_ds = cmdataset.map(lambda image, label: image)\nlabels_ds = cmdataset.map(lambda image, label: label).unbatch()\ncm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy() # get everything as one batch\ncm_probabilities = model.predict(images_ds)\ncm_predictions = np.argmax(cm_probabilities, axis=-1)\nprint(\"Correct   labels: \", cm_correct_labels.shape, cm_correct_labels)\nprint(\"Predicted labels: \", cm_predictions.shape, cm_predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"score = f1_score(cm_correct_labels, cm_predictions, labels=range(104), average='macro')\nprecision = precision_score(cm_correct_labels, cm_predictions, labels=range(104), average='macro')\nrecall = recall_score(cm_correct_labels, cm_predictions, labels=range(104), average='macro')\nprint('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_ds = test_data_fn()\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idn: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)\n\nprint('Generating submission.csv file...')\ntest_ids_ds = test_ds.map(lambda image, idn: idn).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# from keras import backend as K\n\n# def recall_m(y_true, y_pred):\n#     true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n#     possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n#     recall = true_positives / (possible_positives + K.epsilon())\n#     return recall\n\n# def precision_m(y_true, y_pred):\n#     true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n#     predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n#     precision = true_positives / (predicted_positives + K.epsilon())\n#     return precision\n\n# def f1_m(y_true, y_pred):\n#     precision = precision_m(y_true, y_pred)\n#     recall = recall_m(y_true, y_pred)\n#     return 2*((precision*recall)/(precision+recall+K.epsilon()))\n\n\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# model.compile(\n#     optimizer=tf.keras.optimizers.Adam(learning_rate=1.5e-05, beta_1=0.9, beta_2=0.99, amsgrad=False),\n#     loss = 'sparse_categorical_crossentropy',\n#     metrics=['acc',f1_m]#metrics=['sparse_categorical_accuracy'] metrics=['acc',f1_m,precision_m, recall_m]\n# )\n# model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# history01 = model.fit(\n#     training_data_fn(),\n#     steps_per_epoch=STEPS_PER_EPOCH,\n#     epochs=EPOCHS, \n#     callbacks=[callback_stop],   #callbacks = [tf.keras.callbacks.EarlyStopping(monitor='val_sparse_categorical_accuracy',\n#     validation_data=validation_data_fn()\n# )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}