{"metadata":{"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"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import re\nimport os\nimport pprint\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2022-11-29T22:41:20.674956Z","iopub.execute_input":"2022-11-29T22:41:20.675263Z","iopub.status.idle":"2022-11-29T22:41:27.593667Z","shell.execute_reply.started":"2022-11-29T22:41:20.675232Z","shell.execute_reply":"2022-11-29T22:41:27.592782Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pp = pprint.PrettyPrinter(indent=4) # Set Pretty Print Indentation\nprint(tf.__version__) # Check the version of tensorflow used\n\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2022-11-29T22:41:27.595115Z","iopub.execute_input":"2022-11-29T22:41:27.595341Z","iopub.status.idle":"2022-11-29T22:41:27.602423Z","shell.execute_reply.started":"2022-11-29T22:41:27.595312Z","shell.execute_reply":"2022-11-29T22:41:27.601707Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from kaggle_datasets import KaggleDatasets\n\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\nprint(GCS_DS_PATH) # what do gcs paths look like?\nGCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-224x224'\n\ntrain_dir = GCS_PATH + '/train/*.tfrec'\nval_dir = GCS_PATH + '/val/*.tfrec'\ntest_dir = GCS_PATH + '/test/*.tfrec'","metadata":{"execution":{"iopub.status.busy":"2022-11-29T22:41:27.603617Z","iopub.execute_input":"2022-11-29T22:41:27.604457Z","iopub.status.idle":"2022-11-29T22:41:27.922815Z","shell.execute_reply.started":"2022-11-29T22:41:27.604405Z","shell.execute_reply":"2022-11-29T22:41:27.921797Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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\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() \n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2022-11-29T22:41:28.805290Z","iopub.execute_input":"2022-11-29T22:41:28.805552Z","iopub.status.idle":"2022-11-29T22:41:35.085210Z","shell.execute_reply.started":"2022-11-29T22:41:28.805524Z","shell.execute_reply":"2022-11-29T22:41:35.084563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BATCH_SIZE = 16 * strategy.num_replicas_in_sync\nIMAGE_SIZE = (224, 224)\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 augment(image_label, seed):\n    image, label = image_label\n    random_flip = np.random.choice(4, 1)[0]\n    if random_flip == 1:\n        image = tf.image.stateless_random_flip_left_right(image, seed=seed)\n    elif random_flip == 2:\n        image = tf.image.stateless_random_flip_up_down(image, seed=seed)\n    elif random_flip == 3:\n        image = tf.image.stateless_random_hue(image, 0.2, seed=seed)\n        \n    image = tf.image.resize_with_crop_or_pad(image, IMAGE_SIZE[0] + 6, IMAGE_SIZE[1] + 6)\n    # Make a new seed.\n    new_seed = tf.random.experimental.stateless_split(seed, num=1)[0, :]\n    # Random crop back to the original size.\n    image = tf.image.stateless_random_crop(\n      image, size=[IMAGE_SIZE[0], IMAGE_SIZE[0], 3], seed=seed)\n    # Random brightness.\n    image = tf.image.stateless_random_brightness(\n      image, max_delta=0.5, seed=new_seed)\n    image = tf.clip_by_value(image, 0, 1)\n    return image, label","metadata":{"execution":{"iopub.status.busy":"2022-11-29T22:41:35.086673Z","iopub.execute_input":"2022-11-29T22:41:35.086901Z","iopub.status.idle":"2022-11-29T22:41:35.105517Z","shell.execute_reply.started":"2022-11-29T22:41:35.086876Z","shell.execute_reply":"2022-11-29T22:41:35.104203Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"AUTOTUNE = tf.data.AUTOTUNE\ntrain_files = tf.io.gfile.glob(train_dir)\ntrain_ds = tf.data.TFRecordDataset(train_files, num_parallel_reads=AUTOTUNE).map(read_labeled_tfrecord)\ncounter = tf.data.experimental.Counter()\ntrain_ds = tf.data.Dataset.zip((train_ds, (counter, counter)))\ntrain_ds = (train_ds\n    .map(augment, num_parallel_calls=AUTOTUNE)\n    .shuffle(buffer_size=2048)\n    .batch(batch_size=BATCH_SIZE)\n    .prefetch(buffer_size=AUTOTUNE)\n)","metadata":{"execution":{"iopub.status.busy":"2022-11-29T22:41:38.796153Z","iopub.execute_input":"2022-11-29T22:41:38.796404Z","iopub.status.idle":"2022-11-29T22:41:39.225941Z","shell.execute_reply.started":"2022-11-29T22:41:38.796377Z","shell.execute_reply":"2022-11-29T22:41:39.224831Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_files = tf.io.gfile.glob(val_dir)\nval_ds = tf.data.TFRecordDataset(val_files, num_parallel_reads=AUTOTUNE).map(read_labeled_tfrecord)\nval_ds = val_ds.batch(batch_size=BATCH_SIZE).prefetch(buffer_size=AUTOTUNE)","metadata":{"execution":{"iopub.status.busy":"2022-11-29T22:41:54.756078Z","iopub.execute_input":"2022-11-29T22:41:54.756358Z","iopub.status.idle":"2022-11-29T22:41:54.814700Z","shell.execute_reply.started":"2022-11-29T22:41:54.756328Z","shell.execute_reply":"2022-11-29T22:41:54.813877Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_files = tf.io.gfile.glob(test_dir)\ntest_ds = tf.data.TFRecordDataset(test_files, num_parallel_reads=AUTOTUNE).map(read_unlabeled_tfrecord)\ntest_ds = test_ds.batch(batch_size=BATCH_SIZE).prefetch(buffer_size=AUTOTUNE)","metadata":{"execution":{"iopub.status.busy":"2022-11-29T22:41:56.480151Z","iopub.execute_input":"2022-11-29T22:41:56.480441Z","iopub.status.idle":"2022-11-29T22:41:56.599131Z","shell.execute_reply.started":"2022-11-29T22:41:56.480412Z","shell.execute_reply":"2022-11-29T22:41:56.597805Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def show_batch(images, labels, predictions=None):\n    plt.figure(figsize=(20, 20))\n    min = images.numpy().min()\n    max = images.numpy().max()\n    delta = max - min\n\n    for i in range(12):\n        plt.subplot(6, 6, i + 1)\n        plt.imshow((images[i]-min) / delta)\n        if predictions is None:\n            plt.title(CLASSES[labels[i]])\n        else:\n            if labels[i] == predictions[i]:\n                color = 'g'\n            else:\n                color = 'r'\n            plt.title(CLASSES[predictions[i]], color=color)\n        plt.axis(\"off\")\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-11-29T22:41:58.553554Z","iopub.execute_input":"2022-11-29T22:41:58.553830Z","iopub.status.idle":"2022-11-29T22:41:58.561226Z","shell.execute_reply.started":"2022-11-29T22:41:58.553799Z","shell.execute_reply":"2022-11-29T22:41:58.560280Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for images, labels in train_ds.take(1):\n    show_batch(images, labels)","metadata":{"execution":{"iopub.status.busy":"2022-11-29T22:42:00.845044Z","iopub.execute_input":"2022-11-29T22:42:00.845329Z","iopub.status.idle":"2022-11-29T22:42:06.180483Z","shell.execute_reply.started":"2022-11-29T22:42:00.845298Z","shell.execute_reply":"2022-11-29T22:42:06.179430Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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(train_files)\nNUM_VALIDATION_IMAGES = count_data_items(val_files)\nNUM_TEST_IMAGES = count_data_items(test_files)\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","metadata":{"execution":{"iopub.status.busy":"2022-11-29T22:42:06.183183Z","iopub.execute_input":"2022-11-29T22:42:06.183448Z","iopub.status.idle":"2022-11-29T22:42:06.191587Z","shell.execute_reply.started":"2022-11-29T22:42:06.183406Z","shell.execute_reply":"2022-11-29T22:42:06.190387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EPOCHS = 25\n\nwith strategy.scope():\n    preprocess_input = tf.keras.applications.mobilenet_v2.preprocess_input\n\n    # Create the base model from the pre-trained model MobileNet V2\n    IMG_SHAPE = IMAGE_SIZE + (3,)\n    pretrained_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,\n                                                   include_top=False,\n                                                   weights='imagenet')\n    pretrained_model.trainable = False\n    global_average_layer = tf.keras.layers.GlobalAveragePooling2D()\n    prediction_layer = tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    \n    model = tf.keras.Sequential([\n        # To a base pretrained on ImageNet to extract features from images...\n        pretrained_model,\n        # ... attach a new head to act as a classifier.\n        global_average_layer,\n        prediction_layer\n    ])","metadata":{"execution":{"iopub.status.busy":"2022-11-29T23:32:14.731370Z","iopub.execute_input":"2022-11-29T23:32:14.731633Z","iopub.status.idle":"2022-11-29T23:32:23.336792Z","shell.execute_reply.started":"2022-11-29T23:32:14.731606Z","shell.execute_reply":"2022-11-29T23:32:23.335417Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_learning_rate = 0.0001\nmodel.compile(loss='sparse_categorical_crossentropy',\n                optimizer=tf.keras.optimizers.Adam(learning_rate=base_learning_rate),\n                metrics=['sparse_categorical_accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-11-29T23:32:23.338398Z","iopub.execute_input":"2022-11-29T23:32:23.338627Z","iopub.status.idle":"2022-11-29T23:32:23.369920Z","shell.execute_reply.started":"2022-11-29T23:32:23.338599Z","shell.execute_reply":"2022-11-29T23:32:23.368950Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(\n    train_ds,\n    validation_data=val_ds,\n    epochs=EPOCHS\n)","metadata":{"execution":{"iopub.status.busy":"2022-11-29T23:32:23.370947Z","iopub.execute_input":"2022-11-29T23:32:23.371183Z","iopub.status.idle":"2022-11-29T23:40:29.352866Z","shell.execute_reply.started":"2022-11-29T23:32:23.371153Z","shell.execute_reply":"2022-11-29T23:40:29.351790Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2022-11-29T23:19:39.992686Z","iopub.execute_input":"2022-11-29T23:19:39.992921Z","iopub.status.idle":"2022-11-29T23:19:39.999677Z","shell.execute_reply.started":"2022-11-29T23:19:39.992898Z","shell.execute_reply":"2022-11-29T23:19:39.998245Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"display_training_curves(\n    history.history['loss'],\n    history.history['val_loss'],\n    'loss',\n    211,\n)\ndisplay_training_curves(\n    history.history['sparse_categorical_accuracy'],\n    history.history['val_sparse_categorical_accuracy'],\n    'accuracy',\n    212,\n)","metadata":{"execution":{"iopub.status.busy":"2022-11-29T23:40:35.845472Z","iopub.execute_input":"2022-11-29T23:40:35.845757Z","iopub.status.idle":"2022-11-29T23:40:36.267132Z","shell.execute_reply.started":"2022-11-29T23:40:35.845728Z","shell.execute_reply":"2022-11-29T23:40:36.266324Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for images, ids in val_ds.take(1):\n    predictions = model.predict(images)\n    predictions = tf.argmax(predictions, axis=-1)\nshow_batch(images, labels, tf.cast(predictions, tf.int32))","metadata":{"execution":{"iopub.status.busy":"2022-11-29T23:40:51.849070Z","iopub.execute_input":"2022-11-29T23:40:51.851489Z","iopub.status.idle":"2022-11-29T23:40:53.965952Z","shell.execute_reply.started":"2022-11-29T23:40:51.851450Z","shell.execute_reply":"2022-11-29T23:40:53.965289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pretrained_model.trainable = True\n\n# Let's take a look to see how many layers are in the base model\nprint(\"Number of layers in the base model: \", len(pretrained_model.layers))\n\n# Fine-tune from this layer onwards\nfine_tune_at = 100\n\n# Freeze all the layers before the `fine_tune_at` layer\nfor layer in pretrained_model.layers[:fine_tune_at]:\n    layer.trainable = False","metadata":{"execution":{"iopub.status.busy":"2022-11-29T23:41:18.422685Z","iopub.execute_input":"2022-11-29T23:41:18.423111Z","iopub.status.idle":"2022-11-29T23:41:18.437544Z","shell.execute_reply.started":"2022-11-29T23:41:18.423076Z","shell.execute_reply":"2022-11-29T23:41:18.436252Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss='sparse_categorical_crossentropy',\n              optimizer = tf.keras.optimizers.RMSprop(learning_rate=base_learning_rate/10),\n              metrics=['sparse_categorical_accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-11-29T23:41:20.509162Z","iopub.execute_input":"2022-11-29T23:41:20.509425Z","iopub.status.idle":"2022-11-29T23:41:20.542185Z","shell.execute_reply.started":"2022-11-29T23:41:20.509398Z","shell.execute_reply":"2022-11-29T23:41:20.540910Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(model.trainable_variables)","metadata":{"execution":{"iopub.status.busy":"2022-11-29T23:08:34.707312Z","iopub.execute_input":"2022-11-29T23:08:34.708051Z","iopub.status.idle":"2022-11-29T23:08:34.715907Z","shell.execute_reply.started":"2022-11-29T23:08:34.708009Z","shell.execute_reply":"2022-11-29T23:08:34.714793Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fine_tune_epochs = 20\ntotal_epochs =  EPOCHS + fine_tune_epochs\n\nhistory_fine = model.fit(train_ds,\n                         epochs=total_epochs,\n                         initial_epoch=history.epoch[-1],\n                         validation_data=val_ds)","metadata":{"execution":{"iopub.status.busy":"2022-11-29T23:41:32.635772Z","iopub.execute_input":"2022-11-29T23:41:32.636096Z","iopub.status.idle":"2022-11-29T23:48:30.960557Z","shell.execute_reply.started":"2022-11-29T23:41:32.636065Z","shell.execute_reply":"2022-11-29T23:48:30.959226Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred_list = []\nfor images, ids in test_ds:\n    predictions = model.predict(images)\n    predictions = tf.argmax(predictions, axis=-1)\n    pred_list.extend(list(zip(ids.numpy(), predictions.numpy())))\npred_list[:5]","metadata":{"execution":{"iopub.status.busy":"2022-11-29T23:48:44.784463Z","iopub.execute_input":"2022-11-29T23:48:44.785621Z","iopub.status.idle":"2022-11-29T23:49:22.032437Z","shell.execute_reply.started":"2022-11-29T23:48:44.785563Z","shell.execute_reply":"2022-11-29T23:49:22.031322Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.DataFrame(pred_list, columns=['id', 'label'])\ndf['id'] = df['id'].apply(lambda x: str(x)[2:-1])\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2022-11-29T23:49:22.033907Z","iopub.execute_input":"2022-11-29T23:49:22.034156Z","iopub.status.idle":"2022-11-29T23:49:22.070981Z","shell.execute_reply.started":"2022-11-29T23:49:22.034129Z","shell.execute_reply":"2022-11-29T23:49:22.070073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2022-11-29T23:49:22.072139Z","iopub.execute_input":"2022-11-29T23:49:22.072403Z","iopub.status.idle":"2022-11-29T23:49:22.088520Z","shell.execute_reply.started":"2022-11-29T23:49:22.072367Z","shell.execute_reply":"2022-11-29T23:49:22.087563Z"},"trusted":true},"execution_count":null,"outputs":[]}]}