{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.8.17","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"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\n# for 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","execution":{"iopub.status.busy":"2023-09-06T03:42:49.846863Z","iopub.execute_input":"2023-09-06T03:42:49.847235Z","iopub.status.idle":"2023-09-06T03:42:50.301191Z","shell.execute_reply.started":"2023-09-06T03:42:49.847205Z","shell.execute_reply":"2023-09-06T03:42:50.300222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nimport math, re, os\nimport numpy as np\n# import tensorflow as tf\nfrom kaggle_datasets import KaggleDatasets\n# import numpy as np\n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2023-09-06T03:42:56.426678Z","iopub.execute_input":"2023-09-06T03:42:56.427170Z","iopub.status.idle":"2023-09-06T03:43:36.340661Z","shell.execute_reply.started":"2023-09-06T03:42:56.427137Z","shell.execute_reply":"2023-09-06T03:43:36.339745Z"},"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    gpus = tf.config.experimental.list_physical_devices('GPU')\n    # print(gpus)\n    for gpu in gpus:\n        tf.config.experimental.set_memory_growth(gpu, True)\n        print(gpu)\n    if gpus:\n        strategy = tf.distribute.MirroredStrategy()\n    else:\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":"2023-09-06T03:43:36.342186Z","iopub.execute_input":"2023-09-06T03:43:36.342753Z","iopub.status.idle":"2023-09-06T03:43:45.224745Z","shell.execute_reply.started":"2023-09-06T03:43:36.342723Z","shell.execute_reply":"2023-09-06T03:43:45.223690Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"","metadata":{"execution":{"iopub.status.busy":"2023-09-06T03:43:45.225993Z","iopub.execute_input":"2023-09-06T03:43:45.226308Z","iopub.status.idle":"2023-09-06T03:43:45.231450Z","shell.execute_reply.started":"2023-09-06T03:43:45.226279Z","shell.execute_reply":"2023-09-06T03:43:45.230483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [224, 224] # at this size, a GPU will run out of memory. Use the TPU\nEPOCHS = 5\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\nAUTO = tf.data.experimental.AUTOTUNE","metadata":{"execution":{"iopub.status.busy":"2023-09-06T03:43:55.285920Z","iopub.execute_input":"2023-09-06T03:43:55.286941Z","iopub.status.idle":"2023-09-06T03:43:55.292666Z","shell.execute_reply.started":"2023-09-06T03:43:55.286895Z","shell.execute_reply":"2023-09-06T03:43:55.291618Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_DS_PATH","metadata":{"execution":{"iopub.status.busy":"2023-09-06T03:44:00.826995Z","iopub.execute_input":"2023-09-06T03:44:00.827432Z","iopub.status.idle":"2023-09-06T03:44:00.836900Z","shell.execute_reply.started":"2023-09-06T03:44:00.827401Z","shell.execute_reply":"2023-09-06T03:44:00.835542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nIMAGE_SIZE = [512, 512]\nGCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-512x512'\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']                                                                                                                                               # 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  # 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\n\n\n\n\ndef 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    angle = tf.random.uniform(shape=[], minval=0, maxval=4, dtype=tf.int32)\n    image = tf.image.rot90(image, k=angle)\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n    image = tf.image.random_brightness(image, max_delta=0.2)\n    image = tf.image.random_contrast(image, lower=0.5, upper=1.5)\n    image = tf.image.random_saturation(image, lower=0.5, upper=2)\n    image = tf.image.random_hue(image, max_delta=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))\n\n# 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\ntraining_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()\ntest_ds = get_test_dataset()\n\n# print(\"Training:\", training_dataset)\n# print (\"Validation:\", validation_dataset)\n# print(\"Test:\", test_ds)","metadata":{"execution":{"iopub.status.busy":"2023-09-06T03:44:03.632888Z","iopub.execute_input":"2023-09-06T03:44:03.633270Z","iopub.status.idle":"2023-09-06T03:44:04.219061Z","shell.execute_reply.started":"2023-09-06T03:44:03.633241Z","shell.execute_reply":"2023-09-06T03:44:04.218065Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import f1_score\n\n# import tensorflow as tf\n# import numpy as np\n\n# def macro_f1_score(y_true, y_pred):\n#     # Compute confusion matrix\n#     conf_matrix = tf.math.confusion_matrix(y_true, y_pred)\n#     diag = tf.linalg.diag_part(conf_matrix)\n    \n#     # Calculate precision and recall for each class\n#     precision = diag / tf.reduce_sum(conf_matrix, axis=0)\n#     recall = diag / tf.reduce_sum(conf_matrix, axis=1)\n    \n#     # Calculate F1 score for each class\n#     f1_scores = 2 * (precision * recall) / (precision + recall + tf.keras.backend.epsilon())\n    \n#     # Calculate macro F1 score\n#     macro_f1 = tf.reduce_mean(f1_scores)\n    \n#     return macro_f1\n\n#     return tf.py_function(f1_score(y_true, y_pred, average='macro'), tf.float32)\n\n\nlogdir = 'logs'\ntensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=logdir)\ncheckpoint = tf.keras.callbacks.ModelCheckpoint(\"effnet.h5\",monitor='val_sparse_categorical_accuracy', save_best_only=True,mode=\"auto\",verbose=1)\nreduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor = 'val_sparse_categorical_accuracy', factor = 0.3, patience = 2, min_delta = 0.001,mode='auto',verbose=1)\nearly_stopping = tf.keras.callbacks.EarlyStopping(\n    patience=8,\n    min_delta=0.001,\n    restore_best_weights=True,\n)","metadata":{"execution":{"iopub.status.busy":"2023-09-06T03:44:10.686749Z","iopub.execute_input":"2023-09-06T03:44:10.687158Z","iopub.status.idle":"2023-09-06T03:44:11.145391Z","shell.execute_reply.started":"2023-09-06T03:44:10.687118Z","shell.execute_reply":"2023-09-06T03:44:11.144359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nwith strategy.scope():    \n    pretrained_model = tf.keras.applications.EfficientNetB6(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n#     pretrained_model.trainable = False # tramsfer learning\n    \n    model = tf.keras.Sequential([\n#         tf.keras.layers.Dropout(0.1, input_shape=(*IMAGE_SIZE,3)),\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(700, activation='relu'),\n        tf.keras.layers.BatchNormalization(),\n        tf.keras.layers.Dropout(0.5),\n        tf.keras.layers.Dense(200, activation='relu'),\n        tf.keras.layers.BatchNormalization(),\n        #tf.keras.layers.Dropout(0.2),\n        #tf.keras.layers.Dense(256, activation='relu'),\n        tf.keras.layers.Dense(104, activation='softmax'),\n    ])\n        \n    model.compile(\n        optimizer='adam',\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy']\n    )\n#     model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=[f1_score(num_classes=104, average='macro')])\n\n\nhistory = model.fit(\n    training_dataset, \n    steps_per_epoch=STEPS_PER_EPOCH, \n    epochs=100, \n    validation_data=validation_dataset,\n    callbacks=[reduce_lr, early_stopping],\n)","metadata":{"execution":{"iopub.status.busy":"2023-09-06T03:47:29.648347Z","iopub.execute_input":"2023-09-06T03:47:29.648777Z","iopub.status.idle":"2023-09-06T04:22:38.220630Z","shell.execute_reply.started":"2023-09-06T03:47:29.648746Z","shell.execute_reply":"2023-09-06T04:22:38.218912Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# stop\n# hist = history\nimport matplotlib.pyplot as plt\nfig = plt.figure(figsize=(12,4))\nfor hist in [history]:\n    plt.subplot(1,2,1)\n    plt.plot(hist.history['loss'], color='teal', label='loss')\n    plt.plot(hist.history['val_loss'], color='orange', label='val_loss')\n    plt.title('Loss', fontsize=20)\n    plt.legend(loc=\"upper right\")\n    plt.grid(True)\n\n    plt.subplot(1,2,2)\n    plt.plot(hist.history['sparse_categorical_accuracy'], color='teal', label='sparse_categorical_accuracy')\n    plt.plot(hist.history['val_sparse_categorical_accuracy'], color='orange', label='val_sparse_categorical_accuracy')\n    plt.title('Accuracy', fontsize=20)\n    plt.legend(loc=\"upper left\")\n\n    plt.tight_layout()\n    plt.grid(True)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-06T04:23:45.737996Z","iopub.execute_input":"2023-09-06T04:23:45.739166Z","iopub.status.idle":"2023-09-06T04:23:49.356359Z","shell.execute_reply.started":"2023-09-06T04:23:45.739107Z","shell.execute_reply":"2023-09-06T04:23:49.355044Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# stop\n# hist = history\nimport matplotlib.pyplot as plt\nfig = plt.figure(figsize=(12,4))\nfor hist in [history]:\n    plt.subplot(1,2,1)\n    plt.plot(hist.history['loss'], color='teal', label='loss')\n    plt.plot(hist.history['val_loss'], color='orange', label='val_loss')\n    plt.title('Loss', fontsize=20)\n    plt.legend(loc=\"upper right\")\n    plt.grid(True)\n\n    plt.subplot(1,2,2)\n    plt.plot(hist.history['sparse_categorical_accuracy'], color='teal', label='sparse_categorical_accuracy')\n    plt.plot(hist.history['val_sparse_categorical_accuracy'], color='orange', label='val_sparse_categorical_accuracy')\n    plt.title('Accuracy', fontsize=20)\n    plt.legend(loc=\"upper left\")\n\n    plt.tight_layout()\n    plt.grid(True)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-05T18:40:39.791454Z","iopub.execute_input":"2023-09-05T18:40:39.791843Z","iopub.status.idle":"2023-09-05T18:40:40.379808Z","shell.execute_reply.started":"2023-09-05T18:40:39.791802Z","shell.execute_reply":"2023-09-05T18:40:40.378098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import f1_score\n\n# Define a function to compute F1 score\ndef calculate_f1_score(model, dataset):\n    true_labels = []\n    predicted_labels = []\n\n    for batch in dataset:\n        images, labels = batch\n        predictions = model.predict(images)\n        predicted_labels.extend(predictions.argmax(axis=1))\n        true_labels.extend(labels.numpy())\n\n    f1 = f1_score(true_labels, predicted_labels, average='macro')\n    return f1\n\n# Assuming you have a trained model 'model'\n# and the 'validation_dataset' is already defined\n\n# Calculate F1 score for the validation dataset\nf1_validation = calculate_f1_score(model, validation_dataset)\n\nprint(\"F1 Score for Validation Dataset:\", f1_validation)\n","metadata":{"execution":{"iopub.status.busy":"2023-09-06T04:24:48.004290Z","iopub.execute_input":"2023-09-06T04:24:48.005588Z","iopub.status.idle":"2023-09-06T04:25:37.495114Z","shell.execute_reply.started":"2023-09-06T04:24:48.005532Z","shell.execute_reply":"2023-09-06T04:25:37.493679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\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)\n\nprint('Generating submission.csv file...')\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') # all in one batch\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')","metadata":{"execution":{"iopub.status.busy":"2023-09-06T04:29:06.784461Z","iopub.execute_input":"2023-09-06T04:29:06.785662Z","iopub.status.idle":"2023-09-06T04:30:15.391898Z","shell.execute_reply.started":"2023-09-06T04:29:06.785591Z","shell.execute_reply":"2023-09-06T04:30:15.390554Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}],"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"}}