{"cells":[{"metadata":{},"cell_type":"markdown","source":"> Credit: This notebook is originaly based on an [official starter](https://www.kaggle.com/mgornergoogle/getting-started-with-100-flowers-on-tpu) by @mgornergoogle"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import re\n\nimport numpy as np\n\nimport tensorflow as tf\nfrom tensorflow.keras import layers\n\nimport matplotlib.pyplot as plt\nfrom kaggle_datasets import KaggleDatasets  # required for TPU dataloading\n\n\nAUTO = tf.data.experimental.AUTOTUNE\ntf.__version__","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy\ntry:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU ', tpu.master())\n\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nexcept ValueError:\n    # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMAGE_SIZE = [192, 192]\nBATCH_SIZE = 32 * strategy.num_replicas_in_sync\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\nN_CLASSES = len(CLASSES)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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 count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec 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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Load the data"},{"metadata":{"trusted":true},"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path()\n\n# python glob won't wors as you're using GCP buckets (required for TPU)\ntrain_fnames = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/train/*.tfrec')\nvalid_fnames = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/val/*.tfrec')\ntest_fnames = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/test/*.tfrec')\n\nn_train = count_data_items(train_fnames)\n\ntrain_ds = tf.data.TFRecordDataset(filenames=train_fnames)\\\n    .map(read_labeled_tfrecord, num_parallel_calls=AUTO)\\\n    .repeat()\\\n    .shuffle(buffer_size=2048)\n\nvalid_ds = tf.data.TFRecordDataset(filenames=valid_fnames)\\\n    .map(read_labeled_tfrecord, num_parallel_calls=AUTO)\\\n    .cache()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"show_n = 3\nplt.figure(figsize=(15, 5))\n\nfor i, (image, label) in enumerate(train_ds.take(show_n)):\n    plt.subplot(1, show_n, i+1)\n    plt.imshow(image.numpy())\n    plt.title(CLASSES[label])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Build a model"},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():  # device specification (TPU/GPU/CPU)\n    body = tf.keras.applications.DenseNet121(weights='imagenet', include_top=False, input_shape=[*IMAGE_SIZE, 3])\n#     body.trainable = False  # either finetune pretrained model or use it as a feature extractor\n\n    model = tf.keras.Sequential([\n        body,\n        layers.GlobalAveragePooling2D(),\n        layers.Dense(N_CLASSES, activation='softmax')\n    ])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Debug forward pass"},{"metadata":{"trusted":true},"cell_type":"code","source":"batch, label = next(iter(train_ds.batch(2)))\n\nout = model(batch)\nout.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(\n    optimizer=tf.keras.optimizers.Adam(lr=1e-3),\n    loss='sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"steps_per_epoch = n_train // BATCH_SIZE + int(n_train % BATCH_SIZE > 0)\n\ntrain_dl = train_ds.batch(BATCH_SIZE).prefetch(AUTO)\nvalid_dl = valid_ds.batch(BATCH_SIZE).prefetch(AUTO)\n\nhistory = model.fit(train_dl,\n    validation_data=valid_dl,\n    steps_per_epoch=steps_per_epoch,\n    epochs=5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(15,7))\nplt.plot(history.history['sparse_categorical_accuracy'], label='train')\nplt.plot(history.history['val_sparse_categorical_accuracy'], label='valid')\nplt.title('Accuracy')\nplt.legend()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"get_image_lambda = lambda image, id_: image  # Autograph asked to create lambda as a standalone statement\nget_id_lambda = lambda image, id_: id_\n\ntest_ds = tf.data.TFRecordDataset(filenames=test_fnames)\\\n    .map(read_unlabeled_tfrecord, num_parallel_calls=AUTO)\\\n    .batch(BATCH_SIZE)\\\n    .prefetch(AUTO)\nn_test = count_data_items(test_fnames)\n\nprint('Computing predictions...')\n\nprobabilities = model.predict(test_ds.map(get_image_lambda))\npredictions = np.argmax(probabilities, axis=-1)\n\nprint('Generating submission.csv file...')\ntest_ids_ds = test_ds.map(get_id_lambda).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(n_test))).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='')\n!head submission.csv","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":1}