{"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-11T01:49:27.367198Z","iopub.execute_input":"2022-01-11T01:49:27.367726Z","iopub.status.idle":"2022-01-11T01:49:38.936390Z","shell.execute_reply.started":"2022-01-11T01:49:27.367617Z","shell.execute_reply":"2022-01-11T01:49:38.935617Z"},"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 = 15\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nNUM_TRAINING_IMAGES = int(0.9 * 16465)\nNUM_TEST_IMAGES = int(0.1 * 16465)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint(NUM_TRAINING_IMAGES, NUM_TEST_IMAGES)","metadata":{"execution":{"iopub.status.busy":"2022-01-11T01:49:38.938524Z","iopub.execute_input":"2022-01-11T01:49:38.939102Z","iopub.status.idle":"2022-01-11T01:49:38.945247Z","shell.execute_reply.started":"2022-01-11T01:49:38.939052Z","shell.execute_reply":"2022-01-11T01:49:38.944501Z"},"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 split_dataset(dataset: tf.data.Dataset, validation_data_fraction: float):\n    \"\"\"\n    Splits a dataset of type tf.data.Dataset into a training and validation dataset using given ratio. Fractions are\n    rounded up to two decimal places.\n    @param dataset: the input dataset to split.\n    @param validation_data_fraction: the fraction of the validation data as a float between 0 and 1.\n    @return: a tuple of two tf.data.Datasets as (training, validation)\n    \"\"\"\n\n    validation_data_percent = round(validation_data_fraction * 100)\n    if not (0 <= validation_data_percent <= 100):\n        raise ValueError(\"validation data fraction must be ∈ [0,1]\")\n\n    dataset = dataset.enumerate()\n    train_dataset = dataset.filter(lambda f, data: f % 100 > validation_data_percent)\n    validation_dataset = dataset.filter(lambda f, data: f % 100 <= validation_data_percent)\n\n    # remove enumeration\n    train_dataset = train_dataset.map(lambda f, data: data)\n    validation_dataset = validation_dataset.map(lambda f, data: data)\n\n    return train_dataset, validation_dataset\n\ndef 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    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    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-11T01:49:38.946853Z","iopub.execute_input":"2022-01-11T01:49:38.947190Z","iopub.status.idle":"2022-01-11T01:49:39.258875Z","shell.execute_reply.started":"2022-01-11T01:49:38.947134Z","shell.execute_reply":"2022-01-11T01:49:39.258038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_dataset = training_dataset.concatenate(validation_dataset)\nfull_dataset = full_dataset.shuffle(2048)\ntrain_dataset, val_dataset = split_dataset(full_dataset, 0.1)\ntrain_dataset = train_dataset.repeat() # the training dataset must repeat for several epochs\ntrain_dataset = train_dataset.shuffle(2048)\ntrain_dataset = train_dataset.batch(BATCH_SIZE)\nval_dataset = val_dataset.batch(BATCH_SIZE)\nval_dataset = val_dataset.cache()","metadata":{"execution":{"iopub.status.busy":"2022-01-11T01:49:39.261203Z","iopub.execute_input":"2022-01-11T01:49:39.261588Z","iopub.status.idle":"2022-01-11T01:49:39.356826Z","shell.execute_reply.started":"2022-01-11T01:49:39.261549Z","shell.execute_reply":"2022-01-11T01:49:39.356069Z"},"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.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(train_dataset, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS,\n          validation_data = val_dataset)\n","metadata":{"execution":{"iopub.status.busy":"2022-01-11T01:49:39.357953Z","iopub.execute_input":"2022-01-11T01:49:39.358178Z","iopub.status.idle":"2022-01-11T01:54:05.046969Z","shell.execute_reply.started":"2022-01-11T01:49:39.358153Z","shell.execute_reply":"2022-01-11T01:54:05.046027Z"},"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 # transfer 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(train_dataset, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS,\n          validation_data = val_dataset)","metadata":{"execution":{"iopub.status.busy":"2022-01-11T01:54:05.048244Z","iopub.execute_input":"2022-01-11T01:54:05.048472Z","iopub.status.idle":"2022-01-11T01:58:35.088700Z","shell.execute_reply.started":"2022-01-11T01:54:05.048444Z","shell.execute_reply":"2022-01-11T01:58:35.087936Z"},"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 # transfer 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(train_dataset, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS,\n          validation_data = val_dataset)\n","metadata":{"execution":{"iopub.status.busy":"2022-01-11T01:58:35.090082Z","iopub.execute_input":"2022-01-11T01:58:35.090783Z","iopub.status.idle":"2022-01-11T02:03:23.808453Z","shell.execute_reply.started":"2022-01-11T01:58:35.090746Z","shell.execute_reply":"2022-01-11T02:03:23.807738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():   \n    models = [model, xception_model, inception_model]\n    model_input = tf.keras.Input(shape=(192, 192, 3))\n    model_outputs = [model(model_input) for model in models]\n    ensemble_output = tf.keras.layers.Average()(model_outputs)\n    ensemble_model = tf.keras.Model(inputs=model_input, outputs=ensemble_output)\n\nensemble_model.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nensemble_historical = ensemble_model.fit(train_dataset, steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS,\n          validation_data = val_dataset)","metadata":{"execution":{"iopub.status.busy":"2022-01-11T02:03:23.809462Z","iopub.execute_input":"2022-01-11T02:03:23.809659Z","iopub.status.idle":"2022-01-11T02:08:24.379384Z","shell.execute_reply.started":"2022-01-11T02:03:23.809636Z","shell.execute_reply":"2022-01-11T02:08:24.378686Z"},"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, val_dataset)\nget_accuracy(\"Inception Model\",inception_model, val_dataset)\nget_accuracy(\"Xception Model\",xception_model, val_dataset)\nget_accuracy(\"Ensemble Model\",ensemble_model, val_dataset)","metadata":{"execution":{"iopub.status.busy":"2022-01-11T02:08:24.380633Z","iopub.execute_input":"2022-01-11T02:08:24.380977Z","iopub.status.idle":"2022-01-11T02:09:21.335454Z","shell.execute_reply.started":"2022-01-11T02:08:24.380942Z","shell.execute_reply":"2022-01-11T02:09:21.334723Z"},"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, val_dataset)\nget_confusion_matrix(\"Inception Model\",inception_model, val_dataset)\nget_confusion_matrix(\"Xception Model\",xception_model, val_dataset)\nget_confusion_matrix(\"Ensemble Model\",ensemble_model, val_dataset)","metadata":{"execution":{"iopub.status.busy":"2022-01-11T02:09:21.337941Z","iopub.execute_input":"2022-01-11T02:09:21.338219Z","iopub.status.idle":"2022-01-11T02:09:43.310556Z","shell.execute_reply.started":"2022-01-11T02:09:21.338185Z","shell.execute_reply":"2022-01-11T02:09:43.309862Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"NUM_TEST_IMAGES = 7382\ntest_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = ensemble_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, idnum: idnum).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='')","metadata":{"execution":{"iopub.status.busy":"2022-01-11T02:09:43.318123Z","iopub.execute_input":"2022-01-11T02:09:43.318410Z","iopub.status.idle":"2022-01-11T02:10:26.637050Z","shell.execute_reply.started":"2022-01-11T02:09:43.318388Z","shell.execute_reply":"2022-01-11T02:10:26.636277Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}