{"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 numpy as np \nimport pandas as pd \n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-09-13T13:51:47.816023Z","iopub.execute_input":"2022-09-13T13:51:47.816351Z","iopub.status.idle":"2022-09-13T13:51:47.946264Z","shell.execute_reply.started":"2022-09-13T13:51:47.816318Z","shell.execute_reply":"2022-09-13T13:51:47.945303Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# basic libraries \nimport os, re, math \nimport numpy as np \nimport pandas as pd \nimport tensorflow as tf\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# libraries for model \nfrom tensorflow.keras import optimizers, layers, models, utils\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout, Activation\nfrom sklearn.metrics import confusion_matrix, classification_report, accuracy_score, precision_score, recall_score, f1_score\nfrom sklearn.model_selection import train_test_split","metadata":{"execution":{"iopub.status.busy":"2022-09-13T13:55:26.595510Z","iopub.execute_input":"2022-09-13T13:55:26.596166Z","iopub.status.idle":"2022-09-13T13:55:26.602328Z","shell.execute_reply.started":"2022-09-13T13:55:26.596121Z","shell.execute_reply":"2022-09-13T13:55:26.601681Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# finding the version of tf\nimport tensorflow as tf\nprint('Tensorflow version ' + tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2022-09-13T13:51:55.870002Z","iopub.execute_input":"2022-09-13T13:51:55.870327Z","iopub.status.idle":"2022-09-13T13:51:55.876997Z","shell.execute_reply.started":"2022-09-13T13:51:55.870285Z","shell.execute_reply":"2022-09-13T13:51:55.876004Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Setup TPU/detect TPU, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Device:', tpu.master())\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.TPUStrategy(tpu)\nexcept:\n    strategy = tf.distribute.get_strategy()\nprint('Number of accelerators/replicas:', strategy.num_replicas_in_sync)\n","metadata":{"execution":{"iopub.status.busy":"2022-09-13T13:51:55.879343Z","iopub.execute_input":"2022-09-13T13:51:55.879781Z","iopub.status.idle":"2022-09-13T13:52:02.051003Z","shell.execute_reply.started":"2022-09-13T13:51:55.879737Z","shell.execute_reply":"2022-09-13T13:52:02.050027Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Loading the dataset from kaggle\nWhen used with TPUs, datasets need to be stored in a Google Cloud Storage bucket.\nYou can use data from any public GCS bucket by giving its path just like you would data from '/kaggle/input'.\nThe following will retrieve the GCS path for this competition's dataset.","metadata":{}},{"cell_type":"code","source":"# Moving Data To Google Cloud Storage (GCS). TPUs require data to be present on GCS. The below utility copies the data to a GCS bucket co-located with the TPU.\n# Using TFrecords often requires gsbucket address. You could get the gsbucket address by using kaggle API as below:\n\nfrom kaggle_datasets import KaggleDatasets\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\nprint(GCS_DS_PATH)            # this is how the gsbucket address looks like OR say the path where the dataset is stored in cloud","metadata":{"execution":{"iopub.status.busy":"2022-09-13T13:52:02.052243Z","iopub.execute_input":"2022-09-13T13:52:02.052512Z","iopub.status.idle":"2022-09-13T13:52:02.654930Z","shell.execute_reply.started":"2022-09-13T13:52:02.052483Z","shell.execute_reply":"2022-09-13T13:52:02.653971Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [224, 224]\nGCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-224x224'\nAUTO = tf.data.experimental.AUTOTUNE\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\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']  ","metadata":{"execution":{"iopub.status.busy":"2022-09-13T13:53:20.600544Z","iopub.execute_input":"2022-09-13T13:53:20.600836Z","iopub.status.idle":"2022-09-13T13:53:21.055041Z","shell.execute_reply.started":"2022-09-13T13:53:20.600808Z","shell.execute_reply":"2022-09-13T13:53:21.053963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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","metadata":{"execution":{"iopub.status.busy":"2022-09-13T13:53:52.148199Z","iopub.execute_input":"2022-09-13T13:53:52.149112Z","iopub.status.idle":"2022-09-13T13:53:52.159924Z","shell.execute_reply.started":"2022-09-13T13:53:52.149071Z","shell.execute_reply":"2022-09-13T13:53:52.159172Z"},"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_saturation(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=AUTO)\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(AUTO) # 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(AUTO)\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(AUTO)\n    return dataset\n\ndef count_data_items(filenames):\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)\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":"2022-09-13T13:55:32.372111Z","iopub.execute_input":"2022-09-13T13:55:32.372548Z","iopub.status.idle":"2022-09-13T13:55:32.387750Z","shell.execute_reply.started":"2022-09-13T13:55:32.372507Z","shell.execute_reply":"2022-09-13T13:55:32.386865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the batch size. This will be 16 with TPU off and 128 (=16*8) with TPU on\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nds_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":"2022-09-13T13:56:01.187371Z","iopub.execute_input":"2022-09-13T13:56:01.188019Z","iopub.status.idle":"2022-09-13T13:56:01.667351Z","shell.execute_reply.started":"2022-09-13T13:56:01.187971Z","shell.execute_reply":"2022-09-13T13:56:01.666360Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.set_printoptions(threshold=15, linewidth=80)\n\nprint(\"Training data shapes:\")\nfor image, label in ds_train.take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Training data label examples:\", label.numpy())","metadata":{"execution":{"iopub.status.busy":"2022-09-13T13:56:35.472103Z","iopub.execute_input":"2022-09-13T13:56:35.473128Z","iopub.status.idle":"2022-09-13T13:56:37.850016Z","shell.execute_reply.started":"2022-09-13T13:56:35.473071Z","shell.execute_reply":"2022-09-13T13:56:37.848756Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Test data shapes:\")\nfor image, idnum in ds_test.take(3):\n    print(image.numpy().shape, idnum.numpy().shape)\nprint(\"Test data IDs:\", idnum.numpy().astype('U')) # U=unicode string","metadata":{"execution":{"iopub.status.busy":"2022-09-13T13:56:42.884535Z","iopub.execute_input":"2022-09-13T13:56:42.885394Z","iopub.status.idle":"2022-09-13T13:56:44.907716Z","shell.execute_reply.started":"2022-09-13T13:56:42.885340Z","shell.execute_reply":"2022-09-13T13:56:44.906704Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EPOCHS = 12\n\nwith strategy.scope():    \n    densenet = tf.keras.applications.DenseNet201(\n        input_shape = (224, 224, 3),\n        weights = 'imagenet',  # Use the preset parameters of ImageNet\n        include_top = False  # Drop the fully connected network on the top\n    )\n    \n    densenet.trainable =True\n    model = tf.keras.Sequential([\n        densenet,\n        #tf.keras.layers.Dropout(0.2),\n        #tf.keras.layers.BatchNormalization(),\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')\n    ])\n\n    model.compile(\n        optimizer=tf.keras.optimizers.Adam(), loss = 'sparse_categorical_crossentropy', \n        metrics = ['sparse_categorical_accuracy']\n    )","metadata":{"execution":{"iopub.status.busy":"2022-09-13T13:57:10.234703Z","iopub.execute_input":"2022-09-13T13:57:10.235361Z","iopub.status.idle":"2022-09-13T13:57:48.851840Z","shell.execute_reply.started":"2022-09-13T13:57:10.235305Z","shell.execute_reply":"2022-09-13T13:57:48.850935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow import keras\n\nmodel.compile(\n    optimizer=keras.optimizers.Adam(learning_rate=0.00001),\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'],\n)","metadata":{"execution":{"iopub.status.busy":"2022-09-13T13:58:59.177516Z","iopub.execute_input":"2022-09-13T13:58:59.178122Z","iopub.status.idle":"2022-09-13T13:58:59.238809Z","shell.execute_reply.started":"2022-09-13T13:58:59.178082Z","shell.execute_reply":"2022-09-13T13:58:59.238139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"NUM_TRAINING_IMAGES = 12753\nNUM_TEST_IMAGES = 7382\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\nhistory = model.fit(\n    ds_train,\n    validation_data=ds_valid,\n    epochs=30,steps_per_epoch=STEPS_PER_EPOCH\n)","metadata":{"execution":{"iopub.status.busy":"2022-09-13T13:59:28.939751Z","iopub.execute_input":"2022-09-13T13:59:28.940426Z","iopub.status.idle":"2022-09-13T14:10:36.129325Z","shell.execute_reply.started":"2022-09-13T13:59:28.940377Z","shell.execute_reply":"2022-09-13T14:10:36.128564Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pd.DataFrame(history.history).plot(figsize=(8,5))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-09-13T14:11:13.693924Z","iopub.execute_input":"2022-09-13T14:11:13.694243Z","iopub.status.idle":"2022-09-13T14:11:13.934686Z","shell.execute_reply.started":"2022-09-13T14:11:13.694207Z","shell.execute_reply":"2022-09-13T14:11:13.933730Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history['sparse_categorical_accuracy'])\nplt.plot(history.history['val_sparse_categorical_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend\nplt.show()\n\n\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-09-13T14:18:50.307872Z","iopub.execute_input":"2022-09-13T14:18:50.309066Z","iopub.status.idle":"2022-09-13T14:18:50.717747Z","shell.execute_reply.started":"2022-09-13T14:18:50.309012Z","shell.execute_reply":"2022-09-13T14:18:50.716838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}