{"metadata":{"colab":{"provenance":[],"machine_shape":"hm","gpuType":"T4","authorship_tag":"ABX9TyM1pJ60BMiQpqlb+uuPlK2+"},"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"accelerator":"GPU","kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":21154,"databundleVersionId":1243559,"sourceType":"competition"}],"dockerImageVersionId":30787,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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":{"id":"YLAQCywZMymd","executionInfo":{"status":"ok","timestamp":1729960516159,"user_tz":420,"elapsed":3672,"user":{"displayName":"Jesus Deleon","userId":"05916505576821218581"}},"execution":{"iopub.status.busy":"2024-10-26T21:20:41.200287Z","iopub.execute_input":"2024-10-26T21:20:41.200577Z","iopub.status.idle":"2024-10-26T21:20:42.355165Z","shell.execute_reply.started":"2024-10-26T21:20:41.200544Z","shell.execute_reply":"2024-10-26T21:20:42.353779Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for dirpath, dirnames, filenames in os.walk(\"/content/train\"):\n  print(f\"There are {len(dirnames)} directories and {len(filenames)} images in '{dirpath}'.\")","metadata":{"id":"D9Ce-TSHRb2t","executionInfo":{"status":"ok","timestamp":1729960524782,"user_tz":420,"elapsed":636,"user":{"displayName":"Jesus Deleon","userId":"05916505576821218581"}},"outputId":"deb0555b-f0cc-4ad6-d6a0-1e4f142bf6f8"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div style = \"background-color: #dfe6e3; font-size:150%; text-align:left; border: 7px solid #04690e; text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);font-family : arial ; border-radius : 20px 20px 20px 20px; padding: 10px; width:95%\">\n    \n<h1 align=\"center\"><font color=#101210><strong>Load the Data and Create Labels<strong></font></h1>","metadata":{"id":"5PKEh2zhr51M"}},{"cell_type":"code","source":"import tensorflow as tf\n\nIMAGE_SIZE = [224, 224]\nAUTO = tf.data.experimental.AUTOTUNE\nTRAINING_FILENAMES = tf.io.gfile.glob('/kaggle/input/tpu-getting-started/tfrecords-jpeg-224x224/train/*.tfrec')\nVALIDATION_FILENAMES = tf.io.gfile.glob('/kaggle/input/tpu-getting-started/tfrecords-jpeg-224x224/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob('/kaggle/input/tpu-getting-started/tfrecords-jpeg-224x224/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']                                                                                                                                               # 100 - 102\n\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\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"class\": tf.io.FixedLenFeature([], tf.int64),\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\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\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\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)\n    dataset = dataset.with_options(ignore_order)\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    return dataset","metadata":{"id":"aBrC6prlW0wn","executionInfo":{"status":"ok","timestamp":1729960562969,"user_tz":420,"elapsed":3478,"user":{"displayName":"Jesus Deleon","userId":"05916505576821218581"}}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div style = \"background-color: #dfe6e3; font-size:150%; text-align:left; border: 7px solid #04690e; text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);font-family : arial ; border-radius : 20px 20px 20px 20px; padding: 10px; width:95%\">\n    \n<h1 align=\"center\"><font color=#101210><strong>Create Data augmentation and Datasets<strong></font></h1>","metadata":{"id":"C5WnX4ACsRwv"}},{"cell_type":"code","source":"import math, re, os\nimport numpy as np\nimport pandas as pd\n\ndef data_augment(image, label):\n    image = tf.image.random_flip_up_down(image)\n    image = tf.image.random_hue(image, 0,0.5)\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()\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)\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\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":{"id":"21clMwhhsNtt","executionInfo":{"status":"ok","timestamp":1729963998052,"user_tz":420,"elapsed":726,"user":{"displayName":"Jesus Deleon","userId":"05916505576821218581"}},"outputId":"dbfeb8f3-2913-443f-d4fe-05c6aaf82713"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"strategy = tf.distribute.get_strategy()\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)\n","metadata":{"id":"u7-oMfJOTF-e","executionInfo":{"status":"ok","timestamp":1729964005629,"user_tz":420,"elapsed":622,"user":{"displayName":"Jesus Deleon","userId":"05916505576821218581"}},"outputId":"9f0bccef-0367-41d5-a2d4-38f03513a675"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.set_printoptions(threshold=15, linewidth=80)\n\nprint(\"Training shapes:\")\nfor image, label in ds_train.take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Training label examples:\", label.numpy())","metadata":{"id":"89qM1BqUZLNw","executionInfo":{"status":"ok","timestamp":1729964011378,"user_tz":420,"elapsed":1360,"user":{"displayName":"Jesus Deleon","userId":"05916505576821218581"}},"outputId":"7213be85-6ef1-4c9b-93d5-65c418a465d4"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from matplotlib import pyplot as plt\n\ndef 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:\n\n        numpy_labels = [None for _ in enumerate(numpy_images)]\n    return numpy_images, numpy_labels\n\ndef 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\n\ndef 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)\n\n\ndef display_batch_of_images(databatch, predictions=None):\n\n    # data\n    images, labels = batch_to_numpy_images_and_labels(databatch)\n    if labels is None:\n        labels = [None for _ in enumerate(images)]\n\n    rows = int(math.sqrt(len(images)))\n    cols = len(images)//rows\n\n    # size and spacing\n    FIGSIZE = 13.0\n    SPACING = 0.1\n    subplot=(rows,cols,1)\n    if rows < cols:\n        plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))\n    else:\n        plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))\n\n    # display\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        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\n        subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)\n\n    #layout\n    plt.tight_layout()\n    if label 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    plt.show()\n\n\ndef display_training_curves(training, validation, title, subplot):\n    if subplot%10==1:\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_xlabel('epoch')\n    ax.legend(['train', 'valid.'])","metadata":{"id":"FEvw2beVbc3o","executionInfo":{"status":"ok","timestamp":1729962100752,"user_tz":420,"elapsed":757,"user":{"displayName":"Jesus Deleon","userId":"05916505576821218581"}}},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds_iter = iter(ds_train.unbatch().batch(3))\n","metadata":{"id":"nxuit3Jogpyb","executionInfo":{"status":"ok","timestamp":1729962068395,"user_tz":420,"elapsed":331,"user":{"displayName":"Jesus Deleon","userId":"05916505576821218581"}}},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"one_batch = next(ds_iter)\ndisplay_batch_of_images(one_batch)","metadata":{"id":"7yK1Z4hegula","executionInfo":{"status":"ok","timestamp":1729962108085,"user_tz":420,"elapsed":3466,"user":{"displayName":"Jesus Deleon","userId":"05916505576821218581"}},"outputId":"b602a813-629b-42f3-d22f-c9a137dfc52e"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div style = \"background-color: #dfe6e3; font-size:150%; text-align:left; border: 7px solid #04690e; text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);font-family : arial ; border-radius : 20px 20px 20px 20px; padding: 10px; width:95%\">\n    \n<h1 align=\"center\"><font color=#101210><strong>Building Transfer Learn Model<strong></font></h1>","metadata":{"id":"9heiBvmb5Jgm"}},{"cell_type":"code","source":"from tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras.layers import Input\n\nEPOCHS = 12\ninput_shape=(224,224,3)\n\nmodel = tf.keras.models.Sequential([\n  Input(shape=input_shape),\n  MobileNetV2(weights=\"imagenet\", include_top=False, input_shape=(input_shape)),\n  tf.keras.layers.Conv2D(160, (3, 3), padding='same',activation='relu'),\n  tf.keras.layers.MaxPooling2D(2,2),\n  tf.keras.layers.BatchNormalization(),\n  tf.keras.layers.Flatten(),\n  tf.keras.layers.Dense(512, activation='relu'),\n  tf.keras.layers.Dense(256, activation='relu'),\n  tf.keras.layers.Dense(104, activation='softmax'),\n\n])\n\nmodel.layers[0].trainable = False","metadata":{"id":"hD8f1X0F5FH3","executionInfo":{"status":"ok","timestamp":1729965110412,"user_tz":420,"elapsed":1326,"user":{"displayName":"Jesus Deleon","userId":"05916505576821218581"}}},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'],\n)\n\nmodel.summary()","metadata":{"id":"m10IDKEOcks-","executionInfo":{"status":"ok","timestamp":1729965114626,"user_tz":420,"elapsed":617,"user":{"displayName":"Jesus Deleon","userId":"05916505576821218581"}},"outputId":"3dd0b913-6108-4a22-f838-4a4f5ea5fc6f"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EPOCHS = 30\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\nhistory = model.fit(\n      ds_train,\n      steps_per_epoch=STEPS_PER_EPOCH,\n      epochs=EPOCHS,\n      validation_data=ds_valid,\n      validation_steps=25,\n      verbose=2,\n      callbacks = [tf.keras.callbacks.EarlyStopping(monitor='val_sparse_categorical_accuracy', patience=10, verbose=1, restore_best_weights=True),\n                   tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', patience=5, verbose=1)])","metadata":{"id":"ZaJiUr57ctcA","executionInfo":{"status":"ok","timestamp":1729965569379,"user_tz":420,"elapsed":435105,"user":{"displayName":"Jesus Deleon","userId":"05916505576821218581"}},"outputId":"cfc2a040-b18d-4c15-82fb-e6790da8f9bd"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)","metadata":{"id":"6Ypq5fsrll-d","executionInfo":{"status":"ok","timestamp":1729965772237,"user_tz":420,"elapsed":12728,"user":{"displayName":"Jesus Deleon","userId":"05916505576821218581"}},"outputId":"26d0ba3b-db5a-47e4-cc1a-b2dac6d94f88"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('submission.csv')\n\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\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!head submission.csv\n","metadata":{"id":"zVwwnzCWIIOB","executionInfo":{"status":"ok","timestamp":1729965777875,"user_tz":420,"elapsed":1549,"user":{"displayName":"Jesus Deleon","userId":"05916505576821218581"}},"outputId":"5760db35-c709-448b-9d5b-5b6826a6ca87"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"id":"UIu5gfH2IepP"},"execution_count":null,"outputs":[]}]}