{"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":"import math\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport tensorflow as tf","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-07-12T14:53:16.542443Z","iopub.execute_input":"2021-07-12T14:53:16.542864Z","iopub.status.idle":"2021-07-12T14:53:22.298916Z","shell.execute_reply.started":"2021-07-12T14:53:16.542776Z","shell.execute_reply":"2021-07-12T14:53:22.297943Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load Datasets","metadata":{}},{"cell_type":"code","source":"IMAGE_SIZE = [224, 224]\nBATCH_SIZE = 64\n\ndef decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32)\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    image = tf.keras.applications.xception.preprocess_input(image)\n    return image\n\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\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\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    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=tf.data.AUTOTUNE) # 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=tf.data.AUTOTUNE)\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":"2021-07-12T14:53:22.300693Z","iopub.execute_input":"2021-07-12T14:53:22.301082Z","iopub.status.idle":"2021-07-12T14:53:22.315977Z","shell.execute_reply.started":"2021-07-12T14:53:22.30104Z","shell.execute_reply":"2021-07-12T14:53:22.314994Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def data_augment(image, label):\n    # Thanks to the dataset.prefetch(AUTO)\n    # statement in the next function (below), this happens essentially\n    # for free on TPU. Data pipeline code is executed on the \"CPU\"\n    # part 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.random_saturation(image, 0, 2)\n    image = tf.image.random_brightness(image, 0.2)\n    return image, label   \n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    dataset = dataset.map(data_augment, num_parallel_calls=tf.data.AUTOTUNE)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(tf.data.AUTOTUNE) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(tf.data.AUTOTUNE)\n    return dataset\n\ndef 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(tf.data.AUTOTUNE)\n    return dataset\n\ndef count_data_items(filenames):\n    import re\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":"2021-07-12T14:53:22.319815Z","iopub.execute_input":"2021-07-12T14:53:22.32016Z","iopub.status.idle":"2021-07-12T14:53:22.335142Z","shell.execute_reply.started":"2021-07-12T14:53:22.32012Z","shell.execute_reply":"2021-07-12T14:53:22.333935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_PATH = '../input/tpu-getting-started/tfrecords-jpeg-224x224'\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') \n\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","metadata":{"execution":{"iopub.status.busy":"2021-07-12T14:53:22.339221Z","iopub.execute_input":"2021-07-12T14:53:22.339543Z","iopub.status.idle":"2021-07-12T14:53:22.368127Z","shell.execute_reply.started":"2021-07-12T14:53:22.339511Z","shell.execute_reply":"2021-07-12T14:53:22.36711Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds_train = get_training_dataset()\nds_valid = get_validation_dataset()\nds_test = get_test_dataset()\n\nprint(\"Training:\", ds_train)\nprint (\"Validation:\", ds_valid)\nprint(\"Test:\", ds_test)","metadata":{"execution":{"iopub.status.busy":"2021-07-12T14:53:22.371361Z","iopub.execute_input":"2021-07-12T14:53:22.371688Z","iopub.status.idle":"2021-07-12T14:53:24.669239Z","shell.execute_reply.started":"2021-07-12T14:53:22.37165Z","shell.execute_reply":"2021-07-12T14:53:24.668334Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CLASSES = ['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","metadata":{"execution":{"iopub.status.busy":"2021-07-12T14:53:24.670507Z","iopub.execute_input":"2021-07-12T14:53:24.670856Z","iopub.status.idle":"2021-07-12T14:53:24.679382Z","shell.execute_reply.started":"2021-07-12T14:53:24.670821Z","shell.execute_reply":"2021-07-12T14:53:24.678436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(CLASSES)","metadata":{"execution":{"iopub.status.busy":"2021-07-12T14:53:24.681918Z","iopub.execute_input":"2021-07-12T14:53:24.682639Z","iopub.status.idle":"2021-07-12T14:53:24.699988Z","shell.execute_reply.started":"2021-07-12T14:53:24.682566Z","shell.execute_reply":"2021-07-12T14:53:24.698778Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for x, y in ds_train.take(1):\n    print(y)","metadata":{"execution":{"iopub.status.busy":"2021-07-12T14:53:24.702095Z","iopub.execute_input":"2021-07-12T14:53:24.702562Z","iopub.status.idle":"2021-07-12T14:53:30.12984Z","shell.execute_reply.started":"2021-07-12T14:53:24.702515Z","shell.execute_reply":"2021-07-12T14:53:30.128855Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prepare Model","metadata":{}},{"cell_type":"markdown","source":"We use the xception as the base model and add a to new layers","metadata":{}},{"cell_type":"code","source":"base_model = tf.keras.applications.xception.Xception(weights='imagenet', include_top=False)\navg = tf.keras.layers.GlobalAveragePooling2D()(base_model.output)\noutput = tf.keras.layers.Dense(len(CLASSES), activation='softmax')(avg)\nmodel = tf.keras.Model(inputs=base_model.input, outputs=output)","metadata":{"execution":{"iopub.status.busy":"2021-07-12T14:53:30.131706Z","iopub.execute_input":"2021-07-12T14:53:30.132056Z","iopub.status.idle":"2021-07-12T14:53:32.563308Z","shell.execute_reply.started":"2021-07-12T14:53:30.132016Z","shell.execute_reply":"2021-07-12T14:53:32.56241Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Freeze base model layers**","metadata":{}},{"cell_type":"code","source":"for layer in base_model.layers:\n    layer.trainable = False","metadata":{"execution":{"iopub.status.busy":"2021-07-12T14:53:32.565036Z","iopub.execute_input":"2021-07-12T14:53:32.565369Z","iopub.status.idle":"2021-07-12T14:53:32.574342Z","shell.execute_reply.started":"2021-07-12T14:53:32.565332Z","shell.execute_reply":"2021-07-12T14:53:32.572965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2021-07-12T14:53:38.846798Z","iopub.execute_input":"2021-07-12T14:53:38.847143Z","iopub.status.idle":"2021-07-12T14:53:38.916274Z","shell.execute_reply.started":"2021-07-12T14:53:38.847111Z","shell.execute_reply":"2021-07-12T14:53:38.915304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Train model with freezed layers**\n\nWe do this in order to not disturb the weights of xception when trying to fit the new layers on the new dataset","metadata":{}},{"cell_type":"code","source":"initial_lr = 0.1\noptimizer = tf.keras.optimizers.Nadam(lr=initial_lr)\nmodel.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2021-07-12T14:53:41.121355Z","iopub.execute_input":"2021-07-12T14:53:41.121721Z","iopub.status.idle":"2021-07-12T14:53:41.145032Z","shell.execute_reply.started":"2021-07-12T14:53:41.121683Z","shell.execute_reply":"2021-07-12T14:53:41.143767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"initial_epochs = 10\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nmodel.fit(ds_train, validation_data=ds_valid, epochs=initial_epochs, steps_per_epoch=STEPS_PER_EPOCH)","metadata":{"execution":{"iopub.status.busy":"2021-07-12T14:53:47.131294Z","iopub.execute_input":"2021-07-12T14:53:47.131692Z","iopub.status.idle":"2021-07-12T14:54:42.817564Z","shell.execute_reply.started":"2021-07-12T14:53:47.131653Z","shell.execute_reply":"2021-07-12T14:54:42.816647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Train model by unfreezing the last 6 layers of xception**\n\nWe lower the learing rate by a lot because again we want to only make small adjustments on xception weights. After unfreezing we have to recompile model","metadata":{}},{"cell_type":"code","source":"for layer in base_model.layers[-6:]:\n    layer.trainable = True","metadata":{"execution":{"iopub.status.busy":"2021-07-12T14:54:42.81939Z","iopub.execute_input":"2021-07-12T14:54:42.819801Z","iopub.status.idle":"2021-07-12T14:54:42.825123Z","shell.execute_reply.started":"2021-07-12T14:54:42.819754Z","shell.execute_reply":"2021-07-12T14:54:42.824104Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lr = 0.01\noptimizer = tf.keras.optimizers.Nadam(lr=lr)\nmodel.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2021-07-12T14:54:42.827116Z","iopub.execute_input":"2021-07-12T14:54:42.827749Z","iopub.status.idle":"2021-07-12T14:54:42.851872Z","shell.execute_reply.started":"2021-07-12T14:54:42.827706Z","shell.execute_reply":"2021-07-12T14:54:42.85093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs = 200\nmodel.fit(ds_train, validation_data=ds_valid, epochs=epochs, steps_per_epoch=STEPS_PER_EPOCH, callbacks=[\n    tf.keras.callbacks.EarlyStopping(patience=30, restore_best_weights=True),\n    tf.keras.callbacks.ReduceLROnPlateau(factor=0.2, patience=4)\n])","metadata":{"execution":{"iopub.status.busy":"2021-07-12T14:54:42.853515Z","iopub.execute_input":"2021-07-12T14:54:42.853892Z","iopub.status.idle":"2021-07-12T14:56:14.474055Z","shell.execute_reply.started":"2021-07-12T14:54:42.853852Z","shell.execute_reply":"2021-07-12T14:56:14.473187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Stack train and validation data and retrain more layers**","metadata":{}},{"cell_type":"code","source":"for layer in base_model.layers[-16:]:\n    layer.trainable = True","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lr = 0.01\noptimizer = tf.keras.optimizers.Nadam(lr=lr)\nmodel.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy'])","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs = 200\nmodel.fit(ds_train, validation_data=ds_valid, epochs=epochs, steps_per_epoch=STEPS_PER_EPOCH, callbacks=[\n    tf.keras.callbacks.EarlyStopping(patience=30, restore_best_weights=True),\n    tf.keras.callbacks.ReduceLROnPlateau(factor=0.2, patience=4)\n])","metadata":{"execution":{"iopub.status.busy":"2021-07-12T14:56:14.475317Z","iopub.execute_input":"2021-07-12T14:56:14.475686Z","iopub.status.idle":"2021-07-12T14:57:25.242426Z","shell.execute_reply.started":"2021-07-12T14:56:14.475645Z","shell.execute_reply":"2021-07-12T14:57:25.241697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Make Predictions","metadata":{}},{"cell_type":"code","source":"predictions = model.predict(ds_test)\npredictions.shape","metadata":{"execution":{"iopub.status.busy":"2021-07-12T11:58:11.592346Z","iopub.execute_input":"2021-07-12T11:58:11.592729Z","iopub.status.idle":"2021-07-12T11:58:28.463188Z","shell.execute_reply.started":"2021-07-12T11:58:11.592698Z","shell.execute_reply":"2021-07-12T11:58:28.462043Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ids = list(ds_test.unbatch().map(lambda data, _id: _id).as_numpy_iterator())\nids = list(map(lambda x: x.decode(), ids))","metadata":{"execution":{"iopub.status.busy":"2021-07-12T11:58:28.466756Z","iopub.execute_input":"2021-07-12T11:58:28.46706Z","iopub.status.idle":"2021-07-12T11:58:36.580781Z","shell.execute_reply.started":"2021-07-12T11:58:28.467017Z","shell.execute_reply":"2021-07-12T11:58:36.579479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame({'id': ids, 'label': tf.argmax(predictions, axis=1)})\nsubmission = submission.astype({'id': 'string'})\nsubmission.to_csv('submission.csv', index=False)\nsubmission","metadata":{"execution":{"iopub.status.busy":"2021-07-12T11:58:36.5877Z","iopub.execute_input":"2021-07-12T11:58:36.588926Z","iopub.status.idle":"2021-07-12T11:58:37.078912Z","shell.execute_reply.started":"2021-07-12T11:58:36.588823Z","shell.execute_reply":"2021-07-12T11:58:37.077868Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}