{"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, ReduceLROnPlateau\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.applications import VGG19, Xception, DenseNet121\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-04-03T09:10:57.465458Z","iopub.execute_input":"2022-04-03T09:10:57.465772Z","iopub.status.idle":"2022-04-03T09:11:02.410899Z","shell.execute_reply.started":"2022-04-03T09:10:57.465727Z","shell.execute_reply":"2022-04-03T09:11:02.410178Z"},"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-04-03T09:11:07.484611Z","iopub.execute_input":"2022-04-03T09:11:07.485201Z","iopub.status.idle":"2022-04-03T09:11:07.489867Z","shell.execute_reply.started":"2022-04-03T09:11:07.485165Z","shell.execute_reply":"2022-04-03T09:11:07.489169Z"},"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-04-03T09:11:08.324429Z","iopub.execute_input":"2022-04-03T09:11:08.324747Z","iopub.status.idle":"2022-04-03T09:11:14.115092Z","shell.execute_reply.started":"2022-04-03T09:11:08.324714Z","shell.execute_reply":"2022-04-03T09:11:14.114159Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE","metadata":{"execution":{"iopub.status.busy":"2022-04-03T09:11:14.117413Z","iopub.execute_input":"2022-04-03T09:11:14.117679Z","iopub.status.idle":"2022-04-03T09:11:14.121856Z","shell.execute_reply.started":"2022-04-03T09:11:14.117649Z","shell.execute_reply":"2022-04-03T09:11:14.120950Z"},"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-04-03T09:11:14.123104Z","iopub.execute_input":"2022-04-03T09:11:14.123344Z","iopub.status.idle":"2022-04-03T09:11:15.399512Z","shell.execute_reply.started":"2022-04-03T09:11:14.123293Z","shell.execute_reply":"2022-04-03T09:11:15.398419Z"},"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-04-03T09:11:15.401305Z","iopub.execute_input":"2022-04-03T09:11:15.401539Z","iopub.status.idle":"2022-04-03T09:11:15.859346Z","shell.execute_reply.started":"2022-04-03T09:11:15.401512Z","shell.execute_reply":"2022-04-03T09:11:15.858277Z"},"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-04-03T09:11:15.860518Z","iopub.execute_input":"2022-04-03T09:11:15.860737Z","iopub.status.idle":"2022-04-03T09:11:15.866008Z","shell.execute_reply.started":"2022-04-03T09:11:15.860713Z","shell.execute_reply":"2022-04-03T09:11:15.865188Z"},"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-04-03T09:12:12.914272Z","iopub.execute_input":"2022-04-03T09:12:12.914557Z","iopub.status.idle":"2022-04-03T09:12:12.921146Z","shell.execute_reply.started":"2022-04-03T09:12:12.914530Z","shell.execute_reply":"2022-04-03T09:12:12.920227Z"},"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-04-03T09:12:13.167764Z","iopub.execute_input":"2022-04-03T09:12:13.168031Z","iopub.status.idle":"2022-04-03T09:12:13.183399Z","shell.execute_reply.started":"2022-04-03T09:12:13.168005Z","shell.execute_reply":"2022-04-03T09:12:13.182819Z"},"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-04-03T09:12:14.178181Z","iopub.execute_input":"2022-04-03T09:12:14.178509Z","iopub.status.idle":"2022-04-03T09:12:14.209132Z","shell.execute_reply.started":"2022-04-03T09:12:14.178474Z","shell.execute_reply":"2022-04-03T09:12:14.208207Z"},"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-04-03T09:12:14.650327Z","iopub.execute_input":"2022-04-03T09:12:14.650940Z","iopub.status.idle":"2022-04-03T09:12:14.856262Z","shell.execute_reply.started":"2022-04-03T09:12:14.650900Z","shell.execute_reply":"2022-04-03T09:12:14.855097Z"},"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-04-03T09:12:15.369584Z","iopub.execute_input":"2022-04-03T09:12:15.370143Z","iopub.status.idle":"2022-04-03T09:12:15.390476Z","shell.execute_reply.started":"2022-04-03T09:12:15.370095Z","shell.execute_reply":"2022-04-03T09:12:15.389715Z"},"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-04-03T09:12:15.642147Z","iopub.execute_input":"2022-04-03T09:12:15.642421Z","iopub.status.idle":"2022-04-03T09:12:15.724128Z","shell.execute_reply.started":"2022-04-03T09:12:15.642392Z","shell.execute_reply":"2022-04-03T09:12:15.723261Z"},"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_densenet121_model():\n    base_model = DenseNet121(\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-04-03T09:12:23.329883Z","iopub.execute_input":"2022-04-03T09:12:23.330135Z","iopub.status.idle":"2022-04-03T09:12:23.338529Z","shell.execute_reply.started":"2022-04-03T09:12:23.330111Z","shell.execute_reply":"2022-04-03T09:12:23.337756Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Callbacks","metadata":{}},{"cell_type":"code","source":"cp_callback = ModelCheckpoint(filepath='flower_model_densenet121.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, mode='max')\n\nreduce_lr = ReduceLROnPlateau(monitor='val_sparse_categorical_accuracy', factor=0.2, patience=2, \n                              verbose=1, mode='max', min_lr=1e-5,)","metadata":{"execution":{"iopub.status.busy":"2022-04-03T09:13:30.503330Z","iopub.execute_input":"2022-04-03T09:13:30.503944Z","iopub.status.idle":"2022-04-03T09:13:30.511277Z","shell.execute_reply.started":"2022-04-03T09:13:30.503889Z","shell.execute_reply":"2022-04-03T09:13:30.510450Z"},"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_densenet121_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=[reduce_lr, cp_callback, early_stopping])","metadata":{"execution":{"iopub.status.busy":"2022-04-03T09:13:32.779637Z","iopub.execute_input":"2022-04-03T09:13:32.779953Z","iopub.status.idle":"2022-04-03T09:31:02.711599Z","shell.execute_reply.started":"2022-04-03T09:13:32.779921Z","shell.execute_reply":"2022-04-03T09:31:02.710651Z"},"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-04-03T09:31:10.526487Z","iopub.execute_input":"2022-04-03T09:31:10.526951Z","iopub.status.idle":"2022-04-03T09:31:10.788567Z","shell.execute_reply.started":"2022-04-03T09:31:10.526898Z","shell.execute_reply":"2022-04-03T09:31:10.787794Z"},"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-04-03T09:31:13.375217Z","iopub.execute_input":"2022-04-03T09:31:13.375501Z","iopub.status.idle":"2022-04-03T09:31:13.538469Z","shell.execute_reply.started":"2022-04-03T09:31:13.375473Z","shell.execute_reply":"2022-04-03T09:31:13.537681Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = create_densenet121_model()\nmodel.load_weights('flower_model_densenet121.hdf5')","metadata":{"execution":{"iopub.status.busy":"2022-04-03T09:31:43.487352Z","iopub.execute_input":"2022-04-03T09:31:43.487968Z","iopub.status.idle":"2022-04-03T09:31:49.214792Z","shell.execute_reply.started":"2022-04-03T09:31:43.487918Z","shell.execute_reply":"2022-04-03T09:31:49.213699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results = {'id': [], 'label': []}","metadata":{"execution":{"iopub.status.busy":"2022-04-03T09:32:08.301375Z","iopub.execute_input":"2022-04-03T09:32:08.301660Z","iopub.status.idle":"2022-04-03T09:32:08.306083Z","shell.execute_reply.started":"2022-04-03T09:32:08.301632Z","shell.execute_reply":"2022-04-03T09:32:08.305124Z"},"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":{"iopub.status.busy":"2022-04-03T09:32:28.603852Z","iopub.execute_input":"2022-04-03T09:32:28.604467Z","iopub.status.idle":"2022-04-03T09:32:28.610429Z","shell.execute_reply.started":"2022-04-03T09:32:28.604429Z","shell.execute_reply":"2022-04-03T09:32:28.609405Z"},"trusted":true},"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-04-03T09:32:28.749713Z","iopub.execute_input":"2022-04-03T09:32:28.749986Z","iopub.status.idle":"2022-04-03T10:01:27.941685Z","shell.execute_reply.started":"2022-04-03T09:32:28.749960Z","shell.execute_reply":"2022-04-03T10:01:27.940914Z"},"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-04-03T10:05:24.062779Z","iopub.execute_input":"2022-04-03T10:05:24.063711Z","iopub.status.idle":"2022-04-03T10:05:24.095417Z","shell.execute_reply.started":"2022-04-03T10:05:24.063669Z","shell.execute_reply":"2022-04-03T10:05:24.094488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}