{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.15","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"tpu1vmV38","dataSources":[{"sourceId":21154,"databundleVersionId":1243559,"sourceType":"competition"}],"dockerImageVersionId":30786,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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 numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\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\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\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","trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:20.639619Z","iopub.execute_input":"2024-11-19T05:50:20.640530Z","iopub.status.idle":"2024-11-19T05:50:20.664904Z","shell.execute_reply.started":"2024-11-19T05:50:20.640475Z","shell.execute_reply":"2024-11-19T05:50:20.664003Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport math, os, re, random\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:20.666281Z","iopub.execute_input":"2024-11-19T05:50:20.666706Z","iopub.status.idle":"2024-11-19T05:50:20.670494Z","shell.execute_reply.started":"2024-11-19T05:50:20.666679Z","shell.execute_reply":"2024-11-19T05:50:20.669763Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom sklearn.metrics import*\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\nfrom sklearn.model_selection import KFold","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:20.671318Z","iopub.execute_input":"2024-11-19T05:50:20.671564Z","iopub.status.idle":"2024-11-19T05:50:20.680312Z","shell.execute_reply.started":"2024-11-19T05:50:20.671541Z","shell.execute_reply":"2024-11-19T05:50:20.679698Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import keras\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D, BatchNormalization\nfrom keras.utils import to_categorical","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:20.681604Z","iopub.execute_input":"2024-11-19T05:50:20.681875Z","iopub.status.idle":"2024-11-19T05:50:20.691168Z","shell.execute_reply.started":"2024-11-19T05:50:20.681849Z","shell.execute_reply":"2024-11-19T05:50:20.690447Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nimport tensorflow as tf, tensorflow.keras.backend as K\nfrom kaggle_datasets import KaggleDatasets\nprint('Tensorflow version ' + tf.__version__)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:20.798869Z","iopub.execute_input":"2024-11-19T05:50:20.799184Z","iopub.status.idle":"2024-11-19T05:50:20.803608Z","shell.execute_reply.started":"2024-11-19T05:50:20.799157Z","shell.execute_reply":"2024-11-19T05:50:20.802760Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE\n\n# Detect TPU, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver() \n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n    print(\"No TPU\")\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() ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:20.805905Z","iopub.execute_input":"2024-11-19T05:50:20.806181Z","iopub.status.idle":"2024-11-19T05:50:25.383139Z","shell.execute_reply.started":"2024-11-19T05:50:20.806155Z","shell.execute_reply":"2024-11-19T05:50:25.382355Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.384672Z","iopub.execute_input":"2024-11-19T05:50:25.384947Z","iopub.status.idle":"2024-11-19T05:50:25.389127Z","shell.execute_reply.started":"2024-11-19T05:50:25.384918Z","shell.execute_reply":"2024-11-19T05:50:25.388500Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\n\nIMAGE_SIZE = [192, 192]                   \nEPOCHS = 20\nBATCH_SIZE = 24 * strategy.num_replicas_in_sync\n\nSEED = 919\n\nGCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-192x192'\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') ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.390115Z","iopub.execute_input":"2024-11-19T05:50:25.390356Z","iopub.status.idle":"2024-11-19T05:50:25.421443Z","shell.execute_reply.started":"2024-11-19T05:50:25.390332Z","shell.execute_reply":"2024-11-19T05:50:25.420571Z"}},"outputs":[],"execution_count":null},{"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\n\nnp.set_printoptions(threshold=15, linewidth=80)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.423292Z","iopub.execute_input":"2024-11-19T05:50:25.423967Z","iopub.status.idle":"2024-11-19T05:50:25.431626Z","shell.execute_reply.started":"2024-11-19T05:50:25.423936Z","shell.execute_reply":"2024-11-19T05:50:25.430797Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def batch_to_numpy_images_and_labels(data):\n    images, labels = data\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()\n    if numpy_labels.dtype == object: # binary string in this case, these are image ID strings\n        numpy_labels = [None for _ in enumerate(numpy_images)]\n    # If no labels, only image IDs, return None for labels (this is the case for test data)\n    return numpy_images, numpy_labels","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.432456Z","iopub.execute_input":"2024-11-19T05:50:25.432736Z","iopub.status.idle":"2024-11-19T05:50:25.448521Z","shell.execute_reply.started":"2024-11-19T05:50:25.432710Z","shell.execute_reply":"2024-11-19T05:50:25.447832Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def title_from_label_and_target(label, correct_label):\n    if correct_label is None:\n        return CLASSES[label], True\n    correct = (label == correct_label)\n    return \"{} [{}{}{}]\".format(CLASSES[label], 'OK' if correct else 'NO', u\"\\u2192\" if not correct else '',\n                                CLASSES[correct_label] if not correct else ''), correct","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.449357Z","iopub.execute_input":"2024-11-19T05:50:25.449615Z","iopub.status.idle":"2024-11-19T05:50:25.470376Z","shell.execute_reply.started":"2024-11-19T05:50:25.449590Z","shell.execute_reply":"2024-11-19T05:50:25.469674Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def display_one_flower(image, title, subplot, red=False, titlesize=16):\n    plt.subplot(*subplot)\n    plt.axis('off')\n    plt.imshow(image)\n    if len(title) > 0:\n        plt.title(title, fontsize=int(titlesize) if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))\n    return (subplot[0], subplot[1], subplot[2]+1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.471253Z","iopub.execute_input":"2024-11-19T05:50:25.471513Z","iopub.status.idle":"2024-11-19T05:50:25.491882Z","shell.execute_reply.started":"2024-11-19T05:50:25.471480Z","shell.execute_reply":"2024-11-19T05:50:25.491174Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def display_batch_of_images(databatch, predictions=None):\n    images, labels = batch_to_numpy_images_and_labels(databatch)\n    if labels is None:\n        labels = [None for _ in images]\n        \n    # Auto-squaring: ensures images fit into a square or rectangular grid\n    rows = int(math.sqrt(len(images)))\n    cols = len(images) // rows\n        \n    # Set figure size and spacing\n    FIGSIZE = 13.0\n    SPACING = 0.1\n    subplot = (rows, cols, 1)\n    \n    if rows < cols:\n        plt.figure(figsize=(FIGSIZE, FIGSIZE / cols * rows))\n    else:\n        plt.figure(figsize=(FIGSIZE / rows * cols, FIGSIZE))\n    \n    for i, (image, label) in enumerate(zip(images[:rows*cols], labels[:rows*cols])):\n        title = '' if label is None else CLASSES[label]\n        correct = True\n\n        if predictions is not None:\n            title, correct = title_from_label_and_target(predictions[i], label)\n            dynamic_titlesize = FIGSIZE * SPACING / max(rows, cols) * 40 + 3  # Dynamically adjust title size\n            subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)\n        else:\n            subplot = display_one_flower(image, title, subplot, not correct)\n    \n    plt.tight_layout()\n\n    # Adjust spacing only if predictions or labels are not provided\n    if labels[0] is None and predictions is None:\n        plt.subplots_adjust(wspace=0, hspace=0)\n    else:\n        plt.subplots_adjust(wspace=SPACING, hspace=SPACING)\n\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.492791Z","iopub.execute_input":"2024-11-19T05:50:25.493024Z","iopub.status.idle":"2024-11-19T05:50:25.509130Z","shell.execute_reply.started":"2024-11-19T05:50:25.493001Z","shell.execute_reply":"2024-11-19T05:50:25.508395Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def display_confusion_matrix(cmat, score, precision, recall):\n    plt.figure(figsize=(15,15))\n    ax = plt.gca()\n    ax.matshow(cmat, cmap='Reds')\n    ax.set_xticks(range(len(CLASSES)))\n    ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})\n    plt.setp(ax.get_xticklabels(), rotation=45, ha=\"left\", rotation_mode=\"anchor\")\n    ax.set_yticks(range(len(CLASSES)))\n    ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})\n    plt.setp(ax.get_yticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n    titlestring = \"\"\n    if score is not None:\n        titlestring += 'f1 = {:.3f} '.format(score)\n    if precision is not None:\n        titlestring += '\\nprecision = {:.3f} '.format(precision)\n    if recall is not None:\n        titlestring += '\\nrecall = {:.3f} '.format(recall)\n    if len(titlestring) > 0:\n        ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'#804040'})\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.510008Z","iopub.execute_input":"2024-11-19T05:50:25.510230Z","iopub.status.idle":"2024-11-19T05:50:25.524638Z","shell.execute_reply.started":"2024-11-19T05:50:25.510207Z","shell.execute_reply":"2024-11-19T05:50:25.523860Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def display_training_curves(training, validation, title, subplot):\n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    #ax.set_ylim(0.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.527334Z","iopub.execute_input":"2024-11-19T05:50:25.527718Z","iopub.status.idle":"2024-11-19T05:50:25.539544Z","shell.execute_reply.started":"2024-11-19T05:50:25.527689Z","shell.execute_reply":"2024-11-19T05:50:25.538646Z"}},"outputs":[],"execution_count":null},{"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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.540636Z","iopub.execute_input":"2024-11-19T05:50:25.540895Z","iopub.status.idle":"2024-11-19T05:50:25.550476Z","shell.execute_reply.started":"2024-11-19T05:50:25.540870Z","shell.execute_reply":"2024-11-19T05:50:25.549698Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def 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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.551726Z","iopub.execute_input":"2024-11-19T05:50:25.551962Z","iopub.status.idle":"2024-11-19T05:50:25.560378Z","shell.execute_reply.started":"2024-11-19T05:50:25.551939Z","shell.execute_reply":"2024-11-19T05:50:25.559641Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def 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),  \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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.561269Z","iopub.execute_input":"2024-11-19T05:50:25.561504Z","iopub.status.idle":"2024-11-19T05:50:25.573849Z","shell.execute_reply.started":"2024-11-19T05:50:25.561475Z","shell.execute_reply":"2024-11-19T05:50:25.573030Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def 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=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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.575027Z","iopub.execute_input":"2024-11-19T05:50:25.575541Z","iopub.status.idle":"2024-11-19T05:50:25.584995Z","shell.execute_reply.started":"2024-11-19T05:50:25.575512Z","shell.execute_reply":"2024-11-19T05:50:25.584045Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def data_augment(image, label):\n    # data augmentation. Thanks to the dataset.prefetch(AUTO) statement in the next function (below),\n    # this happens essentially for free on TPU. Data pipeline code is executed on the \"CPU\" part\n    # 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 ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.586069Z","iopub.execute_input":"2024-11-19T05:50:25.586342Z","iopub.status.idle":"2024-11-19T05:50:25.594882Z","shell.execute_reply.started":"2024-11-19T05:50:25.586314Z","shell.execute_reply":"2024-11-19T05:50:25.594115Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_training_dataset(dataset,do_aug=True):\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    if do_aug: dataset = dataset.map(transform, 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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.595849Z","iopub.execute_input":"2024-11-19T05:50:25.596149Z","iopub.status.idle":"2024-11-19T05:50:25.611053Z","shell.execute_reply.started":"2024-11-19T05:50:25.596123Z","shell.execute_reply":"2024-11-19T05:50:25.610392Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_validation_dataset(dataset):\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.611889Z","iopub.execute_input":"2024-11-19T05:50:25.612127Z","iopub.status.idle":"2024-11-19T05:50:25.622104Z","shell.execute_reply.started":"2024-11-19T05:50:25.612102Z","shell.execute_reply":"2024-11-19T05:50:25.621427Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def 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) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.622965Z","iopub.execute_input":"2024-11-19T05:50:25.623211Z","iopub.status.idle":"2024-11-19T05:50:25.632399Z","shell.execute_reply.started":"2024-11-19T05:50:25.623186Z","shell.execute_reply":"2024-11-19T05:50:25.631796Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec 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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.633271Z","iopub.execute_input":"2024-11-19T05:50:25.633583Z","iopub.status.idle":"2024-11-19T05:50:25.643123Z","shell.execute_reply.started":"2024-11-19T05:50:25.633556Z","shell.execute_reply":"2024-11-19T05:50:25.642477Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint(\"BATCH_SIZE\", BATCH_SIZE)\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.643944Z","iopub.execute_input":"2024-11-19T05:50:25.644185Z","iopub.status.idle":"2024-11-19T05:50:25.653801Z","shell.execute_reply.started":"2024-11-19T05:50:25.644160Z","shell.execute_reply":"2024-11-19T05:50:25.653113Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def display_one_flower(image, title, subplot, red=False, titlesize=16):\n    plt.subplot(*subplot)\n    plt.axis('off')\n    plt.imshow(image)\n    if len(title) > 0:\n        plt.title(title, fontsize=int(titlesize) if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))\n    return (subplot[0], subplot[1], subplot[2]+1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.654698Z","iopub.execute_input":"2024-11-19T05:50:25.654956Z","iopub.status.idle":"2024-11-19T05:50:25.667856Z","shell.execute_reply.started":"2024-11-19T05:50:25.654930Z","shell.execute_reply":"2024-11-19T05:50:25.667238Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"LR_START = 0.00001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 5\nLR_SUSTAIN_EPOCHS = 0\nLR_EXP_DECAY = .8","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.668751Z","iopub.execute_input":"2024-11-19T05:50:25.668973Z","iopub.status.idle":"2024-11-19T05:50:25.677453Z","shell.execute_reply.started":"2024-11-19T05:50:25.668951Z","shell.execute_reply":"2024-11-19T05:50:25.676845Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def lrfn(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr = (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * epoch + LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n    return lr\n    \nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)\n\nrng = [i for i in range(25 if EPOCHS<25 else EPOCHS)]\ny = [lrfn(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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.678321Z","iopub.execute_input":"2024-11-19T05:50:25.678621Z","iopub.status.idle":"2024-11-19T05:50:25.820134Z","shell.execute_reply.started":"2024-11-19T05:50:25.678597Z","shell.execute_reply":"2024-11-19T05:50:25.819495Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(12, 6))\nplt.bar(rng, y, color=\"teal\", width=0.6)\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Learning Rate\")\nplt.title(\"Learning Rate per Epoch\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:25.820911Z","iopub.execute_input":"2024-11-19T05:50:25.821160Z","iopub.status.idle":"2024-11-19T05:50:26.004085Z","shell.execute_reply.started":"2024-11-19T05:50:25.821136Z","shell.execute_reply":"2024-11-19T05:50:26.003198Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):\n    # returns 3x3 transformmatrix which transforms indicies\n        \n    # CONVERT DEGREES TO RADIANS\n    rotation = math.pi * rotation / 180.\n    shear = math.pi * shear / 180.\n    \n    # ROTATION MATRIX\n    c1 = tf.math.cos(rotation)\n    s1 = tf.math.sin(rotation)\n    one = tf.constant([1],dtype='float32')\n    zero = tf.constant([0],dtype='float32')\n    rotation_matrix = tf.reshape( tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3] )\n     # SHEAR MATRIX\n    c2 = tf.math.cos(shear)\n    s2 = tf.math.sin(shear)\n    shear_matrix = tf.reshape( tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3] )    \n     # ZOOM MATRIX\n    zoom_matrix = tf.reshape( tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3] )\n    \n    # SHIFT MATRIX\n    shift_matrix = tf.reshape( tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3] )\n    \n    return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:26.005139Z","iopub.execute_input":"2024-11-19T05:50:26.005448Z","iopub.status.idle":"2024-11-19T05:50:26.012899Z","shell.execute_reply.started":"2024-11-19T05:50:26.005416Z","shell.execute_reply":"2024-11-19T05:50:26.012136Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def transform(image,label):\n    DIM = IMAGE_SIZE[0]\n    XDIM = DIM%2 #fix for size 331\n    \n    rot = 15. * tf.random.normal([1],dtype='float32')\n    shr = 5. * tf.random.normal([1],dtype='float32') \n    h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.\n    w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.\n    h_shift = 16. * tf.random.normal([1],dtype='float32') \n    w_shift = 16. * tf.random.normal([1],dtype='float32') \n    m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift) \n    x = tf.repeat( tf.range(DIM//2,-DIM//2,-1), DIM )\n    y = tf.tile( tf.range(-DIM//2,DIM//2),[DIM] )\n    z = tf.ones([DIM*DIM],dtype='int32')\n    idx = tf.stack( [x,y,z] )\n    # ROTATE DESTINATION PIXELS ONTO ORIGIN PIXELS\n    idx2 = K.dot(m,tf.cast(idx,dtype='float32'))\n    idx2 = K.cast(idx2,dtype='int32')\n    idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)\n    # FIND ORIGIN PIXEL VALUES           \n    idx3 = tf.stack( [DIM//2-idx2[0,], DIM//2-1+idx2[1,]] )\n    d = tf.gather_nd(image,tf.transpose(idx3))   \n    return tf.reshape(d,[DIM,DIM,3]),label","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:26.013837Z","iopub.execute_input":"2024-11-19T05:50:26.014115Z","iopub.status.idle":"2024-11-19T05:50:26.030013Z","shell.execute_reply.started":"2024-11-19T05:50:26.014087Z","shell.execute_reply":"2024-11-19T05:50:26.029496Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"row = 3; col = 4;\nall_elements = get_training_dataset(load_dataset(TRAINING_FILENAMES),do_aug=False).unbatch()\none_element = tf.data.Dataset.from_tensors( next(iter(all_elements)) )\naugmented_element = one_element.repeat().map(transform).batch(row*col)\n\nfor (img,label) in augmented_element:\n    plt.figure(figsize=(15,int(15*row/col)))\n    for j in range(row*col):\n        plt.subplot(row,col,j+1)\n        plt.axis('off')\n        plt.imshow(img[j,])\n    plt.show()\n    break","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:26.030732Z","iopub.execute_input":"2024-11-19T05:50:26.030946Z","iopub.status.idle":"2024-11-19T05:50:27.744731Z","shell.execute_reply.started":"2024-11-19T05:50:26.030925Z","shell.execute_reply":"2024-11-19T05:50:27.743782Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications import DenseNet201","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:27.749045Z","iopub.execute_input":"2024-11-19T05:50:27.749421Z","iopub.status.idle":"2024-11-19T05:50:27.753236Z","shell.execute_reply.started":"2024-11-19T05:50:27.749389Z","shell.execute_reply":"2024-11-19T05:50:27.752505Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_model():\n    with strategy.scope():\n        rnet = DenseNet201(\n            input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),\n            weights='imagenet',\n            include_top=False\n        )\n        # trainable rnet\n        rnet.trainable = True\n        model = tf.keras.Sequential([\n            rnet,\n            tf.keras.layers.GlobalAveragePooling2D(),\n            tf.keras.layers.Dense(len(CLASSES), activation='softmax',dtype='float32')\n        ])\n    model.compile(\n        optimizer='adam',\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy']\n    )\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:27.754077Z","iopub.execute_input":"2024-11-19T05:50:27.754335Z","iopub.status.idle":"2024-11-19T05:50:27.767060Z","shell.execute_reply.started":"2024-11-19T05:50:27.754308Z","shell.execute_reply":"2024-11-19T05:50:27.766385Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def train_cross_validate(folds = 5):\n    histories = []\n    models = []\n    early_stopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_loss', patience = 3)\n    kfold = KFold(folds, shuffle = True, random_state = SEED)\n    for f, (trn_ind, val_ind) in enumerate(kfold.split(TRAINING_FILENAMES)):\n        print(); print('#'*25)\n        print('### FOLD',f+1)\n        print('#'*25)\n        train_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES}).loc[trn_ind]['TRAINING_FILENAMES']), labeled = True)\n        val_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES}).loc[val_ind]['TRAINING_FILENAMES']), labeled = True, ordered = True)\n        model = get_model()\n        history = model.fit(\n            get_training_dataset(train_dataset), \n            steps_per_epoch = STEPS_PER_EPOCH,\n            epochs = EPOCHS,\n            callbacks = [lr_callback],#, early_stopping],\n            validation_data = get_validation_dataset(val_dataset),\n            verbose=2\n        )\n        models.append(model)\n        histories.append(history)\n    return histories, models","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:27.767948Z","iopub.execute_input":"2024-11-19T05:50:27.768197Z","iopub.status.idle":"2024-11-19T05:50:27.781290Z","shell.execute_reply.started":"2024-11-19T05:50:27.768172Z","shell.execute_reply":"2024-11-19T05:50:27.780638Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"EPOCHS = 12\nwith strategy.scope():\n    pretrained_model = tf.keras.applications.VGG16(\n        weights='imagenet',\n        include_top = False,\n        input_shape = [*IMAGE_SIZE, 3],\n    )\n    pretrained_model.trainable = False\n    \n    model = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:27.782123Z","iopub.execute_input":"2024-11-19T05:50:27.782452Z","iopub.status.idle":"2024-11-19T05:50:29.065706Z","shell.execute_reply.started":"2024-11-19T05:50:27.782425Z","shell.execute_reply":"2024-11-19T05:50:29.064699Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(\n    optimizer='adam',\n    loss='sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'])\n\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:29.066917Z","iopub.execute_input":"2024-11-19T05:50:29.067174Z","iopub.status.idle":"2024-11-19T05:50:29.089861Z","shell.execute_reply.started":"2024-11-19T05:50:29.067148Z","shell.execute_reply":"2024-11-19T05:50:29.089007Z"}},"outputs":[],"execution_count":null},{"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(\"Learned Schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-19T05:50:29.090850Z","iopub.execute_input":"2024-11-19T05:50:29.091112Z","iopub.status.idle":"2024-11-19T05:50:29.236098Z","shell.execute_reply.started":"2024-11-19T05:50:29.091086Z","shell.execute_reply":"2024-11-19T05:50:29.235200Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}