{"cells":[{"metadata":{},"cell_type":"markdown","source":"Thanks to this kernel <Getting started with 100+ flowers on TPU>https://www.kaggle.com/mgornergoogle/getting-started-with-100-flowers-on-tpu\nThe method reading TFRecords is learned from it"},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -q efficientnet","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"b50369e0-08ab-4ac5-ae03-316b5019c4da","_cell_guid":"1e004260-4b31-4710-95ca-f9eb7add9d37","trusted":true},"cell_type":"code","source":"import math, re, os\nimport tensorflow as tf\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nimport efficientnet.tfkeras as efn\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\nfrom tensorflow.keras.applications import InceptionResNetV2\nfrom tensorflow.keras.applications import ResNet152V2\nfrom tensorflow.keras.applications import DenseNet201\nfrom tensorflow.keras.applications import VGG19\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nprint(\"Tensorflow version \" + tf.__version__)\nAUTO = tf.data.experimental.AUTOTUNE","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"92c8f2d8-de91-45ad-9bfc-2eecba799f8d","_cell_guid":"1c7a442f-60f8-42b9-9301-5cc68c122a9f","trusted":true},"cell_type":"markdown","source":"# TPU or GPU detection"},{"metadata":{"_uuid":"990e29e8-e585-4ccf-9290-fa0a7644da9f","_cell_guid":"f205cb96-4491-4007-8639-a015723ad3aa","trusted":true},"cell_type":"code","source":"#使用TPU进行训练\n# Detect hardware, return appropriate distribution strategy\n\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":{"_uuid":"a327478e-ef04-4a32-8b71-e6ace5bf4fad","_cell_guid":"2624d7da-6333-4cee-b27a-552b089fae28","trusted":true},"cell_type":"markdown","source":"# Competition data access\nTPUs read data directly from Google Cloud Storage (GCS).\nTPU直接从谷歌云读取数据"},{"metadata":{"_uuid":"53372dc3-2e1e-4116-8f1c-b3a6505f52c0","_cell_guid":"fc285599-d5b5-4ccc-a1b4-e2eb72ffdbd9","trusted":true},"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"\n#GCS_DS_PATH = 'H:/software'","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"3a61a387-e258-4e7d-ae1f-b6f51f63ac19","_cell_guid":"54b2326b-5809-4b73-a94f-51eb3aa515db","trusted":true},"cell_type":"markdown","source":"# Dateset\nRead dataset from TFRecord.从TFRecord读入数据，TRecord是google的一种数据结构，一般用于训练数据比较大的数据集，主要使用tf.io.parse_single_example进行读取"},{"metadata":{"_uuid":"3d43d7ae-39da-42e2-9a3f-abdeccc7c2cf","_cell_guid":"f3acf114-43d8-4297-911c-97acaf48fab8","trusted":true},"cell_type":"code","source":"#根据需求选择数据集，本例进行TPU进行训练，使用512*512\nIMAGE_SIZE = [512, 512]\nEPOCHS = 20\n#BATCH_SIZE = 16\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nGCS_PATH_SELECT = {\n    192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',\n    224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',\n    331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',\n    512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'\n}\n\nGCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]\n\nTRAINING_FIFENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')\nVALIDATION_FIFENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\nTEST_FIFENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')\n\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#labeled tfrecord 是train、validation 数据，用tf.io.parse_single_example读入TFRecord数据\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), \n        \"class\": tf.io.FixedLenFeature([], tf.int64),  \n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = example['image']\n    image = tf.image.decode_jpeg(image, 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])\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    LABELED_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    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = example['image']\n    image = tf.image.decode_jpeg(image, 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])\n    label = example['id']\n    return image, label # returns a dataset of (image, label) pairs\n\ndef 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\n\nignore_order = tf.data.Options()\n\ndataset_train = tf.data.TFRecordDataset(TRAINING_FIFENAMES)\ndataset_train = dataset_train.with_options(ignore_order)\ndataset_train = dataset_train.map(read_labeled_tfrecord)   #map居然能通过，而直接使用函数缺不可以？\ndataset_train = dataset_train.map(data_augment, num_parallel_calls=AUTO)\ndataset_train = dataset_train.repeat() #\ndataset_train = dataset_train.shuffle(2048)\ndataset_train = dataset_train.batch(BATCH_SIZE)\ndataset_train = dataset_train.prefetch(AUTO)\n\ndataset_val = tf.data.TFRecordDataset(VALIDATION_FIFENAMES)\ndataset_val = dataset_val.with_options(ignore_order)\ndataset_val = dataset_val.map(read_labeled_tfrecord)   #map居然能通过，而直接使用函数缺不可以？\ndataset_val = dataset_val.map(data_augment, num_parallel_calls=AUTO)\ndataset_val = dataset_val.batch(BATCH_SIZE)\ndataset_val = dataset_val.cache()\ndataset_val = dataset_val.prefetch(AUTO)\n\ndataset_test = tf.data.TFRecordDataset(TEST_FIFENAMES)\ndataset_test = dataset_test.with_options(ignore_order)\ndataset_test = dataset_test.map(read_unlabeled_tfrecord)   #map居然能通过，而直接使用函数缺不可以？\ndataset_test = dataset_test.map(data_augment, num_parallel_calls=AUTO)\ndataset_test = dataset_test.batch(BATCH_SIZE)\ndataset_test = dataset_test.prefetch(AUTO)\n\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FIFENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FIFENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FIFENAMES)\n\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# LR schedule"},{"metadata":{"trusted":true},"cell_type":"code","source":"def lr_schedule(epoch):\n    # Learning Rate Schedule\n\n    lr =1e-4\n    total_epochs =epoch\n\n    check_1 = int(total_epochs * 0.9)\n    check_2 = int(total_epochs * 0.8)\n    check_3 = int(total_epochs * 0.6)\n    check_4 = int(total_epochs * 0.4)\n\n    if epoch > check_1:\n        lr *= 1e-1\n    elif epoch > check_2:\n        lr *= 1e-2\n    elif epoch > check_3:\n        lr *= 1e-3\n    elif epoch > check_4:\n        lr *= 1e-4\n\n    return lr\n\n\n\nlr_scheduler =tf.keras.callbacks.LearningRateScheduler(lr_schedule)\n\n#lr_scheduler = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.2,patience=5, min_lr=0.001)\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"66d71c6d-f3f7-48af-859f-91f845ab3b26","_cell_guid":"f0d344b1-85e2-4466-a7fc-d6d5ac85ff9f","trusted":true},"cell_type":"markdown","source":"# Model\nIt choose the VGG16 to train."},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n#     pretrained_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n#     pretrained_model.trainable = True # tramsfer learning\n    \n    enet = efn.EfficientNetB7(\n        input_shape=[*IMAGE_SIZE, 3],\n        weights='imagenet',\n        include_top=False)\n    Incep = InceptionResNetV2(\n        input_shape=[*IMAGE_SIZE, 3],\n        weights='imagenet',\n        include_top=False)   \n    res = ResNet152V2(\n        input_shape=[*IMAGE_SIZE, 3],\n        weights='imagenet',\n        include_top=False)\n    den = DenseNet201(\n        input_shape=(512, 512, 3),\n        weights='imagenet',\n        include_top=False)\n    \n    \n    model_1 = tf.keras.Sequential([\n        enet,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n    \n    model_2 = tf.keras.Sequential([\n        Incep,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n    model_3 = tf.keras.Sequential([\n        res,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n    model_4 = tf.keras.Sequential([\n        den,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n  \n          \nmodel_1.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\nmodel_1.summary()\n\n          \nmodel_2.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\nmodel_2.summary()\n\n          \nmodel_3.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\nmodel_3.summary()\n\n          \nmodel_4.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\nmodel_4.summary()\n\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"5bc619b0-105c-43d3-aede-677bd2d53f05","_cell_guid":"40f1ab2f-2563-4540-b142-e165325aa192","trusted":true},"cell_type":"markdown","source":"# Training 1"},{"metadata":{"trusted":true},"cell_type":"code","source":"history_1 = model_1.fit(dataset_train, steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks=[lr_scheduler],validation_data=dataset_val)\nhistory_2 = model_2.fit(dataset_train, steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks=[lr_scheduler],validation_data=dataset_val)\nhistory_3 = model_3.fit(dataset_train, steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks=[lr_scheduler],validation_data=dataset_val)\nhistory_4 = model_4.fit(dataset_train, steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks=[lr_scheduler],validation_data=dataset_val)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Display traing curves 1"},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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(history_1.history['loss'], history_1.history['val_loss'], 'loss', 211)\ndisplay_training_curves(history_1.history['sparse_categorical_accuracy'], history_1.history['val_sparse_categorical_accuracy'], 'accuracy', 212)\n\ndisplay_training_curves(history_2.history['loss'], history_2.history['val_loss'], 'loss', 211)\ndisplay_training_curves(history_2.history['sparse_categorical_accuracy'], history_2.history['val_sparse_categorical_accuracy'], 'accuracy', 212)\n\ndisplay_training_curves(history_3.history['loss'], history_3.history['val_loss'], 'loss', 211)\ndisplay_training_curves(history_3.history['sparse_categorical_accuracy'], history_3.history['val_sparse_categorical_accuracy'], 'accuracy', 212)\n\ndisplay_training_curves(history_4.history['loss'], history_4.history['val_loss'], 'loss', 211)\ndisplay_training_curves(history_4.history['sparse_categorical_accuracy'], history_4.history['val_sparse_categorical_accuracy'], 'accuracy', 212)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Confusion matrix"},{"metadata":{"trusted":true},"cell_type":"code","source":"dataset_val = tf.data.TFRecordDataset(VALIDATION_FIFENAMES)\n# dataset_val = dataset_val.with_options(ignore_order)\ndataset_val = dataset_val.map(read_labeled_tfrecord)   #map居然能通过，而直接使用函数缺不可以？\ndataset_val = dataset_val.map(data_augment, num_parallel_calls=AUTO)\ndataset_val = dataset_val.batch(BATCH_SIZE)\ndataset_val = dataset_val.cache()\ndataset_val = dataset_val.prefetch(AUTO)\n\nimages_ds = dataset_val.map(lambda image, label: image)\nlabels_ds = dataset_val.map(lambda image, label: label).unbatch()\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)\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":"cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))\nscore = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\nprecision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\nrecall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\n#cmat = (cmat.T / cmat.sum(axis=1)).T # normalized\ndef 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()\ndisplay_confusion_matrix(cmat, score, precision, recall)\nprint('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# dataset_test = tf.data.TFRecordDataset(TEST_FIFENAMES)\n# # dataset_test = dataset_test.with_options(ignore_order)\n# dataset_test = dataset_test.map(read_unlabeled_tfrecord)   #map居然能通过，而直接使用函数缺不可以？\n# dataset_test = dataset_test.map(data_augment, num_parallel_calls=AUTO)\n# dataset_test = dataset_test.batch(BATCH_SIZE)\n# dataset_test = dataset_test.prefetch(AUTO)\n\n# # test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\n\n# print('Computing predictions...')\n# test_images_ds = dataset_test.map(lambda image, idnum: image)\n# probabilities = model.predict(test_images_ds)\n# predictions = np.argmax(probabilities, axis=-1)\n# print(predictions)\n\n# print('Generating submission.csv file...')\n# test_ids_ds = dataset_test.map(lambda image, idnum: idnum).unbatch()\n# test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\n# np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\n# !head submission.csv","execution_count":null,"outputs":[]}],"metadata":{"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"}},"nbformat":4,"nbformat_minor":1}