{"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 tensorflow as tf \nfrom kaggle_datasets import KaggleDatasets \nimport numpy as np \nimport warnings\nwarnings.filterwarnings('ignore')\n\nprint(\"Tensorflow version:\", tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2023-02-07T10:06:45.423550Z","iopub.execute_input":"2023-02-07T10:06:45.424019Z","iopub.status.idle":"2023-02-07T10:06:52.359795Z","shell.execute_reply.started":"2023-02-07T10:06:45.423911Z","shell.execute_reply":"2023-02-07T10:06:52.358430Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Detect my accelerator**","metadata":{}},{"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy \n\ntry: \n    # TPU Detection. No parameters necessary if TPU_NAME environment variable is set. \n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()   \n    print(\"Running on TPU:\", tpu.master()) \nexcept ValueError: \n    tpu = None \n\nif tpu: \n    # Connecting to cluster \n    tf.config.experimental_connect_to_cluster(tpu) \n    tf.tpu.experimental.initialize_tpu_system(tpu) \n    # Synchronous training on TPUs and TPU Pods.\n    strategy = tf.distribute.experimental.TPUStrategy(tpu) \nelse:\n    # Default Distribution strategy in Tensorflow. Works on CPU and single GPU\n    tf.distribute.get_strategy()\n\nprint(\"REPLICAS:\", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2023-02-07T10:06:52.362442Z","iopub.execute_input":"2023-02-07T10:06:52.362833Z","iopub.status.idle":"2023-02-07T10:06:57.733418Z","shell.execute_reply.started":"2023-02-07T10:06:52.362785Z","shell.execute_reply":"2023-02-07T10:06:57.732625Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Get my data path**","metadata":{}},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path() ","metadata":{"execution":{"iopub.status.busy":"2023-02-07T10:06:57.734831Z","iopub.execute_input":"2023-02-07T10:06:57.735185Z","iopub.status.idle":"2023-02-07T10:06:58.064286Z","shell.execute_reply.started":"2023-02-07T10:06:57.735140Z","shell.execute_reply":"2023-02-07T10:06:58.063361Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Set some parameters**","metadata":{}},{"cell_type":"code","source":"# For IMAGE_SIZE=[192, 192], a GPU will run out of memory, hence use TPU \nIMAGE_SIZE = [192, 192] \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-02-07T10:06:58.066592Z","iopub.execute_input":"2023-02-07T10:06:58.067205Z","iopub.status.idle":"2023-02-07T10:06:58.073887Z","shell.execute_reply.started":"2023-02-07T10:06:58.067152Z","shell.execute_reply":"2023-02-07T10:06:58.072719Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Load Data**\n\nThis data is loaded from Kaggle and automatically sharded to maximize parallelization.","metadata":{}},{"cell_type":"code","source":"def decode_image(image_data): \n    image = tf.image.decode_jpeg(image_data, channels=3) \n    # Converting image to floats in the range [0, 1]\n    image = tf.cast(image, tf.float32) / 255.0 \n    # explicit size needed for TPU. Reshaping the data so that all the images are of same shape\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image ","metadata":{"execution":{"iopub.status.busy":"2023-02-07T10:06:58.075598Z","iopub.execute_input":"2023-02-07T10:06:58.075953Z","iopub.status.idle":"2023-02-07T10:06:58.087797Z","shell.execute_reply.started":"2023-02-07T10:06:58.075907Z","shell.execute_reply":"2023-02-07T10:06:58.086920Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_labeled_tfrecord(example): \n    LABELED_TFREC_FORMAT = {\n        # tf.io.FixedLenFeature ==> Configuration for parsing a fixed-length input feature.\n        \"image\": tf.io.FixedLenFeature([], tf.string), # shape [] ==> single element, tf.string ==> bytestring\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 # returns a dataset of (image, label) pairs\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        # class is missing, \n        # 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)","metadata":{"execution":{"iopub.status.busy":"2023-02-07T10:06:58.089345Z","iopub.execute_input":"2023-02-07T10:06:58.089614Z","iopub.status.idle":"2023-02-07T10:06:58.103230Z","shell.execute_reply.started":"2023-02-07T10:06:58.089573Z","shell.execute_reply":"2023-02-07T10:06:58.102011Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_dataset(filenames, labeled=True, ordered=False): \n    # Read from TFRecords. \n    # For optimal performance, reading from multiple files at once and disregarding data order. \n    # 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) \n    # num_parallel_reads=AUTO ==> Number of files to read in parallel\n    # automatically interleaves reads from multiple files\n    \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    # num_parallel_calls=AUTO ==> This loads multiple datasets in parallel, reducing the time waiting for the files to be opened.\n    \n    return dataset\n    # returns a dataset of \n    # (image, label) pairs if labeled=True \n    # OR \n    # (image, id) pairs if labeled=False","metadata":{"execution":{"iopub.status.busy":"2023-02-07T10:06:58.104787Z","iopub.execute_input":"2023-02-07T10:06:58.105250Z","iopub.status.idle":"2023-02-07T10:06:58.119257Z","shell.execute_reply.started":"2023-02-07T10:06:58.105178Z","shell.execute_reply":"2023-02-07T10:06:58.118205Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_training_dataset(): \n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/train/*.tfrec'), labeled=True) \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) \n    # prefetch next batch while training (autotune prefetch buffer size) \n    \n    return dataset \n\ndef get_validation_dataset(): \n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/val/*.tfrec'), labeled=True, ordered=False) \n    dataset = dataset.batch(BATCH_SIZE) \n    dataset = dataset.cache() \n    # The first time the dataset is iterated over, \n    # ...its elements will be cached either in the specified file or in memory. \n    # Subsequent iterations will use the cached data.\n    \n    dataset = dataset.prefetch(AUTO) \n    # prefetch next batch while training (autotune prefetch buffer size) \n    \n    return dataset \n\ndef get_test_dataset(ordered=False): \n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/test/*.tfrec'), labeled=True, ordered=ordered) \n    dataset = dataset.batch(BATCH_SIZE) \n    dataset = dataset.prefetch(AUTO) \n    # prefetch next batch while training (autotune prefetch buffer size) \n    \n    return dataset ","metadata":{"execution":{"iopub.status.busy":"2023-02-07T10:06:58.120441Z","iopub.execute_input":"2023-02-07T10:06:58.120924Z","iopub.status.idle":"2023-02-07T10:06:58.138273Z","shell.execute_reply.started":"2023-02-07T10:06:58.120886Z","shell.execute_reply":"2023-02-07T10:06:58.137019Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"training_dataset = get_training_dataset() \nvalidation_dataset = get_validation_dataset()","metadata":{"execution":{"iopub.status.busy":"2023-02-07T10:06:58.139978Z","iopub.execute_input":"2023-02-07T10:06:58.140356Z","iopub.status.idle":"2023-02-07T10:06:58.443109Z","shell.execute_reply.started":"2023-02-07T10:06:58.140308Z","shell.execute_reply":"2023-02-07T10:06:58.442047Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Building the model**","metadata":{}},{"cell_type":"code","source":"with strategy.scope(): \n    pretrained_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False, input_shape=[*IMAGE_SIZE, 3]) \n    # pretraining on ImageNet, \n    # include_top ==> whether to include the 3 fully-connected layers at the top of the network. \n    \n    pretrained_model.trainable = False # transfer learning \n    # prevents the weights in a given layer/model from being updated during training. \n    \n    model = tf.keras.Sequential([\n        pretrained_model, \n        tf.keras.layers.GlobalAveragePooling2D(), \n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n\nmodel.compile(\n    optimizer='adam', \n    loss='sparse_categorical_crossentropy', \n    metrics=['sparse_categorical_accuracy']\n)\n\nhistorical = model.fit(training_dataset, \n                      steps_per_epoch=STEPS_PER_EPOCH, \n                      epochs=EPOCHS, \n                      validation_data=validation_dataset)","metadata":{"execution":{"iopub.status.busy":"2023-02-07T10:06:58.445288Z","iopub.execute_input":"2023-02-07T10:06:58.445560Z","iopub.status.idle":"2023-02-07T10:07:44.377065Z","shell.execute_reply.started":"2023-02-07T10:06:58.445515Z","shell.execute_reply":"2023-02-07T10:07:44.375666Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Compute predictions on the test data** ","metadata":{}},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True) \n# 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(probabilites, 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]), \n           fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')","metadata":{"execution":{"iopub.status.busy":"2023-02-07T10:07:44.378932Z","iopub.execute_input":"2023-02-07T10:07:44.379304Z","iopub.status.idle":"2023-02-07T10:07:47.517416Z","shell.execute_reply.started":"2023-02-07T10:07:44.379257Z","shell.execute_reply":"2023-02-07T10:07:47.515403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}