{"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":"code","source":"! pip install vit-keras","metadata":{"execution":{"iopub.status.busy":"2023-06-06T02:12:03.092580Z","iopub.execute_input":"2023-06-06T02:12:03.092860Z","iopub.status.idle":"2023-06-06T02:12:20.625010Z","shell.execute_reply.started":"2023-06-06T02:12:03.092833Z","shell.execute_reply":"2023-06-06T02:12:20.623910Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import math, re, os\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nfrom vit_keras import vit\n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-06-06T02:12:20.628562Z","iopub.execute_input":"2023-06-06T02:12:20.629212Z","iopub.status.idle":"2023-06-06T02:12:37.264027Z","shell.execute_reply.started":"2023-06-06T02:12:20.629170Z","shell.execute_reply":"2023-06-06T02:12:37.262020Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from kaggle_datasets import KaggleDatasets\n\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\nprint(GCS_DS_PATH) # what do gcs paths look like?","metadata":{"execution":{"iopub.status.busy":"2023-06-06T02:12:37.265415Z","iopub.execute_input":"2023-06-06T02:12:37.266133Z","iopub.status.idle":"2023-06-06T02:12:37.659179Z","shell.execute_reply.started":"2023-06-06T02:12:37.266099Z","shell.execute_reply":"2023-06-06T02:12:37.658229Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE\n\n# Detect hardware, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect() # TPU detection\n    strategy = tf.distribute.TPUStrategy(tpu)\nexcept ValueError:\n    strategy = tf.distribute.MirroredStrategy() # for GPU or multi-GPU machines\n\nprint(\"Number of accelerators: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2023-06-06T02:12:37.663746Z","iopub.execute_input":"2023-06-06T02:12:37.667282Z","iopub.status.idle":"2023-06-06T02:12:43.766211Z","shell.execute_reply.started":"2023-06-06T02:12:37.667245Z","shell.execute_reply":"2023-06-06T02:12:43.763978Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [512, 512]\nBATCH_SIZE = 32\nGCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-512x512'\nAUTO = tf.data.experimental.AUTOTUNE\n\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\n\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, num_parallel_reads=AUTO) # 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, num_parallel_calls=AUTO)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2023-06-06T02:12:43.767922Z","iopub.execute_input":"2023-06-06T02:12:43.768611Z","iopub.status.idle":"2023-06-06T02:12:43.922117Z","shell.execute_reply.started":"2023-06-06T02:12:43.768577Z","shell.execute_reply":"2023-06-06T02:12:43.921087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_test_dataset(ordered=False):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)\n    return dataset\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)","metadata":{"execution":{"iopub.status.busy":"2023-06-06T02:41:10.822108Z","iopub.execute_input":"2023-06-06T02:41:10.822491Z","iopub.status.idle":"2023-06-06T02:41:10.829611Z","shell.execute_reply.started":"2023-06-06T02:41:10.822463Z","shell.execute_reply":"2023-06-06T02:41:10.828372Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds_test = get_test_dataset()","metadata":{"execution":{"iopub.status.busy":"2023-06-06T02:12:43.931538Z","iopub.execute_input":"2023-06-06T02:12:43.931946Z","iopub.status.idle":"2023-06-06T02:12:44.151099Z","shell.execute_reply.started":"2023-06-06T02:12:43.931911Z","shell.execute_reply":"2023-06-06T02:12:44.150065Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)","metadata":{"execution":{"iopub.status.busy":"2023-06-06T02:41:14.729107Z","iopub.execute_input":"2023-06-06T02:41:14.729479Z","iopub.status.idle":"2023-06-06T02:41:14.734062Z","shell.execute_reply.started":"2023-06-06T02:41:14.729449Z","shell.execute_reply":"2023-06-06T02:41:14.733170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    base_model = vit.vit_l16(\n            image_size=IMAGE_SIZE[0],\n            activation='softmax',\n            pretrained=False,\n            include_top=False ,\n            pretrained_top=False,\n        )\n\n    model = tf.keras.Sequential([\n        base_model,\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n\n    model.compile(\n        optimizer='adam',\n        loss = 'categorical_crossentropy',\n        metrics=[tfa.metrics.F1Score(len(CLASSES), average='macro')],\n    )","metadata":{"execution":{"iopub.status.busy":"2023-06-06T02:12:44.152755Z","iopub.execute_input":"2023-06-06T02:12:44.153122Z","iopub.status.idle":"2023-06-06T02:12:54.631374Z","shell.execute_reply.started":"2023-06-06T02:12:44.153088Z","shell.execute_reply":"2023-06-06T02:12:54.630406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.load_weights('/kaggle/input/vit-model/vit_best.h5')","metadata":{"execution":{"iopub.status.busy":"2023-06-06T02:12:54.632956Z","iopub.execute_input":"2023-06-06T02:12:54.633319Z","iopub.status.idle":"2023-06-06T02:13:06.825856Z","shell.execute_reply.started":"2023-06-06T02:12:54.633284Z","shell.execute_reply":"2023-06-06T02:13:06.824878Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Computing predictions...')\ntest_images_ds = ds_test.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)","metadata":{"execution":{"iopub.status.busy":"2023-06-06T02:13:06.829395Z","iopub.execute_input":"2023-06-06T02:13:06.829762Z","iopub.status.idle":"2023-06-06T02:32:16.027753Z","shell.execute_reply.started":"2023-06-06T02:13:06.829728Z","shell.execute_reply":"2023-06-06T02:32:16.026665Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Generating submission.csv file...')\n\n# Get image ids from test set and convert to unicode\ntest_ids_ds = ds_test.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-06-06T02:41:24.964134Z","iopub.execute_input":"2023-06-06T02:41:24.964488Z","iopub.status.idle":"2023-06-06T02:41:47.970794Z","shell.execute_reply.started":"2023-06-06T02:41:24.964459Z","shell.execute_reply":"2023-06-06T02:41:47.969701Z"},"trusted":true},"execution_count":null,"outputs":[]}]}