{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"from kaggle_datasets import KaggleDatasets\nimport numpy as np\nimport tensorflow as tf\nimport re\nfrom tensorflow import keras\nimport matplotlib.pyplot as plt\n\nprint(f'Tensorflow version: {tf.__version__}')\n\nimport math, re, os, random \nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix,accuracy_score","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# TPU detection\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n    \n# TPUStrategy for distributing training\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: # default strategy that 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":"AUTO = tf.data.experimental.AUTOTUNE\n\nIMAGE_SIZE = [512, 512]\nEPOCHS = 8\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nSEED = 752\nSKIP_VALIDATION = False\nTTA_NUM = 5\n\nrandom.seed(SEED)\nnp.random.seed(SEED)\ntf.random.set_seed(SEED)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path()\nprint(GCS_DS_PATH)\n\nGCS_PATH_SELECT = { # Image Sizes\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]]\nprint(GCS_PATH)\n\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec') # predictions on this dataset should be submitted for the competition","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# 0 to 103\nCLASSES = [\n    \"pink primrose\",\n    \"hard-leaved pocket orchid\",\n    \"canterbury bells\",\n    \"sweet pea\",\n    \"wild geranium\",\n    \"tiger lily\",\n    \"moon orchid\",\n    \"bird of paradise\",\n    \"monkshood\",\n    \"globe thistle\",\n    \"snapdragon\",\n    \"colt's foot\",\n    \"king protea\",\n    \"spear thistle\",\n    \"yellow iris\",\n    \"globe-flower\",\n    \"purple coneflower\",\n    \"peruvian lily\",\n    \"balloon flower\",\n    \"giant white arum lily\",\n    \"fire lily\",\n    \"pincushion flower\",\n    \"fritillary\",\n    \"red ginger\",\n    \"grape hyacinth\",\n    \"corn poppy\",\n    \"prince of wales feathers\",\n    \"stemless gentian\",\n    \"artichoke\",\n    \"sweet william\",\n    \"carnation\",\n    \"garden phlox\",\n    \"love in the mist\",\n    \"cosmos\",\n    \"alpine sea holly\",\n    \"ruby-lipped cattleya\",\n    \"cape flower\",\n    \"great masterwort\",\n    \"siam tulip\",\n    \"lenten rose\",\n    \"barberton daisy\",\n    \"daffodil\",\n    \"sword lily\",\n    \"poinsettia\",\n    \"bolero deep blue\",\n    \"wallflower\",\n    \"marigold\",\n    \"buttercup\",\n    \"daisy\",\n    \"common dandelion\",\n    \"petunia\",\n    \"wild pansy\",\n    \"primula\",\n    \"sunflower\",\n    \"lilac hibiscus\",\n    \"bishop of llandaff\",\n    \"gaura\",\n    \"geranium\",\n    \"orange dahlia\",\n    \"pink-yellow dahlia\",\n    \"cautleya spicata\",\n    \"japanese anemone\",\n    \"black-eyed susan\",\n    \"silverbush\",\n    \"californian poppy\",\n    \"osteospermum\",\n    \"spring crocus\",\n    \"iris\",\n    \"windflower\",\n    \"tree poppy\",\n    \"gazania\",\n    \"azalea\",\n    \"water lily\",\n    \"rose\",\n    \"thorn apple\",\n    \"morning glory\",\n    \"passion flower\",\n    \"lotus\",\n    \"toad lily\",\n    \"anthurium\",\n    \"frangipani\",\n    \"clematis\",\n    \"hibiscus\",\n    \"columbine\",\n    \"desert-rose\",\n    \"tree mallow\",\n    \"magnolia\",\n    \"cyclamen \",\n    \"watercress\",\n    \"canna lily\",\n    \"hippeastrum \",\n    \"bee balm\",\n    \"pink quill\",\n    \"foxglove\",\n    \"bougainvillea\",\n    \"camellia\",\n    \"mallow\",\n    \"mexican petunia\",\n    \"bromelia\",\n    \"blanket flower\",\n    \"trumpet creeper\",\n    \"blackberry lily\",\n    \"common tulip\",\n    \"wild rose\",\n]","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\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image\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 = decode_image(example['image'])\n    label = tf.cast(example['class'], tf.int32)\n    return image, label\n\ndef read_unlabeled_tfrecord(test_example):\n    UNLABELED_TFREC_FORMAT = {\n        'image':tf.io.FixedLenFeature([], tf.string),\n        'id':tf.io.FixedLenFeature([], tf.string),\n    }\n    example = tf.io.parse_single_example(test_example,UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['id']\n    return image, idnum\n\ndef data_augment(image, label):\n    image = tf.image.random_flip_left_right(image)\n    return image, label \n\ndef load_dataset(filenames, labeled = True, ordered = False):\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads = AUTO)\n    dataset = dataset.with_options(ignore_order)\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls = AUTO)\n    return dataset\n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled = True, ordered = False)\n    dataset = dataset.map(data_augment, num_parallel_calls = AUTO)\n    dataset = dataset.repeat()\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_validation_dataset():\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled = True, ordered = False)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_test_dataset():\n    dataset = load_dataset(TEST_FILENAMES, labeled = False, ordered = True)\n    dataset = dataset.batch(BATCH_SIZE)\n    # prefetch next batch while training (autotune prefetch buffer 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 files, \n    # 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":{"trusted":true},"cell_type":"code","source":"NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"training_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Iterate over first batch (128 images)\nfor img, label in training_dataset.take(1):\n#     Get first 16 images\n    data = [img[0:16,:,:,:].numpy(),label[0:16].numpy()]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data[0].shape, data[1].shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"rows = 4\ncols = 4\nfig = plt.figure(figsize  = (18, 10))\nfor index in range(1, rows * cols + 1):\n    ax = fig.add_subplot(rows, cols, index)\n    img = data[0][index -1]\n    label = data[1][index - 1]\n    ax.axis('off')\n    plt.imshow(img)\n    plt.title(CLASSES[label])\nplt.show()","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":4}