{"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\n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2023-03-01T04:00:24.109846Z","iopub.execute_input":"2023-03-01T04:00:24.110207Z","iopub.status.idle":"2023-03-01T04:00:29.220045Z","shell.execute_reply.started":"2023-03-01T04:00:24.110101Z","shell.execute_reply":"2023-03-01T04:00:29.218961Z"},"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":"2023-03-01T04:00:29.221977Z","iopub.execute_input":"2023-03-01T04:00:29.222221Z","iopub.status.idle":"2023-03-01T04:00:34.894904Z","shell.execute_reply.started":"2023-03-01T04:00:29.222194Z","shell.execute_reply":"2023-03-01T04:00:34.894059Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"","metadata":{"execution":{"iopub.status.busy":"2023-03-01T04:00:34.896267Z","iopub.execute_input":"2023-03-01T04:00:34.896502Z","iopub.status.idle":"2023-03-01T04:00:35.345164Z","shell.execute_reply.started":"2023-03-01T04:00:34.896475Z","shell.execute_reply":"2023-03-01T04:00:35.344385Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [331, 331] # at this size, a GPU will run out of memory. Use the TPU\nEPOCHS = 32\nBATCH_SIZE = 8 * strategy.num_replicas_in_sync\n\nNUM_TRAINING_IMAGES = 12753\nNUM_TEST_IMAGES = 7382\nNUM_VAL_IMAGES = 3712\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE","metadata":{"execution":{"iopub.status.busy":"2023-03-01T04:00:35.347604Z","iopub.execute_input":"2023-03-01T04:00:35.348198Z","iopub.status.idle":"2023-03-01T04:00:35.353506Z","shell.execute_reply.started":"2023-03-01T04:00:35.348149Z","shell.execute_reply":"2023-03-01T04:00:35.352552Z"},"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\n@tf.function\ndef augment(image, label):\n    image = tf.image.per_image_standardization(image)\n    image = tf.image.random_brightness(image, 0.2)\n    image = tf.image.random_contrast(image, 0, 0.2)\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_saturation(image, 0, 5)\n    return image, label\n\n@tf.function\ndef standardize(image, label):\n    image = tf.image.per_image_standardization(image)\n    return image, label\n\ndef get_training_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + f'/tfrecords-jpeg-{IMAGE_SIZE[0]}x{IMAGE_SIZE[0]}/train/*.tfrec'), labeled=True)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.map(augment, num_parallel_calls=tf.data.AUTOTUNE)\n    dataset = dataset.map(standardize, num_parallel_calls=tf.data.AUTOTUNE)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(tf.data.AUTOTUNE)\n    return dataset\n\ndef get_validation_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + f'/tfrecords-jpeg-{IMAGE_SIZE[0]}x{IMAGE_SIZE[0]}/val/*.tfrec'), labeled=True, ordered=False)\n    dataset = dataset.map(standardize, num_parallel_calls=tf.data.AUTOTUNE)\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 + f'/tfrecords-jpeg-{IMAGE_SIZE[0]}x{IMAGE_SIZE[0]}/test/*.tfrec'), labeled=False, ordered=ordered)\n    dataset = dataset.map(standardize, num_parallel_calls=tf.data.AUTOTUNE)\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":"2023-03-01T04:00:35.355052Z","iopub.execute_input":"2023-03-01T04:00:35.355417Z","iopub.status.idle":"2023-03-01T04:00:35.813170Z","shell.execute_reply.started":"2023-03-01T04:00:35.355377Z","shell.execute_reply":"2023-03-01T04:00:35.812268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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#     pretrained_model.trainable = False # transfer learning\n    \n#     model = tf.keras.Sequential([\n#         pretrained_model,\n#         tf.keras.layers.GlobalAveragePooling2D(),\n#         tf.keras.layers.Dense(104, activation='softmax')\n#     ])\nwith strategy.scope():    \n    #vgg16 = tf.keras.applications.VGG16(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    resnet50 = tf.keras.applications.ResNet50(include_top=False, input_shape=[*IMAGE_SIZE, 3])\n    \n    model = tf.keras.Sequential([\n        resnet50,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n\n        ","metadata":{"execution":{"iopub.status.busy":"2023-03-01T04:00:35.814622Z","iopub.execute_input":"2023-03-01T04:00:35.814915Z","iopub.status.idle":"2023-03-01T04:00:48.161596Z","shell.execute_reply.started":"2023-03-01T04:00:35.814877Z","shell.execute_reply":"2023-03-01T04:00:48.160886Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    model.compile(\n        optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),\n        loss = tf.keras.losses.SparseCategoricalCrossentropy(),\n        metrics=[tf.keras.metrics.SparseCategoricalAccuracy()],\n        steps_per_execution = 50\n    )","metadata":{"execution":{"iopub.status.busy":"2023-03-01T04:00:48.162897Z","iopub.execute_input":"2023-03-01T04:00:48.163210Z","iopub.status.idle":"2023-03-01T04:00:48.225370Z","shell.execute_reply.started":"2023-03-01T04:00:48.163172Z","shell.execute_reply":"2023-03-01T04:00:48.224505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)\nlearning_callback = tf.keras.callbacks.ReduceLROnPlateau(verbose=1, patience=3)\n\nhistorical = model.fit(training_dataset, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS, \n          validation_data=validation_dataset,\n          validation_steps=NUM_VAL_IMAGES // BATCH_SIZE,\n          callbacks=[learning_callback]\n          )","metadata":{"execution":{"iopub.status.busy":"2023-03-01T04:00:48.226387Z","iopub.execute_input":"2023-03-01T04:00:48.226621Z","iopub.status.idle":"2023-03-01T04:16:25.025702Z","shell.execute_reply.started":"2023-03-01T04:00:48.226593Z","shell.execute_reply":"2023-03-01T04:16:25.024654Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nloss_values = historical.history['loss']\nval_loss_values = historical.history['val_loss']\nepochs = range(1, len(loss_values)+1)\n\nplt.plot(epochs, loss_values, label='Training Loss')\nplt.plot(epochs, val_loss_values, label='Validation Loss')\n\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-03-01T04:16:25.027127Z","iopub.execute_input":"2023-03-01T04:16:25.027457Z","iopub.status.idle":"2023-03-01T04:16:25.271980Z","shell.execute_reply.started":"2023-03-01T04:16:25.027419Z","shell.execute_reply":"2023-03-01T04:16:25.271100Z"},"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":"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, steps=NUM_TEST_IMAGES // BATCH_SIZE + 1)\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":"2023-03-01T04:16:25.274282Z","iopub.execute_input":"2023-03-01T04:16:25.274521Z","iopub.status.idle":"2023-03-01T04:17:15.902176Z","shell.execute_reply.started":"2023-03-01T04:16:25.274493Z","shell.execute_reply":"2023-03-01T04:17:15.901203Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}