{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"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"},"kaggle":{"accelerator":"none","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":"markdown","source":"# 1. Loading Data","metadata":{}},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-09T09:30:49.630318Z","iopub.execute_input":"2024-11-09T09:30:49.630778Z","iopub.status.idle":"2024-11-09T09:30:49.669706Z","shell.execute_reply.started":"2024-11-09T09:30:49.630736Z","shell.execute_reply":"2024-11-09T09:30:49.668465Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-09T09:30:49.671658Z","iopub.execute_input":"2024-11-09T09:30:49.672014Z","iopub.status.idle":"2024-11-09T09:30:49.677016Z","shell.execute_reply.started":"2024-11-09T09:30:49.671978Z","shell.execute_reply":"2024-11-09T09:30:49.675897Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 2. Create Labels","metadata":{}},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-09T09:30:49.678647Z","iopub.execute_input":"2024-11-09T09:30:49.679355Z","iopub.status.idle":"2024-11-09T09:30:49.723228Z","shell.execute_reply.started":"2024-11-09T09:30:49.679305Z","shell.execute_reply":"2024-11-09T09:30:49.722014Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 3. Data Augumentation","metadata":{}},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-09T09:30:49.724703Z","iopub.execute_input":"2024-11-09T09:30:49.725156Z","iopub.status.idle":"2024-11-09T09:30:49.737425Z","shell.execute_reply.started":"2024-11-09T09:30:49.725110Z","shell.execute_reply":"2024-11-09T09:30:49.736246Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-09T09:30:49.740055Z","iopub.execute_input":"2024-11-09T09:30:49.740482Z","iopub.status.idle":"2024-11-09T09:30:49.961765Z","shell.execute_reply.started":"2024-11-09T09:30:49.740442Z","shell.execute_reply":"2024-11-09T09:30:49.960520Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-09T09:30:49.963481Z","iopub.execute_input":"2024-11-09T09:30:49.963997Z","iopub.status.idle":"2024-11-09T09:30:52.595709Z","shell.execute_reply.started":"2024-11-09T09:30:49.963937Z","shell.execute_reply":"2024-11-09T09:30:52.594444Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-09T09:30:52.596809Z","iopub.execute_input":"2024-11-09T09:30:52.597162Z","iopub.status.idle":"2024-11-09T09:30:52.615461Z","shell.execute_reply.started":"2024-11-09T09:30:52.597119Z","shell.execute_reply":"2024-11-09T09:30:52.614412Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ds_iter = iter(ds_train.unbatch().batch(3))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-09T09:30:52.616998Z","iopub.execute_input":"2024-11-09T09:30:52.617496Z","iopub.status.idle":"2024-11-09T09:30:52.759933Z","shell.execute_reply.started":"2024-11-09T09:30:52.617444Z","shell.execute_reply":"2024-11-09T09:30:52.758746Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"one_batch = next(ds_iter)\ndisplay_batch_of_images(one_batch)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-09T09:30:52.761494Z","iopub.execute_input":"2024-11-09T09:30:52.761918Z","iopub.status.idle":"2024-11-09T09:30:55.680810Z","shell.execute_reply.started":"2024-11-09T09:30:52.761878Z","shell.execute_reply":"2024-11-09T09:30:55.679451Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 4. Building Transfer Model","metadata":{}},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-09T09:30:55.682358Z","iopub.execute_input":"2024-11-09T09:30:55.682796Z","iopub.status.idle":"2024-11-09T09:30:56.527212Z","shell.execute_reply.started":"2024-11-09T09:30:55.682753Z","shell.execute_reply":"2024-11-09T09:30:56.526079Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'],\n)\n\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-09T09:30:56.528922Z","iopub.execute_input":"2024-11-09T09:30:56.529574Z","iopub.status.idle":"2024-11-09T09:30:56.568167Z","shell.execute_reply.started":"2024-11-09T09:30:56.529502Z","shell.execute_reply":"2024-11-09T09:30:56.567180Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"EPOCHS = 15\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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-09T09:30:56.569776Z","iopub.execute_input":"2024-11-09T09:30:56.570744Z","iopub.status.idle":"2024-11-09T10:45:46.411912Z","shell.execute_reply.started":"2024-11-09T09:30:56.570690Z","shell.execute_reply":"2024-11-09T10:45:46.410630Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-09T10:45:46.413754Z","iopub.execute_input":"2024-11-09T10:45:46.414208Z","iopub.status.idle":"2024-11-09T10:48:14.833436Z","shell.execute_reply.started":"2024-11-09T10:45:46.414165Z","shell.execute_reply":"2024-11-09T10:48:14.828508Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 5. Submission","metadata":{}},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-09T10:48:14.837493Z","iopub.execute_input":"2024-11-09T10:48:14.837919Z","iopub.status.idle":"2024-11-09T10:48:19.626022Z","shell.execute_reply.started":"2024-11-09T10:48:14.837880Z","shell.execute_reply":"2024-11-09T10:48:19.624734Z"}},"outputs":[],"execution_count":null}]}