{"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":"# TensorFlow and tf.keras\nimport tensorflow as tf\n\n# Helper libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport re\nfrom functools import partial\n\nprint(tf.__version__)","metadata":{"_uuid":"80076f0c-f3c6-40ea-bcf4-5a644e04b54a","_cell_guid":"b1596b52-c5e7-4727-825a-f310d23a7f7b","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-10-01T01:14:59.671380Z","iopub.execute_input":"2021-10-01T01:14:59.671740Z","iopub.status.idle":"2021-10-01T01:15:04.933402Z","shell.execute_reply.started":"2021-10-01T01:14:59.671648Z","shell.execute_reply":"2021-10-01T01:15:04.932534Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print(\"Device:\", tpu.master())\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.TPUStrategy(tpu)\nexcept:\n    strategy = tf.distribute.get_strategy()\nprint(\"Number of replicas:\", strategy.num_replicas_in_sync)","metadata":{"_uuid":"c7dcd1ee-0e94-4f90-b824-e25ce49a2ddd","_cell_guid":"52624cfa-71df-4795-bc9a-707bd9c7d91b","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-10-01T01:15:06.796180Z","iopub.execute_input":"2021-10-01T01:15:06.796505Z","iopub.status.idle":"2021-10-01T01:15:12.604368Z","shell.execute_reply.started":"2021-10-01T01:15:06.796470Z","shell.execute_reply":"2021-10-01T01:15:12.603763Z"},"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?","metadata":{"_uuid":"8f4e83a8-debf-4edf-9d13-09aa1b1b2874","_cell_guid":"3a70eded-9851-479e-a308-f937c562b6b4","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-10-01T01:15:22.470993Z","iopub.execute_input":"2021-10-01T01:15:22.471594Z","iopub.status.idle":"2021-10-01T01:15:22.991371Z","shell.execute_reply.started":"2021-10-01T01:15:22.471554Z","shell.execute_reply":"2021-10-01T01:15:22.990403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-512x512'\n\nIMAGE_SIZE = [512, 512]\n\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\nprint(\"Train TFRecord Files:\", len(TRAINING_FILENAMES))\nprint(\"Validation TFRecord Files:\", len(VALIDATION_FILENAMES))\nprint(\"Test TFRecord Files:\", len(TEST_FILENAMES))","metadata":{"_uuid":"d257d342-4d6b-4c3a-9870-d6f59f1081da","_cell_guid":"54e80f7f-248f-4987-a504-547506d5cbd3","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-10-01T01:15:55.932198Z","iopub.execute_input":"2021-10-01T01:15:55.932466Z","iopub.status.idle":"2021-10-01T01:15:56.152280Z","shell.execute_reply.started":"2021-10-01T01:15:55.932438Z","shell.execute_reply":"2021-10-01T01:15:56.151470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BATCH_SIZE = 16 * strategy.num_replicas_in_sync","metadata":{"_uuid":"a63b5bcb-6f8f-4b14-afd4-fb7559d7e7ce","_cell_guid":"e2151eb2-d331-491f-98d3-febe78de0cba","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-10-01T01:15:51.223765Z","iopub.execute_input":"2021-10-01T01:15:51.224027Z","iopub.status.idle":"2021-10-01T01:15:51.228245Z","shell.execute_reply.started":"2021-10-01T01:15:51.224001Z","shell.execute_reply":"2021-10-01T01:15:51.227158Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def decode_image(image):\n    image = tf.image.decode_jpeg(image, channels=3)\n    image = tf.cast(image, tf.float32)\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), # 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) # 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)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\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    image = tf.image.random_flip_left_right(image)\n    #image = tf.image.random_saturation(image, 0, 2)\n    return image, label   \n\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","metadata":{"_uuid":"8078f2cb-8d7b-4ed9-b814-650bb4041816","_cell_guid":"6f1750ac-d5e6-4e58-a32c-0a73f72e45ea","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-10-01T01:16:07.799239Z","iopub.execute_input":"2021-10-01T01:16:07.799555Z","iopub.status.idle":"2021-10-01T01:16:07.816794Z","shell.execute_reply.started":"2021-10-01T01:16:07.799521Z","shell.execute_reply":"2021-10-01T01:16:07.815641Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds_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)","metadata":{"_uuid":"b85046c8-795b-4ec2-b9c8-0e84631b22e5","_cell_guid":"61b9f38c-c218-447e-8d0d-8ce3fea9efdf","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-10-01T01:16:11.535803Z","iopub.execute_input":"2021-10-01T01:16:11.536081Z","iopub.status.idle":"2021-10-01T01:16:11.857594Z","shell.execute_reply.started":"2021-10-01T01:16:11.536055Z","shell.execute_reply":"2021-10-01T01:16:11.856608Z"},"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(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":{"_uuid":"37d4487c-5d0a-4816-a8f1-4c680b9ae8ff","_cell_guid":"c30ca3ec-7ea9-4b19-9c71-422c77dd566e","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-10-01T01:16:14.597829Z","iopub.execute_input":"2021-10-01T01:16:14.598499Z","iopub.status.idle":"2021-10-01T01:16:14.605996Z","shell.execute_reply.started":"2021-10-01T01:16:14.598457Z","shell.execute_reply":"2021-10-01T01:16:14.605144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CLASSES = ['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\nlen(CLASSES)","metadata":{"_uuid":"a7d68bb0-f2ca-40f7-a3ed-490a070f6791","_cell_guid":"d6eafa86-cc80-4228-93bf-f097500caceb","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-10-01T01:16:19.019788Z","iopub.execute_input":"2021-10-01T01:16:19.020072Z","iopub.status.idle":"2021-10-01T01:16:19.037501Z","shell.execute_reply.started":"2021-10-01T01:16:19.020043Z","shell.execute_reply":"2021-10-01T01:16:19.036540Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_batch, label_batch = next(iter(ds_train))\n\ndef show_batch(image_batch, label_batch):\n    plt.figure(figsize=(10, 10))\n    for n in range(25):\n        ax = plt.subplot(5, 5, n + 1)\n        plt.imshow(image_batch[n] / 255.0)\n        plt.title(CLASSES[label_batch[n]])\n        plt.axis(\"off\")\n\n\nshow_batch(image_batch.numpy(), label_batch.numpy())","metadata":{"execution":{"iopub.status.busy":"2021-10-01T01:16:22.357501Z","iopub.execute_input":"2021-10-01T01:16:22.357790Z","iopub.status.idle":"2021-10-01T01:16:37.657210Z","shell.execute_reply.started":"2021-10-01T01:16:22.357763Z","shell.execute_reply":"2021-10-01T01:16:37.656412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nwith strategy.scope():\n    pretrained_model = tf.keras.applications.VGG16(\n        weights='imagenet',\n        include_top=False ,\n        input_shape=[*IMAGE_SIZE, 3]\n    )\n\n    pretrained_model.trainable = False\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        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])","metadata":{"_uuid":"5e0052ad-f9f2-453e-94fa-d0420e4f166e","_cell_guid":"7923eb99-66a7-424d-bc5e-38f80cf590a8","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-10-01T01:16:44.474507Z","iopub.execute_input":"2021-10-01T01:16:44.474786Z","iopub.status.idle":"2021-10-01T01:16:47.136023Z","shell.execute_reply.started":"2021-10-01T01:16:44.474758Z","shell.execute_reply":"2021-10-01T01:16:47.135164Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(\n    optimizer = 'adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['accuracy'],\n)\n\nmodel.summary()","metadata":{"_uuid":"5f2ac906-ffd7-4d4b-a943-92af737f3adf","_cell_guid":"3db7feeb-e59d-447e-8a42-4f7d176f48c5","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-10-01T01:16:50.830754Z","iopub.execute_input":"2021-10-01T01:16:50.831051Z","iopub.status.idle":"2021-10-01T01:16:50.878911Z","shell.execute_reply.started":"2021-10-01T01:16:50.831017Z","shell.execute_reply":"2021-10-01T01:16:50.878075Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nEPOCHS = 12\nhistory = model.fit(\n                    ds_train, \n                    steps_per_epoch=STEPS_PER_EPOCH, \n                    epochs=EPOCHS,\n                    validation_data=ds_valid\n)","metadata":{"_uuid":"050dde91-c429-450f-87ed-01e2ca85a3e3","_cell_guid":"24b32d4f-93dd-4e94-ba67-fcd88e7a9b3a","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-10-01T01:16:53.612651Z","iopub.execute_input":"2021-10-01T01:16:53.613271Z","iopub.status.idle":"2021-10-01T01:27:32.983538Z","shell.execute_reply.started":"2021-10-01T01:16:53.613233Z","shell.execute_reply":"2021-10-01T01:27:32.982627Z"},"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_xlabel('epoch')\n  ax.legend(['train', 'valid.'])","metadata":{"_uuid":"a429bcd1-ee26-4a48-9393-ccd23b43ea0d","_cell_guid":"c24026cd-fb8a-49e9-82be-f971a38ce1fd","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-10-01T01:27:39.301662Z","iopub.execute_input":"2021-10-01T01:27:39.301953Z","iopub.status.idle":"2021-10-01T01:27:39.309202Z","shell.execute_reply.started":"2021-10-01T01:27:39.301907Z","shell.execute_reply":"2021-10-01T01:27:39.308403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(history.history.keys())\ndisplay_training_curves(history.history['accuracy'], history.history['val_accuracy'], 'accuracy', 211)\ndisplay_training_curves(history.history['loss'], history.history['val_loss'], 'loss', 212)","metadata":{"_uuid":"518ec79f-5b2e-4c96-bdf6-8d33d39a1efd","_cell_guid":"357eb5c4-0372-4ff6-8e59-a14995cd3abb","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-10-01T01:27:41.862908Z","iopub.execute_input":"2021-10-01T01:27:41.863826Z","iopub.status.idle":"2021-10-01T01:27:42.325152Z","shell.execute_reply.started":"2021-10-01T01:27:41.863787Z","shell.execute_reply":"2021-10-01T01:27:42.324362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_batch, label_batch = next(iter(ds_valid))\n\ndef title_from_label_and_target(label, correct_label):\n  correct = (label == correct_label)\n  return \"{} [{}{}{}]\".format(CLASSES[label], str(correct), ', shoud be ' if not correct else '',\n                              CLASSES[correct_label] if not correct else ''), correct\n\ndef show_flower_prediction(image_batch, label_batch):\n    plt.figure(figsize=(18, 18))\n    for n in range(25):\n        ax = plt.subplot(5, 5, n + 1)\n        plt.imshow(image_batch[n] / 255.0)\n        img_array = tf.expand_dims(image_batch[n], axis=0)\n        predictions = model.predict(img_array)[0]\n        prediction_label = np.argmax(predictions, axis=-1)\n        plt.title(title_from_label_and_target(prediction_label, label_batch[n]))\n        plt.axis(\"off\")\n\n\nshow_flower_prediction(image_batch.numpy(), label_batch.numpy())","metadata":{"_uuid":"32260eb9-8603-4a90-b5ef-8cffc4def712","_cell_guid":"50fbec20-d7d5-466f-bbb0-8a5d583865b2","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-10-01T01:27:57.253645Z","iopub.execute_input":"2021-10-01T01:27:57.254127Z","iopub.status.idle":"2021-10-01T01:28:20.709018Z","shell.execute_reply.started":"2021-10-01T01:27:57.254095Z","shell.execute_reply":"2021-10-01T01:28:20.708392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Computing predictions...')\ntest_images_ds = ds_test.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)","metadata":{"execution":{"iopub.status.busy":"2021-10-01T01:28:39.777384Z","iopub.execute_input":"2021-10-01T01:28:39.777662Z","iopub.status.idle":"2021-10-01T01:29:30.335240Z","shell.execute_reply.started":"2021-10-01T01:28:39.777635Z","shell.execute_reply":"2021-10-01T01:29:30.334440Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Generating submission.csv file...')\n\n# Get image ids from test set and convert to unicode\ntest_ids_ds = ds_test.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\n# Write the submission file\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# Look at the first few predictions\n!head submission.csv","metadata":{"execution":{"iopub.status.busy":"2021-10-01T01:29:45.661745Z","iopub.execute_input":"2021-10-01T01:29:45.662483Z","iopub.status.idle":"2021-10-01T01:30:13.668206Z","shell.execute_reply.started":"2021-10-01T01:29:45.662441Z","shell.execute_reply":"2021-10-01T01:30:13.667268Z"},"trusted":true},"execution_count":null,"outputs":[]}]}