{"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":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-01-17T14:39:04.512894Z","iopub.execute_input":"2022-01-17T14:39:04.513721Z","iopub.status.idle":"2022-01-17T14:39:04.736802Z","shell.execute_reply.started":"2022-01-17T14:39:04.513596Z","shell.execute_reply":"2022-01-17T14:39:04.736098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom kaggle_datasets import KaggleDatasets\nimport numpy as np\n","metadata":{"execution":{"iopub.status.busy":"2022-01-17T14:39:04.738672Z","iopub.execute_input":"2022-01-17T14:39:04.738920Z","iopub.status.idle":"2022-01-17T14:39:09.137847Z","shell.execute_reply.started":"2022-01-17T14:39:04.738886Z","shell.execute_reply":"2022-01-17T14:39:09.137101Z"},"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":"2022-01-17T14:39:09.139061Z","iopub.execute_input":"2022-01-17T14:39:09.139316Z","iopub.status.idle":"2022-01-17T14:39:09.151453Z","shell.execute_reply.started":"2022-01-17T14:39:09.139285Z","shell.execute_reply":"2022-01-17T14:39:09.150778Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path()#Google cloud storage bucket path","metadata":{"execution":{"iopub.status.busy":"2022-01-17T14:39:09.154749Z","iopub.execute_input":"2022-01-17T14:39:09.154933Z","iopub.status.idle":"2022-01-17T14:39:09.673203Z","shell.execute_reply.started":"2022-01-17T14:39:09.154912Z","shell.execute_reply":"2022-01-17T14:39:09.672492Z"},"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 = 20\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","metadata":{"execution":{"iopub.status.busy":"2022-01-17T14:39:09.674391Z","iopub.execute_input":"2022-01-17T14:39:09.674648Z","iopub.status.idle":"2022-01-17T14:39:09.679031Z","shell.execute_reply.started":"2022-01-17T14:39:09.674618Z","shell.execute_reply":"2022-01-17T14:39:09.677875Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\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    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()\n","metadata":{"execution":{"iopub.status.busy":"2022-01-17T14:39:09.680382Z","iopub.execute_input":"2022-01-17T14:39:09.680899Z","iopub.status.idle":"2022-01-17T14:39:12.345846Z","shell.execute_reply.started":"2022-01-17T14:39:09.680861Z","shell.execute_reply":"2022-01-17T14:39:12.345156Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers.experimental import preprocessing\n\nwith strategy.scope():\n    model = keras.Sequential([\n        layers.InputLayer(input_shape = [192, 192, 3]),\n        #augmentation\n        preprocessing.RandomFlip('horizontal'),\n        preprocessing.RandomFlip('vertical'),\n        preprocessing.RandomWidth(factor = 0.15),\n        preprocessing.RandomRotation(factor = 0.20),\n        preprocessing.RandomTranslation(height_factor = 0.1, width_factor = 0.1),\n        #block1\n        layers.Conv2D(filters = 32, kernel_size = 3, activation = 'relu',  padding ='SAME'),\n        layers.MaxPool2D(),\n        #block2\n        layers.BatchNormalization(renorm = True),\n        layers.Conv2D(filters = 64, kernel_size = 3, activation = 'relu', padding = 'SAME'),\n        layers.Conv2D(filters = 64, kernel_size = 3, activation = 'relu', padding = 'SAME'),\n        layers.MaxPool2D(),\n        #block3\n        layers.BatchNormalization(renorm = True),\n        layers.Conv2D(filters = 128, kernel_size = 3, activation = 'relu', padding = 'SAME'),\n        layers.Conv2D(filters = 128, kernel_size = 3, activation = 'relu', padding = 'SAME'),\n        layers.Conv2D(filters = 128, kernel_size = 3, activation = 'relu', padding = 'SAME'),\n        layers.MaxPool2D(),\n        #block4\n        layers.BatchNormalization(renorm = True),\n        layers.Conv2D(filters = 256, kernel_size = 3, activation = 'relu', padding = 'SAME'),\n        layers.Conv2D(filters = 256, kernel_size = 3, activation = 'relu', padding = 'SAME'),\n        layers.Conv2D(filters = 256, kernel_size = 3, activation = 'relu', padding = 'SAME'),\n        layers.Conv2D(filters = 256, kernel_size = 3, activation = 'relu', padding = 'SAME'),\n        layers.MaxPool2D(),\n        #headblock\n        layers.BatchNormalization(renorm = True),\n        layers.GlobalAveragePooling2D(),\n        layers.Dense(104, activation = 'softmax'),\n    ])\n    \nmodel.compile(\n    optimizer = 'adam', \n    loss = 'sparse_categorical_crossentropy',\n    metrics = ['sparse_categorical_accuracy']\n)\n\nhistory = model.fit( training_dataset,\n    steps_per_epoch = STEPS_PER_EPOCH,\n    epochs = EPOCHS,\n    validation_data = validation_dataset\n)","metadata":{"execution":{"iopub.status.busy":"2022-01-17T14:39:12.347111Z","iopub.execute_input":"2022-01-17T14:39:12.347347Z","iopub.status.idle":"2022-01-17T14:55:43.589131Z","shell.execute_reply.started":"2022-01-17T14:39:12.347305Z","shell.execute_reply":"2022-01-17T14:55:43.588308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\ndf = pd.DataFrame(history.history)\ndf.loc[:, ['loss', 'val_loss']].plot()\ndf.loc[:,['sparse_categorical_accuracy', 'val_sparse_categorical_accuracy']].plot()","metadata":{"execution":{"iopub.status.busy":"2022-01-17T14:55:43.590853Z","iopub.execute_input":"2022-01-17T14:55:43.591113Z","iopub.status.idle":"2022-01-17T14:55:44.081804Z","shell.execute_reply.started":"2022-01-17T14:55:43.591077Z","shell.execute_reply":"2022-01-17T14:55:44.080901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}