{"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":"markdown","source":"# A Simple TF 2.2 notebook\n\nThis is intended as a simple, short introduction to the operations competitors will need to perform with TPUs.","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom kaggle_datasets import KaggleDatasets\nimport numpy as np\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.\nGCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2022-01-09T22:29:46.722969Z","iopub.execute_input":"2022-01-09T22:29:46.723531Z","iopub.status.idle":"2022-01-09T22:29:47.038923Z","shell.execute_reply.started":"2022-01-09T22:29:46.723491Z","shell.execute_reply":"2022-01-09T22:29:47.038171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [192, 192] # at this size, a GPU will run out of memory. Use the TPU\nEPOCHS = 1\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nNUM_TRAINING_IMAGES = int(0.9 * 16465)\nNUM_TEST_IMAGES = int(0.1 * 16465)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint(NUM_TRAINING_IMAGES, NUM_TEST_IMAGES)","metadata":{"execution":{"iopub.status.busy":"2022-01-09T22:29:47.040300Z","iopub.execute_input":"2022-01-09T22:29:47.040514Z","iopub.status.idle":"2022-01-09T22:29:47.047722Z","shell.execute_reply.started":"2022-01-09T22:29:47.040489Z","shell.execute_reply":"2022-01-09T22:29:47.046981Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Set some parameters","metadata":{}},{"cell_type":"markdown","source":"# Load my data\n\nThis data is loaded from Kaggle and automatically sharded to maximize parallelization.","metadata":{}},{"cell_type":"code","source":"def split_dataset(dataset: tf.data.Dataset, validation_data_fraction: float):\n    \"\"\"\n    Splits a dataset of type tf.data.Dataset into a training and validation dataset using given ratio. Fractions are\n    rounded up to two decimal places.\n    @param dataset: the input dataset to split.\n    @param validation_data_fraction: the fraction of the validation data as a float between 0 and 1.\n    @return: a tuple of two tf.data.Datasets as (training, validation)\n    \"\"\"\n\n    validation_data_percent = round(validation_data_fraction * 100)\n    if not (0 <= validation_data_percent <= 100):\n        raise ValueError(\"validation data fraction must be ∈ [0,1]\")\n\n    dataset = dataset.enumerate()\n    train_dataset = dataset.filter(lambda f, data: f % 100 > validation_data_percent)\n    validation_dataset = dataset.filter(lambda f, data: f % 100 <= validation_data_percent)\n\n    # remove enumeration\n    train_dataset = train_dataset.map(lambda f, data: data)\n    validation_dataset = validation_dataset.map(lambda f, data: data)\n\n    return train_dataset, validation_dataset\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-192x192/train/*.tfrec'), labeled=True)\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    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=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":"2022-01-09T22:29:47.049348Z","iopub.execute_input":"2022-01-09T22:29:47.050190Z","iopub.status.idle":"2022-01-09T22:29:47.277470Z","shell.execute_reply.started":"2022-01-09T22:29:47.050142Z","shell.execute_reply":"2022-01-09T22:29:47.276814Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_dataset = training_dataset.concatenate(validation_dataset)\ntrain_dataset, val_dataset = split_dataset(full_dataset, 0.1)\ntrain_dataset = train_dataset.repeat() # the training dataset must repeat for several epochs\ntrain_dataset = train_dataset.shuffle(2048)\ntrain_dataset = train_dataset.batch(BATCH_SIZE)\nval_dataset = val_dataset.batch(BATCH_SIZE)\nval_dataset = val_dataset.cache()","metadata":{"execution":{"iopub.status.busy":"2022-01-09T22:29:47.279165Z","iopub.execute_input":"2022-01-09T22:29:47.279873Z","iopub.status.idle":"2022-01-09T22:29:47.317323Z","shell.execute_reply.started":"2022-01-09T22:29:47.279835Z","shell.execute_reply":"2022-01-09T22:29:47.316690Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build a model on TPU (or GPU, or CPU...) with Tensorflow 2.1!","metadata":{}},{"cell_type":"code","source":"with strategy.scope():     \n    model = tf.keras.Sequential([\n        tf.keras.layers.Conv2D(4, (3, 3), activation='relu', input_shape=(192, 192, 3)),\n        tf.keras.layers.MaxPooling2D((2, 2), strides=2),\n        tf.keras.layers.Conv2D(4, (3, 3), activation='relu'),\n        tf.keras.layers.MaxPooling2D((2, 2), strides=2),\n        tf.keras.layers.Flatten(),\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(train_dataset,\n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS)\n","metadata":{"execution":{"iopub.status.busy":"2022-01-09T22:29:47.318349Z","iopub.execute_input":"2022-01-09T22:29:47.318603Z","iopub.status.idle":"2022-01-09T22:30:24.576390Z","shell.execute_reply.started":"2022-01-09T22:29:47.318571Z","shell.execute_reply":"2022-01-09T22:30:24.575364Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():    \n    pretrained_model = tf.keras.applications.xception.Xception(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model.trainable = False # tramsfer learning\n    \n    xception_model = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n        \nxception_model.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nhistorical_xception = xception_model.fit(train_dataset,\n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS)","metadata":{"execution":{"iopub.status.busy":"2022-01-09T22:30:24.578251Z","iopub.execute_input":"2022-01-09T22:30:24.579109Z","iopub.status.idle":"2022-01-09T22:31:22.284965Z","shell.execute_reply.started":"2022-01-09T22:30:24.579067Z","shell.execute_reply":"2022-01-09T22:31:22.284236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():    \n    pretrained_model = tf.keras.applications.inception_v3.InceptionV3(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model.trainable = False # tramsfer learning\n    \n    inception_model = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n        \ninception_model.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nhistorical_inception = inception_model.fit(train_dataset,\n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS)\n","metadata":{"execution":{"iopub.status.busy":"2022-01-09T22:31:22.286967Z","iopub.execute_input":"2022-01-09T22:31:22.287247Z","iopub.status.idle":"2022-01-09T22:32:17.551272Z","shell.execute_reply.started":"2022-01-09T22:31:22.287209Z","shell.execute_reply":"2022-01-09T22:32:17.550380Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"models = [model, xception_model, inception_model]\nmodel_input = tf.keras.Input(shape=(192, 192, 3))\nmodel_outputs = [model(model_input) for model in models]\nensemble_output = tf.keras.layers.Average()(model_outputs)\nensemble_model = tf.keras.Model(inputs=model_input, outputs=ensemble_output)\nensemble_model.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nensemble_historical = ensemble_model.fit(train_dataset, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS)","metadata":{"execution":{"iopub.status.busy":"2022-01-09T22:32:17.553102Z","iopub.execute_input":"2022-01-09T22:32:17.553465Z","iopub.status.idle":"2022-01-09T22:33:41.436840Z","shell.execute_reply.started":"2022-01-09T22:32:17.553425Z","shell.execute_reply":"2022-01-09T22:33:41.436038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Compute your predictions on the test set!\n\nThis will create a file that can be submitted to the competition.","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import f1_score, precision_score\ndef get_accuracy(model_name, model, validation_dataset):\n    probabilities = model.predict(x = validation_dataset)\n    predictions = np.argmax(probabilities, axis=-1)\n    true_classes = np.concatenate([true_classes for x, true_classes in validation_dataset], axis=0)\n    f_score = f1_score(\n        true_classes,\n        predictions,\n        labels=range(104),\n        average='macro',\n    )\n    print(model_name + \" macro f-score: \" + str(f_score))\n    score = (true_classes == predictions).sum() / len(true_classes)\n    print(model_name + \" accuracy: \" + str(score))\n    \nget_accuracy(\"Our Model\",model, val_dataset)\nget_accuracy(\"Inception Model\",inception_model, val_dataset)\nget_accuracy(\"Xception Model\",xception_model, val_dataset)\nget_accuracy(\"Ensemble Model\",ensemble_model, val_dataset)","metadata":{"execution":{"iopub.status.busy":"2022-01-09T22:33:41.438741Z","iopub.execute_input":"2022-01-09T22:33:41.439428Z","iopub.status.idle":"2022-01-09T22:34:16.399244Z","shell.execute_reply.started":"2022-01-09T22:33:41.439386Z","shell.execute_reply":"2022-01-09T22:34:16.396619Z"},"trusted":true},"execution_count":null,"outputs":[]}]}