{"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 matplotlib.pyplot as plt\nAUTO = tf.data.experimental.AUTOTUNE\n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-10-10T19:42:13.304042Z","iopub.execute_input":"2021-10-10T19:42:13.304778Z","iopub.status.idle":"2021-10-10T19:42:13.312281Z","shell.execute_reply.started":"2021-10-10T19:42:13.30473Z","shell.execute_reply":"2021-10-10T19:42:13.311482Z"},"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    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":"2021-10-10T19:42:13.314311Z","iopub.execute_input":"2021-10-10T19:42:13.314969Z","iopub.status.idle":"2021-10-10T19:42:20.712213Z","shell.execute_reply.started":"2021-10-10T19:42:13.314922Z","shell.execute_reply":"2021-10-10T19:42:20.711148Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [512, 512] # at this size, a GPU will run out of memory. Use the TPU\nEPOCHS = 50\nBATCH_SIZE = 64 * strategy.num_replicas_in_sync\n\nNUM_TRAINING_IMAGES = 12753\nNUM_TEST_IMAGES = 7382\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE","metadata":{"execution":{"iopub.status.busy":"2021-10-10T19:42:20.714059Z","iopub.execute_input":"2021-10-10T19:42:20.714307Z","iopub.status.idle":"2021-10-10T19:42:20.719137Z","shell.execute_reply.started":"2021-10-10T19:42:20.71428Z","shell.execute_reply":"2021-10-10T19:42:20.718508Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Learning Rate Schedule for Fine Tuning #\ndef exponential_lr(epoch,\n                   start_lr = 0.00001, min_lr = 0.00001, max_lr = 0.0001,\n                   rampup_epochs = 20, sustain_epochs = 0,\n                   exp_decay = 0.8):\n\n    # linear increase from start to rampup_epochs\n    if epoch < rampup_epochs:\n        lr = ((max_lr - start_lr) /rampup_epochs * epoch + start_lr)\n    # constant max_lr during sustain_epochs\n    elif epoch < rampup_epochs + sustain_epochs:\n        lr = max_lr\n    # exponential decay towards min_lr\n    else:\n        lr = ((max_lr - min_lr) *\n                exp_decay**(epoch - rampup_epochs - sustain_epochs) +\n                min_lr)\n    \n    return lr\n\nlr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr, verbose=True)\nrng = [i for i in range(EPOCHS)]\ny = [exponential_lr(x) for x in rng]\nplt.plot(rng, y)\nprint(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))","metadata":{"execution":{"iopub.status.busy":"2021-10-10T19:42:20.720825Z","iopub.execute_input":"2021-10-10T19:42:20.721525Z","iopub.status.idle":"2021-10-10T19:42:20.944307Z","shell.execute_reply.started":"2021-10-10T19:42:20.721483Z","shell.execute_reply":"2021-10-10T19:42:20.943074Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path()","metadata":{"execution":{"iopub.status.busy":"2021-10-10T19:42:20.945761Z","iopub.execute_input":"2021-10-10T19:42:20.946071Z","iopub.status.idle":"2021-10-10T19:42:21.351038Z","shell.execute_reply.started":"2021-10-10T19:42:20.946038Z","shell.execute_reply":"2021-10-10T19:42:21.350118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"augmentations = tf.keras.Sequential([\n    tf.keras.layers.experimental.preprocessing.RandomFlip(mode='horizontal'),\n    tf.keras.layers.experimental.preprocessing.RandomFlip(mode='vertical'),\n    tf.keras.layers.experimental.preprocessing.RandomContrast(factor=0.8),\n    tf.keras.layers.experimental.preprocessing.RandomZoom(-0.9,0.9),\n    tf.keras.layers.experimental.preprocessing.RandomRotation(factor=0.2, dtype=tf.float32)\n])\ndef data_augment(image, label):\n    # data augmentation. Thanks to the dataset.prefetch(AUTO) statement in the next function ,\n    # this happens essentially for free on TPU. Data pipeline code is executed on the \"CPU\" part\n    # of the TPU while the TPU itself is computing gradients.\n    image = augmentations(image, training=True) # Keras preprocessing layers are only applied at training time. Forcing it here for visualization.\n    return image, label\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) # 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 get_training_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/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.map(data_augment, num_parallel_calls=AUTO)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training\n    return dataset\n\ndef get_validation_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/val/*.tfrec'), labeled=True, ordered=False)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/test/*.tfrec'), labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset\n\ntraining_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()","metadata":{"execution":{"iopub.status.busy":"2021-10-10T19:42:21.356408Z","iopub.execute_input":"2021-10-10T19:42:21.356684Z","iopub.status.idle":"2021-10-10T19:42:22.040089Z","shell.execute_reply.started":"2021-10-10T19:42:21.356655Z","shell.execute_reply":"2021-10-10T19:42:22.039139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():    \n    pretrained_model = tf.keras.applications.Xception(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model.trainable = False # transfer learning\n    #print(pretrained_model.summary())\n    pretrained_model.trainable = True\n    set_trainable = False\n    for layer in pretrained_model.layers:\n        if layer.name == 'block11_sepconv1':\n            set_trainable = True\n        if set_trainable:\n            layer.trainable = True\n        else:\n            layer.trainable = False\n    \n    model = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.Dense(2048, activation='relu'),\n        tf.keras.layers.Dropout(0.3),\n        tf.keras.layers.Dense(1024, activation='relu'),\n        tf.keras.layers.Dropout(0.3),\n        tf.keras.layers.Dense(512, activation='relu'),\n        tf.keras.layers.Dropout(0.3),\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) #,\n          #callbacks=[lr_callback])","metadata":{"execution":{"iopub.status.busy":"2021-10-10T19:42:22.041649Z","iopub.execute_input":"2021-10-10T19:42:22.042118Z","iopub.status.idle":"2021-10-10T20:39:23.798163Z","shell.execute_reply.started":"2021-10-10T19:42:22.042077Z","shell.execute_reply":"2021-10-10T20:39:23.797352Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nhistory_dict = historical.history\nacc  = history_dict['sparse_categorical_accuracy']\nval_acc = history_dict['val_sparse_categorical_accuracy']\nepochs = range(1,len(val_acc)+1)\n\nplt.plot(epochs, acc,'bo',label='Training Accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation Accuracy')\nplt.title('Training and validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.ylim(0.5,1)\nplt.legend()\nplt.show()\n\n\nloss  = history_dict['loss']\nval_loss = history_dict['val_loss']\nepochs = range(1,len(val_loss)+1)\n\nplt.plot(epochs, loss,'bo',label='Training Loss')\nplt.plot(epochs, val_loss, 'b', label='Validation Loss')\nplt.title('Training and validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\n#plt.ylim(0.5,1)\nplt.legend()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2021-10-10T20:39:23.799515Z","iopub.execute_input":"2021-10-10T20:39:23.799852Z","iopub.status.idle":"2021-10-10T20:39:24.260946Z","shell.execute_reply.started":"2021-10-10T20:39:23.799812Z","shell.execute_reply":"2021-10-10T20:39:24.259999Z"},"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":"2021-10-10T20:39:24.262904Z","iopub.execute_input":"2021-10-10T20:39:24.263136Z","iopub.status.idle":"2021-10-10T20:40:10.244789Z","shell.execute_reply.started":"2021-10-10T20:39:24.263109Z","shell.execute_reply":"2021-10-10T20:40:10.243394Z"},"trusted":true},"execution_count":null,"outputs":[]}]}