{"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":"2023-02-17T03:43:53.134498Z","iopub.execute_input":"2023-02-17T03:43:53.135377Z","iopub.status.idle":"2023-02-17T03:43:59.080307Z","shell.execute_reply.started":"2023-02-17T03:43:53.135252Z","shell.execute_reply":"2023-02-17T03:43:59.079369Z"},"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":"2023-02-17T03:43:59.083398Z","iopub.execute_input":"2023-02-17T03:43:59.083757Z","iopub.status.idle":"2023-02-17T03:43:59.0927Z","shell.execute_reply.started":"2023-02-17T03:43:59.083714Z","shell.execute_reply":"2023-02-17T03:43:59.09193Z"},"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":"2023-02-17T03:43:59.093883Z","iopub.execute_input":"2023-02-17T03:43:59.09437Z","iopub.status.idle":"2023-02-17T03:43:59.395122Z","shell.execute_reply.started":"2023-02-17T03:43:59.094326Z","shell.execute_reply":"2023-02-17T03:43:59.394148Z"},"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":"2023-02-17T03:43:59.397379Z","iopub.execute_input":"2023-02-17T03:43:59.397697Z","iopub.status.idle":"2023-02-17T03:44:04.464678Z","shell.execute_reply.started":"2023-02-17T03:43:59.397656Z","shell.execute_reply":"2023-02-17T03:44:04.463681Z"},"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":"2023-02-17T03:44:04.466385Z","iopub.execute_input":"2023-02-17T03:44:04.466751Z","iopub.status.idle":"2023-02-17T03:44:04.484161Z","shell.execute_reply.started":"2023-02-17T03:44:04.46672Z","shell.execute_reply":"2023-02-17T03:44:04.483356Z"},"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":"2023-02-17T03:44:04.485381Z","iopub.execute_input":"2023-02-17T03:44:04.485805Z","iopub.status.idle":"2023-02-17T03:44:04.973704Z","shell.execute_reply.started":"2023-02-17T03:44:04.485766Z","shell.execute_reply":"2023-02-17T03:44:04.972826Z"},"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":"2023-02-17T03:44:04.974916Z","iopub.execute_input":"2023-02-17T03:44:04.97517Z","iopub.status.idle":"2023-02-17T03:44:05.046306Z","shell.execute_reply.started":"2023-02-17T03:44:04.975142Z","shell.execute_reply":"2023-02-17T03:44:05.044735Z"},"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":"2023-02-17T03:44:05.048244Z","iopub.execute_input":"2023-02-17T03:44:05.048583Z","iopub.status.idle":"2023-02-17T03:44:05.169068Z","shell.execute_reply.started":"2023-02-17T03:44:05.048541Z","shell.execute_reply":"2023-02-17T03:44:05.168168Z"},"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":"2023-02-17T03:44:05.170124Z","iopub.execute_input":"2023-02-17T03:44:05.170761Z","iopub.status.idle":"2023-02-17T03:44:05.177312Z","shell.execute_reply.started":"2023-02-17T03:44:05.170728Z","shell.execute_reply":"2023-02-17T03:44:05.176601Z"},"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":"2023-02-17T03:44:05.179665Z","iopub.execute_input":"2023-02-17T03:44:05.180101Z","iopub.status.idle":"2023-02-17T03:44:10.666106Z","shell.execute_reply.started":"2023-02-17T03:44:05.18007Z","shell.execute_reply":"2023-02-17T03:44:10.664409Z"},"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":"2023-02-17T03:44:10.667354Z","iopub.execute_input":"2023-02-17T03:44:10.667624Z","iopub.status.idle":"2023-02-17T03:44:10.674866Z","shell.execute_reply.started":"2023-02-17T03:44:10.667591Z","shell.execute_reply":"2023-02-17T03:44:10.674084Z"},"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":"2023-02-17T03:44:10.676435Z","iopub.execute_input":"2023-02-17T03:44:10.676916Z","iopub.status.idle":"2023-02-17T03:44:20.237349Z","shell.execute_reply.started":"2023-02-17T03:44:10.676869Z","shell.execute_reply":"2023-02-17T03:44:20.236508Z"},"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":"2023-02-17T03:44:20.238671Z","iopub.execute_input":"2023-02-17T03:44:20.239023Z","iopub.status.idle":"2023-02-17T03:44:20.280142Z","shell.execute_reply.started":"2023-02-17T03:44:20.238963Z","shell.execute_reply":"2023-02-17T03:44:20.27922Z"},"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":"2023-02-17T03:44:20.281278Z","iopub.execute_input":"2023-02-17T03:44:20.281986Z","iopub.status.idle":"2023-02-17T03:52:25.238893Z","shell.execute_reply.started":"2023-02-17T03:44:20.28195Z","shell.execute_reply":"2023-02-17T03:52:25.238024Z"},"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":"2023-02-17T03:52:25.240263Z","iopub.execute_input":"2023-02-17T03:52:25.240505Z","iopub.status.idle":"2023-02-17T03:52:25.247865Z","shell.execute_reply.started":"2023-02-17T03:52:25.240478Z","shell.execute_reply":"2023-02-17T03:52:25.247034Z"},"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":"2023-02-17T03:52:25.250726Z","iopub.execute_input":"2023-02-17T03:52:25.251042Z","iopub.status.idle":"2023-02-17T03:52:25.700599Z","shell.execute_reply.started":"2023-02-17T03:52:25.251013Z","shell.execute_reply":"2023-02-17T03:52:25.699763Z"},"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":"2023-02-17T03:52:25.701899Z","iopub.execute_input":"2023-02-17T03:52:25.702219Z","iopub.status.idle":"2023-02-17T03:52:31.704171Z","shell.execute_reply.started":"2023-02-17T03:52:25.70218Z","shell.execute_reply":"2023-02-17T03:52:31.703205Z"},"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":"2023-02-17T03:52:31.705547Z","iopub.execute_input":"2023-02-17T03:52:31.705825Z","iopub.status.idle":"2023-02-17T03:52:31.722169Z","shell.execute_reply.started":"2023-02-17T03:52:31.705792Z","shell.execute_reply":"2023-02-17T03:52:31.721107Z"},"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":"2023-02-17T03:52:31.723494Z","iopub.execute_input":"2023-02-17T03:52:31.723736Z","iopub.status.idle":"2023-02-17T03:52:31.777914Z","shell.execute_reply.started":"2023-02-17T03:52:31.723706Z","shell.execute_reply":"2023-02-17T03:52:31.776733Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(model.trainable_variables)","metadata":{"execution":{"iopub.status.busy":"2023-02-17T03:52:31.779149Z","iopub.execute_input":"2023-02-17T03:52:31.779415Z","iopub.status.idle":"2023-02-17T03:52:31.786472Z","shell.execute_reply.started":"2023-02-17T03:52:31.779383Z","shell.execute_reply":"2023-02-17T03:52:31.785703Z"},"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":"2023-02-17T03:52:31.787633Z","iopub.execute_input":"2023-02-17T03:52:31.788071Z","iopub.status.idle":"2023-02-17T03:59:32.623864Z","shell.execute_reply.started":"2023-02-17T03:52:31.788037Z","shell.execute_reply":"2023-02-17T03:59:32.622964Z"},"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":"2023-02-17T03:59:32.625331Z","iopub.execute_input":"2023-02-17T03:59:32.625582Z","iopub.status.idle":"2023-02-17T04:00:08.429058Z","shell.execute_reply.started":"2023-02-17T03:59:32.625554Z","shell.execute_reply":"2023-02-17T04:00:08.428065Z"},"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":"2023-02-17T04:00:08.430352Z","iopub.execute_input":"2023-02-17T04:00:08.430611Z","iopub.status.idle":"2023-02-17T04:00:08.465253Z","shell.execute_reply.started":"2023-02-17T04:00:08.43058Z","shell.execute_reply":"2023-02-17T04:00:08.464443Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-02-17T04:03:08.285342Z","iopub.execute_input":"2023-02-17T04:03:08.285663Z","iopub.status.idle":"2023-02-17T04:03:08.301332Z","shell.execute_reply.started":"2023-02-17T04:03:08.285629Z","shell.execute_reply":"2023-02-17T04:03:08.30062Z"},"trusted":true},"execution_count":null,"outputs":[]}]}