{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"### 0. Preparations","metadata":{"execution":{"iopub.status.busy":"2023-08-28T04:19:19.430501Z","iopub.execute_input":"2023-08-28T04:19:19.431290Z","iopub.status.idle":"2023-08-28T04:19:20.499797Z","shell.execute_reply.started":"2023-08-28T04:19:19.431253Z","shell.execute_reply":"2023-08-28T04:19:20.498390Z"}}},{"cell_type":"code","source":"import math\nimport re\nimport os\nimport numpy as np\nimport random\n\n# tf imports\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow_addons.metrics import F1Score\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom tensorflow.keras import applications as tf_app\n\nfrom sklearn.metrics import (f1_score,\n                             precision_score,\n                             recall_score,\n                             confusion_matrix)\n\n# input data\nfrom kaggle_datasets import KaggleDatasets\n\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2023-08-28T14:54:18.848715Z","iopub.execute_input":"2023-08-28T14:54:18.849066Z","iopub.status.idle":"2023-08-28T14:55:00.682044Z","shell.execute_reply.started":"2023-08-28T14:54:18.849035Z","shell.execute_reply":"2023-08-28T14:55:00.680833Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\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.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() \n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2023-08-28T14:55:00.683957Z","iopub.execute_input":"2023-08-28T14:55:00.684641Z","iopub.status.idle":"2023-08-28T14:55:09.732631Z","shell.execute_reply.started":"2023-08-28T14:55:00.684608Z","shell.execute_reply":"2023-08-28T14:55:09.731243Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 1. Parameters","metadata":{}},{"cell_type":"code","source":"SEED = 1005\nIMAGE_SIZE = (512, 512)  # 192, 224, 331, 512\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync  # Define the batch size. This will be 16 with TPU off and 128 (=16*8) with TPU on\nEPOCHS = 15\nMAX_LR = 0.00005 * strategy.num_replicas_in_sync\nnet_type = tf_app               # tf_app, efn\nmodel_type = 'DenseNet201'      # 'EfficientNetB7', 'Xception', 'DenseNet201'\nmodel_weights = 'imagenet'      # 'imagenet' ('noisy-student' for efn)\ntrain_base = True","metadata":{"execution":{"iopub.status.busy":"2023-08-28T14:57:16.272739Z","iopub.execute_input":"2023-08-28T14:57:16.273211Z","iopub.status.idle":"2023-08-28T14:57:16.279791Z","shell.execute_reply.started":"2023-08-28T14:57:16.273167Z","shell.execute_reply":"2023-08-28T14:57:16.278848Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 2. Custom Functions","metadata":{}},{"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\"\"\"\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    return (\n        # automatically interleaves reads from multiple files\n        tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)\n        .with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n        .map(read_labeled_tfrecord          # returns a dataset of (image, label) pairs\n             if labeled                     # if labeled=True\n             else read_unlabeled_tfrecord,  # or (image, id) pairs if labeled=False\n             num_parallel_calls=AUTO)\n    )\n\n# Define a function to rescale images\ndef rescale_images(image, label):\n    image = tf.cast(image, tf.float32) / 255.0  # Rescale pixel values to [0, 1]\n    return image, label\n\ndef augment_data(image, label):\n    # Random horizontal and vertical flips\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n    \n    # Random adjustments to brightness, contrast, and saturation\n    image = tf.image.random_brightness(image, max_delta=0.2)\n    image = tf.image.random_contrast(image, lower=0.8, upper=1.2)\n    image = tf.image.random_saturation(image, lower=0.8, upper=1.2)\n    \n    # Random cropping and resizing to the original size\n    image = tf.image.random_crop(image, size=[*IMAGE_SIZE, 3])\n    image = tf.image.resize(image, size=IMAGE_SIZE)\n    \n    return image, label\n\ndef get_training_dataset(filenames, ordered=False):\n    return (\n        load_dataset(filenames, labeled=True, ordered=ordered)\n        .map(augment_data, num_parallel_calls=AUTO)\n#         .map(rescale_images, num_parallel_calls=AUTO)  # Add rescaling here\n        .repeat() # the training dataset must repeat for several epochs\n        .shuffle(buffer_size=2048)\n        .batch(BATCH_SIZE)\n        .prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    )\n\ndef get_validation_dataset(filenames, ordered=False):\n    return (\n        load_dataset(filenames, labeled=True, ordered=ordered)\n#         .map(rescale_images, num_parallel_calls=AUTO)  # Add rescaling here\n        .batch(BATCH_SIZE)\n        .cache()\n        .prefetch(AUTO)\n    )\n\ndef get_test_dataset(filenames, ordered=False):\n    return (\n        load_dataset(filenames, labeled=False, ordered=ordered)\n#         .map(rescale_images, num_parallel_calls=AUTO)  # Add rescaling here\n        .batch(BATCH_SIZE)\n        .prefetch(AUTO)\n    )\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec\n    # 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\ndef seed_everything(seed=SEED):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    tf.random.set_seed(seed)\nseed_everything(SEED)","metadata":{"execution":{"iopub.status.busy":"2023-08-28T14:55:09.743714Z","iopub.execute_input":"2023-08-28T14:55:09.744057Z","iopub.status.idle":"2023-08-28T14:55:09.771541Z","shell.execute_reply.started":"2023-08-28T14:55:09.744028Z","shell.execute_reply":"2023-08-28T14:55:09.770317Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 3. Get Input Data","metadata":{}},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\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\nAUTO = tf.data.experimental.AUTOTUNE\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') \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']                                                                                                                                               # 100 - 102","metadata":{"execution":{"iopub.status.busy":"2023-08-28T14:55:09.772890Z","iopub.execute_input":"2023-08-28T14:55:09.773206Z","iopub.status.idle":"2023-08-28T14:55:09.836541Z","shell.execute_reply.started":"2023-08-28T14:55:09.773176Z","shell.execute_reply":"2023-08-28T14:55:09.835367Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds_train = get_training_dataset(TRAINING_FILENAMES)\nds_valid = get_validation_dataset(VALIDATION_FILENAMES)\nds_test = get_test_dataset(TEST_FILENAMES)\n\nNUM_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))","metadata":{"execution":{"iopub.status.busy":"2023-08-28T14:55:09.837954Z","iopub.execute_input":"2023-08-28T14:55:09.838274Z","iopub.status.idle":"2023-08-28T14:55:10.361552Z","shell.execute_reply.started":"2023-08-28T14:55:09.838244Z","shell.execute_reply":"2023-08-28T14:55:10.360080Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Train Model","metadata":{}},{"cell_type":"code","source":"# Learning Rate Schedule for Fine Tuning #\ndef exponential_lr(epoch,\n                   start_lr = 0.00001, min_lr = 0.00001, max_lr = MAX_LR,\n                   rampup_epochs = 5, sustain_epochs = 0,\n                   exp_decay = 0.8):\n\n    def lr(epoch, start_lr, min_lr, max_lr, rampup_epochs, sustain_epochs, exp_decay):\n        # linear increase from start to rampup_epochs\n        if epoch < rampup_epochs:\n            lr = ((max_lr - start_lr) /\n                  rampup_epochs * epoch + start_lr)\n        # constant max_lr during sustain_epochs\n        elif epoch < rampup_epochs + sustain_epochs:\n            lr = max_lr\n        # exponential decay towards min_lr\n        else:\n            lr = ((max_lr - min_lr) *\n                  exp_decay**(epoch - rampup_epochs - sustain_epochs) +\n                  min_lr)\n        return lr\n    return lr(epoch,\n              start_lr,\n              min_lr,\n              max_lr,\n              rampup_epochs,\n              sustain_epochs,\n              exp_decay)\n\nlr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr, verbose=True)","metadata":{"execution":{"iopub.status.busy":"2023-08-28T14:55:10.363053Z","iopub.execute_input":"2023-08-28T14:55:10.363436Z","iopub.status.idle":"2023-08-28T14:55:10.373100Z","shell.execute_reply.started":"2023-08-28T14:55:10.363399Z","shell.execute_reply":"2023-08-28T14:55:10.371856Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_fit_model(net, used_model, seed, weights):\n\n    with strategy.scope():\n        base_model = getattr(net, used_model)(\n            weights = weights,  \n            include_top=False,\n            input_shape=(*IMAGE_SIZE, 3)\n        )\n        base_model.trainable = train_base\n\n        model = tf.keras.Sequential([\n            base_model,\n            layers.GlobalAveragePooling2D(),\n            layers.Flatten(),\n            tf.keras.layers.BatchNormalization(),\n            tf.keras.layers.Dropout(rate=0.3),\n\n    #         tf.keras.layers.Dense(32, activation='softmax'),\n    #         tf.keras.layers.BatchNormalization(),\n    #         tf.keras.layers.Dropout(rate=0.3),\n            tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n        ])\n\n    model.compile(\n        optimizer='nadam',\n        loss='sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy'],\n    )\n\n    os.makedirs('checkpoints', exist_ok=True)\n\n    checkpoint_callback = ModelCheckpoint(\n        f'checkpoints/{used_model}_best.h5',\n        save_weights_only=True,\n        monitor='val_sparse_categorical_accuracy',\n        mode='max',\n        save_best_only=True,\n        verbose=1\n    )\n\n    early_stopping = EarlyStopping(\n        min_delta=0.001,  # minimium amount of change to count as an improvement\n        patience=3,  # how many epochs to wait before stopping\n        restore_best_weights=True\n    )\n\n    model.summary()\n    \n    history = model.fit(\n        ds_train,\n        validation_data=ds_valid,\n        epochs=EPOCHS,\n        steps_per_epoch=NUM_TRAINING_IMAGES // BATCH_SIZE,\n        callbacks=[early_stopping, checkpoint_callback, lr_callback]\n    )\n\n    model.load_weights(f'checkpoints/{used_model}_best.h5')\n    \n    return model, history","metadata":{"execution":{"iopub.status.busy":"2023-08-28T14:57:21.262544Z","iopub.execute_input":"2023-08-28T14:57:21.262968Z","iopub.status.idle":"2023-08-28T14:57:21.275307Z","shell.execute_reply.started":"2023-08-28T14:57:21.262933Z","shell.execute_reply":"2023-08-28T14:57:21.274383Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model, history = get_fit_model(net_type, model_type, SEED, model_weights)","metadata":{"execution":{"iopub.status.busy":"2023-08-28T14:57:23.506637Z","iopub.execute_input":"2023-08-28T14:57:23.507568Z","iopub.status.idle":"2023-08-28T15:28:30.200264Z","shell.execute_reply.started":"2023-08-28T14:57:23.507529Z","shell.execute_reply":"2023-08-28T15:28:30.199003Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def display_confusion_matrix(cmat, score, precision, recall):\n    plt.figure(figsize=(15,15))\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\ndef display_training_curves(training, validation, title, subplot):\n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    #ax.set_ylim(0.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.'])\n\ndisplay_training_curves(\n    history.history['loss'],\n    history.history['val_loss'],\n    'loss',\n    211,\n)\ndisplay_training_curves(\n    history.history['sparse_categorical_accuracy'],\n    history.history['val_sparse_categorical_accuracy'],\n    'accuracy',\n    212,\n)","metadata":{"execution":{"iopub.status.busy":"2023-08-28T15:28:30.203065Z","iopub.execute_input":"2023-08-28T15:28:30.203399Z","iopub.status.idle":"2023-08-28T15:28:31.004678Z","shell.execute_reply.started":"2023-08-28T15:28:30.203367Z","shell.execute_reply":"2023-08-28T15:28:31.003565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Results Validation","metadata":{}},{"cell_type":"code","source":"cmdataset = get_validation_dataset(VALIDATION_FILENAMES, ordered=True)\nimages_ds = cmdataset.map(lambda image, label: image)\nlabels_ds = cmdataset.map(lambda image, label: label).unbatch()\n\ncm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy()\ncm_probabilities = model.predict(images_ds)\ncm_predictions = np.argmax(cm_probabilities, axis=-1)\n\nlabels = range(len(CLASSES))\ncmat = confusion_matrix(\n    cm_correct_labels,\n    cm_predictions,\n    labels=labels,\n)\ncmat = (cmat.T / cmat.sum(axis=1)).T # normalize\n\nscore = f1_score(cm_correct_labels, cm_predictions,labels=labels, average='macro')\nprecision = precision_score(cm_correct_labels, cm_predictions, labels=labels, average='macro')\nrecall = recall_score(cm_correct_labels, cm_predictions, labels=labels, average='macro')\n\ndisplay_confusion_matrix(cmat, score, precision, recall)","metadata":{"execution":{"iopub.status.busy":"2023-08-28T15:28:31.005838Z","iopub.execute_input":"2023-08-28T15:28:31.006139Z","iopub.status.idle":"2023-08-28T15:29:16.771751Z","shell.execute_reply.started":"2023-08-28T15:28:31.006111Z","shell.execute_reply":"2023-08-28T15:29:16.770483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Make Submission","metadata":{}},{"cell_type":"code","source":"test_ds = get_test_dataset(TEST_FILENAMES, ordered=True)\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)\n\nprint('Generating submission.csv file...')\n\n# Get image ids from test set and convert to unicode\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\n# Write the submission file\nnp.savetxt(\n    'submission.csv',\n    np.rec.fromarrays([test_ids, predictions]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)\n\n# Look at the first few predictions\n!head submission.csv","metadata":{"execution":{"iopub.status.busy":"2023-08-28T15:29:16.773829Z","iopub.execute_input":"2023-08-28T15:29:16.774165Z","iopub.status.idle":"2023-08-28T15:30:14.600535Z","shell.execute_reply.started":"2023-08-28T15:29:16.774135Z","shell.execute_reply":"2023-08-28T15:30:14.598852Z"},"trusted":true},"execution_count":null,"outputs":[]}]}