{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import math, re, os\nimport tensorflow as tf\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\nprint(\"Tensorflow version \" + tf.__version__)\nAUTO = tf.data.experimental.AUTOTUNE","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"GCS_DS_PATH =  \"dataset\"# Your dataset path\nIMAGE_SIZE = [224, 224] # At this size, a GPU will run out of memory. Use the TPU.\n                        # For GPU training, please select 224 x 224 px image size.\n\naugment_img_size = 224\n\nGCS_PATH_SELECT = { # available 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}\nGCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]\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\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'] ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Datasets","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","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 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\n\ndef data_augment(image, label):\n    # data augmentation. Thanks to the dataset.prefetch(AUTO) statement in the next function (below),\n    # this happens essentially for free on TPU. Data pipeline code is executed on the \"CPU\" part\n    # of the TPU while the TPU itself is computing gradients.\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n    image = tf.image.resize(image, (256, 256))\n    image = tf.image.random_crop(image, (augment_img_size, augment_img_size, 3))\n    image = tf.image.per_image_standardization(image)\n    image = tf.transpose(image, [2, 0, 1])\n    # image = tf.image.adjust_brightness(image, 0.4)\n    # image = tf.image.adjust_contrast(image, 0.4)\n    # image = tf.image.adjust_saturation(image, 0.4)\n    #image = tf.image.random_saturation(image, 0, 2)\n    return image, label\n\ndef val_data_augment(image, label):\n    image = tf.image.resize(image, (augment_img_size, augment_img_size))\n    image = tf.image.per_image_standardization(image)\n    image = tf.transpose(image, [2,0,1])\n    #image = tf.image.random_saturation(image, 0, 2)\n    return image, label\n\ndef get_training_dataset(batch_size, do_augment=True):\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    if do_augment:\n        dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    # dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(batch_size, drop_remainder=False)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_validation_dataset(batch_size, ordered=False, do_augment=True):\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\n    if do_augment:\n        dataset = dataset.map(val_data_augment, num_parallel_calls=AUTO)\n    dataset = dataset.batch(batch_size, drop_remainder=False)\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(batch_size, ordered=False, do_augment=True):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    if do_augment:\n        dataset = dataset.map(val_data_augment, num_parallel_calls=AUTO)\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 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)\n\ndef get_data(train_batch_size, valid_batch_size, test_batch_size, img_size):\n    augment_img_size = img_size\n    train_data = get_training_dataset(train_batch_size)\n    val_data = get_validation_dataset(valid_batch_size)\n    test_data = get_test_dataset(test_batch_size)\n\n    train_data_len = count_data_items(TRAINING_FILENAMES)\n    val_data_len = count_data_items(VALIDATION_FILENAMES)\n    test_data_len = count_data_items(TEST_FILENAMES)\n\n    return train_data, val_data, test_data, train_data_len, val_data_len, test_data_len\n\ndef save_data_as_image_file():\n    batch_size = 1280\n\n    train_data = get_training_dataset(batch_size, do_augment=False)\n    val_data = get_validation_dataset(batch_size, do_augment=False)\n    test_data = get_test_dataset(batch_size, do_augment=False)\n\n    data_list = [train_data, val_data, test_data]\n    title_list = [\"train\", \"val\", \"test\"]\n    for did, data in enumerate(iter(data_list)):\n        for i, (imgs, labels) in enumerate(iter(data)):\n            print(\"get data from %s, batch %d\"%(title_list[did], i))\n            for imgid in range(len(imgs)):\n                image = imgs[imgid]\n                if (did!=len(data_list)-1):\n                    label = CLASSES[labels[imgid]].replace(\" \", \"_\")\n                    dirname = os.path.join(GCS_PATH, \"images\", title_list[did], label)\n                    os.makedirs(dirname, exist_ok=True)\n                    filename = os.path.join(dirname, \"%d_%d.jpg\"%(i, imgid))\n                else:\n                    label = \"all\"\n                    dirname = os.path.join(GCS_PATH, \"images\", title_list[did], label)\n                    os.makedirs(dirname, exist_ok=True)\n                    filename = os.path.join(dirname, \"%s.jpg\"%labels[imgid].numpy().decode())\n                image = image.numpy()*255\n                image[image>255]=255\n                image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n                try:\n                    cv2.imwrite(filename, image)\n                except:\n                    print(filename)\n                    break\n\n# save_data_as_image_file()","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}