{"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":"# A Simple TF 2.2 notebook\n\nThis is intended as a simple, short introduction to the operations competitors will need to perform with TPUs.","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom kaggle_datasets import KaggleDatasets\nimport numpy as np\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.\nGCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2022-01-09T21:12:33.805428Z","iopub.execute_input":"2022-01-09T21:12:33.805732Z","iopub.status.idle":"2022-01-09T21:12:38.853547Z","shell.execute_reply.started":"2022-01-09T21:12:33.805654Z","shell.execute_reply":"2022-01-09T21:12:38.852781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Set some parameters","metadata":{}},{"cell_type":"code","source":"IMAGE_SIZE = [192, 192] # at this size, a GPU will run out of memory. Use the TPU\nEPOCHS = 1\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nNUM_TRAINING_IMAGES = 12753\nNUM_TEST_IMAGES = 7382\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE","metadata":{"execution":{"iopub.status.busy":"2022-01-09T21:12:38.856045Z","iopub.execute_input":"2022-01-09T21:12:38.85648Z","iopub.status.idle":"2022-01-09T21:12:38.862398Z","shell.execute_reply.started":"2022-01-09T21:12:38.85644Z","shell.execute_reply":"2022-01-09T21:12:38.861362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load my data\n\nThis data is loaded from Kaggle and automatically sharded to maximize parallelization.","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 and\n    # disregarding 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) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef get_training_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/train/*.tfrec'), labeled=True)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset\n\ndef get_validation_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/val/*.tfrec'), labeled=True, ordered=False)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/test/*.tfrec'), labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset\n\ntraining_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()","metadata":{"execution":{"iopub.status.busy":"2022-01-09T21:12:38.86433Z","iopub.execute_input":"2022-01-09T21:12:38.86506Z","iopub.status.idle":"2022-01-09T21:12:41.300991Z","shell.execute_reply.started":"2022-01-09T21:12:38.865004Z","shell.execute_reply":"2022-01-09T21:12:41.300196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_dataset = training_dataset.concatenate(validation_dataset)","metadata":{"execution":{"iopub.status.busy":"2022-01-09T21:12:41.303123Z","iopub.execute_input":"2022-01-09T21:12:41.303467Z","iopub.status.idle":"2022-01-09T21:12:41.308667Z","shell.execute_reply.started":"2022-01-09T21:12:41.303428Z","shell.execute_reply":"2022-01-09T21:12:41.307864Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build a model on TPU (or GPU, or CPU...) with Tensorflow 2.1!","metadata":{}},{"cell_type":"code","source":"with strategy.scope():     \n    model = tf.keras.Sequential([\n        tf.keras.layers.Conv2D(4, (3, 3), activation='relu', input_shape=(192, 192, 3)),\n        tf.keras.layers.MaxPooling2D((2, 2), strides=2),\n        tf.keras.layers.Conv2D(4, (3, 3), activation='relu'),\n        tf.keras.layers.MaxPooling2D((2, 2), strides=2),\n        tf.keras.layers.Flatten(),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n        \nmodel.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nhistorical = model.fit(training_dataset, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS)\n","metadata":{"execution":{"iopub.status.busy":"2022-01-09T21:12:41.309986Z","iopub.execute_input":"2022-01-09T21:12:41.31053Z","iopub.status.idle":"2022-01-09T21:13:09.33994Z","shell.execute_reply.started":"2022-01-09T21:12:41.310479Z","shell.execute_reply":"2022-01-09T21:13:09.339131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():    \n    pretrained_model = tf.keras.applications.xception.Xception(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model.trainable = False # tramsfer learning\n    \n    xception_model = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n        \nxception_model.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nhistorical_xception = xception_model.fit(training_dataset, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS)","metadata":{"execution":{"iopub.status.busy":"2022-01-09T21:13:09.344246Z","iopub.execute_input":"2022-01-09T21:13:09.346113Z","iopub.status.idle":"2022-01-09T21:13:55.387229Z","shell.execute_reply.started":"2022-01-09T21:13:09.34606Z","shell.execute_reply":"2022-01-09T21:13:55.386573Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():    \n    pretrained_model = tf.keras.applications.inception_v3.InceptionV3(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model.trainable = False # tramsfer learning\n    \n    inception_model = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n        \ninception_model.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nhistorical_inception = inception_model.fit(training_dataset, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS)\n","metadata":{"execution":{"iopub.status.busy":"2022-01-09T21:13:55.388629Z","iopub.execute_input":"2022-01-09T21:13:55.388891Z","iopub.status.idle":"2022-01-09T21:14:38.16415Z","shell.execute_reply.started":"2022-01-09T21:13:55.388856Z","shell.execute_reply":"2022-01-09T21:14:38.163474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"models = [model, xception_model, inception_model]\nmodel_input = tf.keras.Input(shape=(192, 192, 3))\nmodel_outputs = [model(model_input) for model in models]\nensemble_output = tf.keras.layers.Average()(model_outputs)\nensemble_model = tf.keras.Model(inputs=model_input, outputs=ensemble_output)\nensemble_model.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nensemble_historical = ensemble_model.fit(training_dataset, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS)","metadata":{"execution":{"iopub.status.busy":"2022-01-09T21:14:38.165648Z","iopub.execute_input":"2022-01-09T21:14:38.16593Z","iopub.status.idle":"2022-01-09T21:15:44.97966Z","shell.execute_reply.started":"2022-01-09T21:14:38.165895Z","shell.execute_reply":"2022-01-09T21:15:44.978963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Compute your predictions on the test set!\n\nThis will create a file that can be submitted to the competition.","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import f1_score, precision_score\ndef get_accuracy(model_name, model, validation_dataset):\n    probabilities = model.predict(x = validation_dataset)\n    predictions = np.argmax(probabilities, axis=-1)\n    true_classes = np.concatenate([true_classes for x, true_classes in validation_dataset], axis=0)\n    f_score = f1_score(\n        true_classes,\n        predictions,\n        labels=range(104),\n        average='macro',\n    )\n    print(model_name + \" macro f-score: \" + str(f_score))\n    score = (true_classes == predictions).sum() / len(true_classes)\n    print(model_name + \" accuracy: \" + str(score))\n    \nget_accuracy(\"Our Model\",model, validation_dataset)\nget_accuracy(\"Inception Model\",inception_model, validation_dataset)\nget_accuracy(\"Xception Model\",xception_model, validation_dataset)\nget_accuracy(\"Ensemble Model\",ensemble_model, validation_dataset)","metadata":{"execution":{"iopub.status.busy":"2022-01-09T21:15:44.980943Z","iopub.execute_input":"2022-01-09T21:15:44.981682Z","iopub.status.idle":"2022-01-09T21:16:18.995432Z","shell.execute_reply.started":"2022-01-09T21:15:44.981644Z","shell.execute_reply":"2022-01-09T21:16:18.994656Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import f1_score, precision_score, confusion_matrix, recall_score\nimport matplotlib.pyplot as plt\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']    \n\n\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()\n\n\ndef get_confusion_matrix(model_name, model, validation_dataset):\n    probabilities = model.predict(x = validation_dataset)\n    predictions = np.argmax(probabilities, axis=-1)\n    true_classes = np.concatenate([true_classes for x, true_classes in validation_dataset], axis=0)\n    f_score = f1_score(\n        true_classes,\n        predictions,\n        labels=range(104),\n        average='macro',\n    )\n    print(model_name + \" macro f-score: \" + str(f_score))\n    score = (true_classes == predictions).sum() / len(true_classes)\n    print(model_name + \" accuracy: \" + str(score))\n    cmat = confusion_matrix(\n        true_classes,\n        predictions,\n        labels=range(104),\n        normalize='true',\n    )\n    precision = precision_score(\n        true_classes,\n        predictions,\n        labels=range(104),\n        average='macro',\n    )\n    recall = recall_score(\n            true_classes,\n            predictions,\n            labels=range(104),\n            average='macro',\n    )\n    \n    display_confusion_matrix(cmat,f_score,precision,recall)\n    \n\n\nget_confusion_matrix(\"Our Model\",model, validation_dataset)\nget_confusion_matrix(\"Inception Model\",inception_model, validation_dataset)\nget_confusion_matrix(\"Xception Model\",xception_model, validation_dataset)\nget_confusion_matrix(\"Ensemble Model\",ensemble_model, validation_dataset)","metadata":{"execution":{"iopub.status.busy":"2022-01-09T21:30:45.291599Z","iopub.execute_input":"2022-01-09T21:30:45.291928Z","iopub.status.idle":"2022-01-09T21:31:27.123226Z","shell.execute_reply.started":"2022-01-09T21:30:45.291891Z","shell.execute_reply":"2022-01-09T21:31:27.119077Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(CLASSES)","metadata":{"execution":{"iopub.status.busy":"2022-01-09T21:26:39.772429Z","iopub.execute_input":"2022-01-09T21:26:39.772689Z","iopub.status.idle":"2022-01-09T21:26:39.779302Z","shell.execute_reply.started":"2022-01-09T21:26:39.77266Z","shell.execute_reply":"2022-01-09T21:26:39.7784Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}