{"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":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport glob\n\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.applications import VGG19, Xception\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\nimport os\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-03-29T13:30:18.189456Z","iopub.execute_input":"2022-03-29T13:30:18.189874Z","iopub.status.idle":"2022-03-29T13:30:24.188873Z","shell.execute_reply.started":"2022-03-29T13:30:18.189775Z","shell.execute_reply":"2022-03-29T13:30:24.188120Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size = 256\nIMAGE_SIZE = [512, 512]\nnum_epochs = 65","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:30:24.190100Z","iopub.execute_input":"2022-03-29T13:30:24.190631Z","iopub.status.idle":"2022-03-29T13:30:24.195350Z","shell.execute_reply.started":"2022-03-29T13:30:24.190589Z","shell.execute_reply":"2022-03-29T13:30:24.194438Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Set strategy","metadata":{}},{"cell_type":"code","source":"# Set distribution strategy to use TPUs\nresolver = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection\nprint('Found connected TPU: ', resolver.cluster_spec().as_dict()['worker'])\n\ntf.config.experimental_connect_to_cluster(resolver)\ntf.tpu.experimental.initialize_tpu_system(resolver)\nstrategy = tf.distribute.TPUStrategy(resolver)","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:30:29.333884Z","iopub.execute_input":"2022-03-29T13:30:29.334528Z","iopub.status.idle":"2022-03-29T13:30:35.079415Z","shell.execute_reply.started":"2022-03-29T13:30:29.334490Z","shell.execute_reply":"2022-03-29T13:30:35.078625Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:30:35.255989Z","iopub.execute_input":"2022-03-29T13:30:35.256436Z","iopub.status.idle":"2022-03-29T13:30:35.261497Z","shell.execute_reply.started":"2022-03-29T13:30:35.256397Z","shell.execute_reply":"2022-03-29T13:30:35.260321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# TPU requires everything to be in a GCS bucket to work.\n\nfrom 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":"2022-03-29T13:30:38.261768Z","iopub.execute_input":"2022-03-29T13:30:38.262047Z","iopub.status.idle":"2022-03-29T13:30:38.925848Z","shell.execute_reply.started":"2022-03-29T13:30:38.262019Z","shell.execute_reply":"2022-03-29T13:30:38.924742Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Read Images ","metadata":{"execution":{"iopub.status.busy":"2022-03-27T10:34:48.204897Z","iopub.execute_input":"2022-03-27T10:34:48.205148Z","iopub.status.idle":"2022-03-27T10:34:48.491554Z","shell.execute_reply.started":"2022-03-27T10:34:48.205121Z","shell.execute_reply":"2022-03-27T10:34:48.490355Z"}}},{"cell_type":"code","source":"# list files\ntrain_files = tf.io.gfile.glob(f'{GCS_DS_PATH}/tfrecords-jpeg-512x512/train/*')\nval_files = tf.io.gfile.glob(f'{GCS_DS_PATH}/tfrecords-jpeg-512x512/val/*')\ntest_files = tf.io.gfile.glob(f'{GCS_DS_PATH}/tfrecords-jpeg-512x512/test/*')","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:30:39.946706Z","iopub.execute_input":"2022-03-29T13:30:39.947004Z","iopub.status.idle":"2022-03-29T13:30:40.184249Z","shell.execute_reply.started":"2022-03-29T13:30:39.946970Z","shell.execute_reply":"2022-03-29T13:30:40.183556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# file name contains the number of samples in that tf record. 00-224x224-798.tfrec -> contains 798 samples.\ndef get_num_samples(file_list):\n    count = 0 \n    for file_name in file_list:\n        num_sample = int(file_name.split('.tfrec')[0].rsplit('-', 1)[1])\n        count += num_sample\n    return count","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:30:41.560158Z","iopub.execute_input":"2022-03-29T13:30:41.560634Z","iopub.status.idle":"2022-03-29T13:30:41.566961Z","shell.execute_reply.started":"2022-03-29T13:30:41.560591Z","shell.execute_reply":"2022-03-29T13:30:41.566173Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Sizes of each dataset","metadata":{}},{"cell_type":"code","source":"train_size = get_num_samples(train_files)\nval_size = get_num_samples(val_files)\ntest_size = get_num_samples(test_files)\n\nprint(f\"Train dataset size: {train_size}\")\nprint(f\"Validation dataset size: {val_size}\")\nprint(f\"Test dataset size: {test_size}\")","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:30:48.315815Z","iopub.execute_input":"2022-03-29T13:30:48.316305Z","iopub.status.idle":"2022-03-29T13:30:48.322726Z","shell.execute_reply.started":"2022-03-29T13:30:48.316270Z","shell.execute_reply":"2022-03-29T13:30:48.321872Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Functions and 'classes' variable in this cell were taken from https://www.kaggle.com/code/ryanholbrook/create-your-first-submission/notebook\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\ndef 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_saturation(image, 0, 2)\n    return image, label   \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)","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:30:50.830606Z","iopub.execute_input":"2022-03-29T13:30:50.831070Z","iopub.status.idle":"2022-03-29T13:30:50.848633Z","shell.execute_reply.started":"2022-03-29T13:30:50.831023Z","shell.execute_reply":"2022-03-29T13:30:50.847976Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Create TF data objects","metadata":{}},{"cell_type":"code","source":"train_dataset = tf.data.TFRecordDataset(train_files, num_parallel_reads=AUTO)\ntest_dataset = tf.data.TFRecordDataset(test_files, num_parallel_reads=AUTO)\nval_dataset = tf.data.TFRecordDataset(val_files, num_parallel_reads=AUTO)","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:30:51.552464Z","iopub.execute_input":"2022-03-29T13:30:51.552964Z","iopub.status.idle":"2022-03-29T13:30:51.584845Z","shell.execute_reply.started":"2022-03-29T13:30:51.552915Z","shell.execute_reply":"2022-03-29T13:30:51.583897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset = train_dataset.map(read_labeled_tfrecord)\ntrain_dataset = train_dataset.map(data_augment, num_parallel_calls=AUTO)\ntrain_dataset = train_dataset.shuffle(buffer_size=batch_size)\ntrain_dataset = train_dataset.repeat()\ntrain_dataset = train_dataset.batch(batch_size=batch_size)\ntrain_dataset = train_dataset.prefetch(buffer_size=batch_size)","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:30:51.842166Z","iopub.execute_input":"2022-03-29T13:30:51.842452Z","iopub.status.idle":"2022-03-29T13:30:52.055913Z","shell.execute_reply.started":"2022-03-29T13:30:51.842424Z","shell.execute_reply":"2022-03-29T13:30:52.055008Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_dataset = val_dataset.map(read_labeled_tfrecord)\nval_dataset = val_dataset.batch(batch_size=batch_size)\nval_dataset = val_dataset.prefetch(buffer_size=batch_size)","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:30:52.060641Z","iopub.execute_input":"2022-03-29T13:30:52.060888Z","iopub.status.idle":"2022-03-29T13:30:52.085157Z","shell.execute_reply.started":"2022-03-29T13:30:52.060861Z","shell.execute_reply":"2022-03-29T13:30:52.084506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_dataset = test_dataset.map(read_unlabeled_tfrecord)\ntest_dataset = test_dataset.prefetch(buffer_size=batch_size)","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:30:52.513676Z","iopub.execute_input":"2022-03-29T13:30:52.514373Z","iopub.status.idle":"2022-03-29T13:30:52.599090Z","shell.execute_reply.started":"2022-03-29T13:30:52.514334Z","shell.execute_reply":"2022-03-29T13:30:52.598062Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Build model","metadata":{"execution":{"iopub.status.busy":"2022-03-27T11:06:51.727295Z","iopub.execute_input":"2022-03-27T11:06:51.727602Z"}}},{"cell_type":"code","source":"# VGG19 model\ndef create_vgg19_model():\n    base_model = VGG19(\n        weights='imagenet',\n        input_shape=(512, 512, 3),\n        include_top=False\n    )\n    base_model.trainable = False\n    inputs = tf.keras.Input(shape=(512, 512, 3))\n    x = base_model(inputs, training=False)\n    x = layers.GlobalAveragePooling2D()(x)\n    x = layers.Flatten()(x)\n    x = layers.Dense(4112, activation='relu')(x)\n    x = layers.Dense(2056, activation='relu')(x)\n    x = layers.Dense(1024, activation='relu')(x)\n    x = layers.Dense(512, activation='relu')(x)\n    outputs = layers.Dense(len(CLASSES), activation='softmax')(x)\n    model = tf.keras.Model(inputs, outputs)\n\n    model.compile(optimizer='adam',\n                  loss='sparse_categorical_crossentropy',\n                  metrics=['sparse_categorical_accuracy'])\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:30:55.211693Z","iopub.execute_input":"2022-03-29T13:30:55.212317Z","iopub.status.idle":"2022-03-29T13:30:55.221272Z","shell.execute_reply.started":"2022-03-29T13:30:55.212278Z","shell.execute_reply":"2022-03-29T13:30:55.220401Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Xception model\ndef create_xception_model():\n    base_model = Xception(\n    weights='imagenet',  # Load weights pre-trained on ImageNet.\n    input_shape=(512, 512, 3),\n    include_top=False)\n    \n    base_model.trainable = False\n    inputs = tf.keras.Input(shape=(512, 512, 3))\n    x = base_model(inputs, training=False)\n    x = layers.GlobalAveragePooling2D()(x)\n    x = layers.Flatten()(x)\n    x = layers.Dense(4112, activation='relu')(x)\n    x = layers.Dropout(0.5)(x)\n    x = layers.Dense(4112, activation='relu')(x)\n    outputs = layers.Dense(len(CLASSES), activation='softmax')(x)\n    model = tf.keras.Model(inputs, outputs)\n\n    model.compile(optimizer='adam',\n                  loss='sparse_categorical_crossentropy',\n                  metrics=['sparse_categorical_accuracy'])\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:30:58.276980Z","iopub.execute_input":"2022-03-29T13:30:58.277575Z","iopub.status.idle":"2022-03-29T13:30:58.286407Z","shell.execute_reply.started":"2022-03-29T13:30:58.277533Z","shell.execute_reply":"2022-03-29T13:30:58.285332Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Callbacks","metadata":{}},{"cell_type":"code","source":"cp_callback = ModelCheckpoint(filepath='flower_model_xception.hdf5',\n                              monitor='val_sparse_categorical_accuracy',\n                              save_freq='epoch', verbose=1, period=1,\n                              save_best_only=True, save_weights_only=True)\n\nearly_stopping = EarlyStopping(monitor='val_sparse_categorical_accuracy',\n                               verbose=1, patience=5)","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:31:01.077965Z","iopub.execute_input":"2022-03-29T13:31:01.078247Z","iopub.status.idle":"2022-03-29T13:31:01.084000Z","shell.execute_reply.started":"2022-03-29T13:31:01.078219Z","shell.execute_reply":"2022-03-29T13:31:01.083328Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Train","metadata":{}},{"cell_type":"code","source":"with strategy.scope():\n    batch_size = batch_size * strategy.num_replicas_in_sync\n    steps_per_epoch = int(train_size / batch_size)*2\n    model = create_xception_model()\n    history = model.fit(\n                train_dataset, \n                validation_data=val_dataset,\n                epochs=num_epochs,\n                steps_per_epoch=steps_per_epoch,\n                callbacks=[cp_callback, early_stopping])","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:31:07.489995Z","iopub.execute_input":"2022-03-29T13:31:07.490431Z","iopub.status.idle":"2022-03-29T13:43:34.901164Z","shell.execute_reply.started":"2022-03-29T13:31:07.490399Z","shell.execute_reply":"2022-03-29T13:43:34.900238Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history['loss'], label='train_loss') \nplt.plot(history.history['val_loss'], label='val_loss')\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:44:03.686870Z","iopub.execute_input":"2022-03-29T13:44:03.687209Z","iopub.status.idle":"2022-03-29T13:44:03.916188Z","shell.execute_reply.started":"2022-03-29T13:44:03.687174Z","shell.execute_reply":"2022-03-29T13:44:03.915126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history['sparse_categorical_accuracy'], label='train_accuracy')\nplt.plot(history.history['val_sparse_categorical_accuracy'], label='val_accuracy')\nplt.legend() \nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:44:07.161460Z","iopub.execute_input":"2022-03-29T13:44:07.161770Z","iopub.status.idle":"2022-03-29T13:44:07.896530Z","shell.execute_reply.started":"2022-03-29T13:44:07.161739Z","shell.execute_reply":"2022-03-29T13:44:07.895519Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = create_xception_model()\nmodel.load_weights('flower_model_xception.hdf5')","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:44:40.674660Z","iopub.execute_input":"2022-03-29T13:44:40.675161Z","iopub.status.idle":"2022-03-29T13:44:43.685843Z","shell.execute_reply.started":"2022-03-29T13:44:40.675110Z","shell.execute_reply":"2022-03-29T13:44:43.684301Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results = {'id': [], 'label': []}","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:44:51.993193Z","iopub.execute_input":"2022-03-29T13:44:51.993922Z","iopub.status.idle":"2022-03-29T13:44:51.998942Z","shell.execute_reply.started":"2022-03-29T13:44:51.993879Z","shell.execute_reply":"2022-03-29T13:44:51.997742Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Test","metadata":{}},{"cell_type":"code","source":"def predict(element):\n    image = element[0]\n    id_ = tf.keras.backend.get_value(element[1]).decode(\"utf-8\")\n    result = list(model.predict(np.array([image]))[0])\n    max_pred = max(result)\n    result = result.index(max_pred)\n    results['id'].append(id_)\n    results['label'].append(result) ","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"count = 0\nfor row in test_dataset: \n    image = row[0]\n    id_ = tf.keras.backend.get_value(row[1]).decode(\"utf-8\")\n    result = list(model.predict(np.array([image]))[0])\n    max_pred = max(result) \n    result = result.index(max_pred) \n    results['id'].append(id_)\n    results['label'].append(result)\n    count += 1 \n    if (count % 500) == 0:\n        print(f\"Finished predicting {count} images\") ","metadata":{"execution":{"iopub.status.busy":"2022-03-29T13:44:55.823764Z","iopub.execute_input":"2022-03-29T13:44:55.824365Z","iopub.status.idle":"2022-03-29T14:11:08.890782Z","shell.execute_reply.started":"2022-03-29T13:44:55.824322Z","shell.execute_reply":"2022-03-29T14:11:08.889393Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results_df = pd.DataFrame(results)\nresults_df.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2022-03-29T14:11:13.839717Z","iopub.execute_input":"2022-03-29T14:11:13.840445Z","iopub.status.idle":"2022-03-29T14:11:13.888227Z","shell.execute_reply.started":"2022-03-29T14:11:13.840395Z","shell.execute_reply":"2022-03-29T14:11:13.887195Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}