{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":21154,"databundleVersionId":1243559,"sourceType":"competition"}],"dockerImageVersionId":30734,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install tfrecord","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-08-28T04:48:52.039539Z","iopub.execute_input":"2024-08-28T04:48:52.040332Z","iopub.status.idle":"2024-08-28T04:49:08.812990Z","shell.execute_reply.started":"2024-08-28T04:48:52.040300Z","shell.execute_reply":"2024-08-28T04:49:08.811908Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom kaggle_datasets import KaggleDatasets\nimport numpy as np\n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2024-08-28T04:49:08.815316Z","iopub.execute_input":"2024-08-28T04:49:08.815963Z","iopub.status.idle":"2024-08-28T04:49:22.640083Z","shell.execute_reply.started":"2024-08-28T04:49:08.815927Z","shell.execute_reply":"2024-08-28T04:49:22.639133Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2024-08-28T04:49:22.641973Z","iopub.execute_input":"2024-08-28T04:49:22.642740Z","iopub.status.idle":"2024-08-28T04:49:22.652426Z","shell.execute_reply.started":"2024-08-28T04:49:22.642704Z","shell.execute_reply":"2024-08-28T04:49:22.651392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\nIMAGE_SIZE = [192,192] # at this size, a GPU will run out of memory. Use the TPU\nEPOCHS = 10\nBATCH_SIZE = 16* strategy.num_replicas_in_sync\n\nNUM_TRAINING_IMAGES = 12753\nNUM_TEST_IMAGES = 7382\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE","metadata":{"execution":{"iopub.status.busy":"2024-08-28T04:49:27.656184Z","iopub.execute_input":"2024-08-28T04:49:27.656562Z","iopub.status.idle":"2024-08-28T04:49:28.058980Z","shell.execute_reply.started":"2024-08-28T04:49:27.656535Z","shell.execute_reply":"2024-08-28T04:49:28.058060Z"},"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) # 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)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef get_training_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/train/*.tfrec'), labeled=True)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset\n\ndef get_validation_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/val/*.tfrec'), labeled=True, ordered=False)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/test/*.tfrec'), labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset\n\ntraining_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()\ntest_dataset=get_test_dataset()","metadata":{"execution":{"iopub.status.busy":"2024-08-28T04:49:37.094184Z","iopub.execute_input":"2024-08-28T04:49:37.094868Z","iopub.status.idle":"2024-08-28T04:49:38.552291Z","shell.execute_reply.started":"2024-08-28T04:49:37.094837Z","shell.execute_reply":"2024-08-28T04:49:38.551459Z"},"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']\nimport matplotlib.pyplot as plt\n\n# Assuming you have a function to load and preprocess test images\ndef preprocess_image(image):\n    # Add any necessary preprocessing steps here\n    return image\n\n# Assuming `test_dataset` is a TensorFlow dataset\n# Iterate through the dataset to get a batch of images and labels\nfor images, labels in training_dataset.take(2):  # Take a batch of images and labels\n    # Preprocess the images\n    preprocessed_images = [preprocess_image(image) for image in images.numpy()]\n\n    # Display the images\n    plt.figure(figsize=(10, 10))\n    for i in range(8):  # Displaying 9 images\n        ax = plt.subplot(3, 3, i + 1)\n        plt.imshow(preprocessed_images[i])\n        plt.title(f\"lables: {CLASSES[labels[i].numpy()]}\")  # Assuming labels are available\n        plt.axis(\"off\")\n    \n    plt.tight_layout()\n    plt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-08-28T04:49:44.855841Z","iopub.execute_input":"2024-08-28T04:49:44.856191Z","iopub.status.idle":"2024-08-28T04:49:49.461286Z","shell.execute_reply.started":"2024-08-28T04:49:44.856161Z","shell.execute_reply":"2024-08-28T04:49:49.460231Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_augmentation = tf.keras.Sequential([\n    tf.keras.layers.RandomFlip('horizontal_and_vertical'),\n    tf.keras.layers.RandomRotation(0.2),\n    tf.keras.layers.RandomZoom(0.2),\n    tf.keras.layers.RandomContrast(0.2),\n])\n","metadata":{"execution":{"iopub.status.busy":"2024-08-28T01:18:00.731394Z","iopub.execute_input":"2024-08-28T01:18:00.731732Z","iopub.status.idle":"2024-08-28T01:18:00.779847Z","shell.execute_reply.started":"2024-08-28T01:18:00.731706Z","shell.execute_reply":"2024-08-28T01:18:00.778851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EPOCHS = 15\n\nwith strategy.scope():\n    pretrained_model = tf.keras.applications.DenseNet201(\n        weights='imagenet',\n        include_top=False ,\n        input_shape=[*IMAGE_SIZE, 3]\n    )\n    pretrained_model.trainable = True\n    \n    model = tf.keras.Sequential([\n        pretrained_model,\n        # ... attach a new head to act as a classifier.\n        tf.keras.layers.GlobalAveragePooling2D(),\n#         tf.keras.layers.Dense(480, activation = 'relu'),\n#         tf.keras.layers.Dense(240, activation = 'relu'),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n    \n    \n   ","metadata":{"execution":{"iopub.status.busy":"2024-08-28T04:49:56.978761Z","iopub.execute_input":"2024-08-28T04:49:56.979102Z","iopub.status.idle":"2024-08-28T04:50:01.685182Z","shell.execute_reply.started":"2024-08-28T04:49:56.979074Z","shell.execute_reply":"2024-08-28T04:50:01.684397Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def exponential_lr(epoch,\n                   start_lr = 0.00001, min_lr = 0.00001, max_lr = 0.00005,\n                   rampup_epochs = 5, sustain_epochs = 0,\n                   exp_decay = 0.8):\n\n    def lr(epoch, start_lr, min_lr, max_lr, rampup_epochs, sustain_epochs, exp_decay):\n        # linear increase from start to rampup_epochs\n        if epoch < rampup_epochs:\n            lr = ((max_lr - start_lr) /\n                  rampup_epochs * epoch + start_lr)\n        # constant max_lr during sustain_epochs\n        elif epoch < rampup_epochs + sustain_epochs:\n            lr = max_lr\n        # exponential decay towards min_lr\n        else:\n            lr = ((max_lr - min_lr) *\n                  exp_decay**(epoch - rampup_epochs - sustain_epochs) +\n                  min_lr)\n        return lr\n    return lr(epoch,\n              start_lr,\n              min_lr,\n              max_lr,\n              rampup_epochs,\n              sustain_epochs,\n              exp_decay)\n\nlr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr, verbose=True)\n\nrng = [i for i in range(EPOCHS)]\ny = [exponential_lr(x) for x in rng]\nplt.plot(rng, y)\nprint(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))","metadata":{"execution":{"iopub.status.busy":"2024-08-28T04:50:06.447640Z","iopub.execute_input":"2024-08-28T04:50:06.448230Z","iopub.status.idle":"2024-08-28T04:50:06.726519Z","shell.execute_reply.started":"2024-08-28T04:50:06.448198Z","shell.execute_reply":"2024-08-28T04:50:06.725556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(\n    optimizer=\"adam\",\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'],\n)\nSTEPS_PER_EPOCH= 12753  // BATCH_SIZE         ","metadata":{"execution":{"iopub.status.busy":"2024-08-28T04:50:14.138457Z","iopub.execute_input":"2024-08-28T04:50:14.139299Z","iopub.status.idle":"2024-08-28T04:50:14.157268Z","shell.execute_reply.started":"2024-08-28T04:50:14.139266Z","shell.execute_reply":"2024-08-28T04:50:14.156304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(\ntraining_dataset,\nvalidation_data=validation_dataset,\nepochs=EPOCHS,\nsteps_per_epoch=STEPS_PER_EPOCH,\ncallbacks=[lr_callback],\n)","metadata":{"execution":{"iopub.status.busy":"2024-08-28T04:50:24.680163Z","iopub.execute_input":"2024-08-28T04:50:24.680555Z","iopub.status.idle":"2024-08-28T05:37:57.242781Z","shell.execute_reply.started":"2024-08-28T04:50:24.680525Z","shell.execute_reply":"2024-08-28T05:37:57.241661Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save(\"best_model.keras\")","metadata":{"execution":{"iopub.status.busy":"2024-08-28T05:38:07.259224Z","iopub.execute_input":"2024-08-28T05:38:07.260059Z","iopub.status.idle":"2024-08-28T05:38:09.975328Z","shell.execute_reply.started":"2024-08-28T05:38:07.260025Z","shell.execute_reply":"2024-08-28T05:38:09.974472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(\nvalidation_dataset,\nepochs=EPOCHS,\nsteps_per_epoch=STEPS_PER_EPOCH,\ncallbacks=[lr_callback],\n)","metadata":{"execution":{"iopub.status.busy":"2024-08-28T05:38:26.240392Z","iopub.execute_input":"2024-08-28T05:38:26.240758Z","iopub.status.idle":"2024-08-28T05:49:36.273025Z","shell.execute_reply.started":"2024-08-28T05:38:26.240728Z","shell.execute_reply":"2024-08-28T05:49:36.272145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ntest_images_ds = test_dataset.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)","metadata":{"execution":{"iopub.status.busy":"2024-08-28T05:52:44.248402Z","iopub.execute_input":"2024-08-28T05:52:44.249090Z","iopub.status.idle":"2024-08-28T05:53:51.864986Z","shell.execute_reply.started":"2024-08-28T05:52:44.249058Z","shell.execute_reply":"2024-08-28T05:53:51.864051Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Generating submission.csv file...')\n\n# Get image ids from test set and convert to unicode\ntest_ids_ds = test_dataset.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\n# Write the submission file\nnp.savetxt(\n    'submission.csv',\n    np.rec.fromarrays([test_ids, predictions]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)\n\n# Look at the first few predictions\n!head submission.csv","metadata":{"execution":{"iopub.status.busy":"2024-08-28T05:55:37.621918Z","iopub.execute_input":"2024-08-28T05:55:37.622485Z","iopub.status.idle":"2024-08-28T05:55:45.355954Z","shell.execute_reply.started":"2024-08-28T05:55:37.622444Z","shell.execute_reply":"2024-08-28T05:55:45.354788Z"},"trusted":true},"execution_count":null,"outputs":[]}]}