{"cells":[{"metadata":{"_uuid":"0990e1b1-6c60-4193-a3b6-5ebf7d3d9f1e","_cell_guid":"0826a5ac-3282-4dfa-81cb-f3ee8711b78d","trusted":true},"cell_type":"markdown","source":"# A CNN Aproach For Classification of Petals to Metal \n(Edited Version of the [tutorial.](https://www.kaggle.com/philculliton/a-simple-petals-tf-2-2-notebook))"},{"metadata":{"_uuid":"97641606-f354-461e-8a34-728de155e9a7","_cell_guid":"0aadd682-57ef-4f50-8419-91636d7412a3","trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom kaggle_datasets import KaggleDatasets\nimport numpy as np\n\nprint(\"Tensorflow version \" + tf.__version__)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"04385c5b-4e29-42eb-8b68-8d1cc4c6a643","_cell_guid":"bc5db1d3-e9b4-43d7-8d94-ea5a6329edf3","trusted":true},"cell_type":"markdown","source":"# Detect my accelerator"},{"metadata":{"_uuid":"01bae2f9-cdf6-44a5-8e80-fe8be179e864","_cell_guid":"e8bc2129-c67a-44e9-a1e4-4b2bf237ccc8","trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d9beae67-337f-4353-9bb6-2c28b0e08061","_cell_guid":"75d20c46-edba-46d3-9fb8-fd4ae885065b","trusted":true},"cell_type":"markdown","source":"# Get my data path"},{"metadata":{"_uuid":"d6bd2e4a-bdb8-4169-9938-7f72df4bb566","_cell_guid":"c4429b8e-235c-405a-aae2-a7b01429943d","trusted":true},"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"aaa4011e-d419-4471-ac8e-476f6bac1bd8","_cell_guid":"fae6039d-a02a-4b10-bf58-c4fe4037e8b5","trusted":true},"cell_type":"markdown","source":"# Set some parameters"},{"metadata":{"_uuid":"9a469886-0132-4eac-af2d-68fe8b85731b","_cell_guid":"acbb7744-56e6-4094-82b6-fdc0b58c1224","trusted":true},"cell_type":"code","source":"IMAGE_SIZE = [512, 512] # 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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"64ff63b3-e4c5-4f7d-bdf4-c9690ffb6674","_cell_guid":"1b391318-a7ab-488a-afd2-351291ffd69c","trusted":true},"cell_type":"markdown","source":"# Load my data\nThis data is loaded from Kaggle and automatically sharded to maximize parallelization."},{"metadata":{"_uuid":"9e4bdd10-c4b2-48eb-8d93-7f4576b464a2","_cell_guid":"e0ce0b99-eee7-4e6f-a31e-517337c5278c","trusted":true},"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.image.resize(image, IMAGE_SIZE)\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    print(label)\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    \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 + \n                                            '/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 + \n                                            '/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 + \n                                            '/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()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"6f69cfbd-34c6-421d-89d9-86d6a74c00a3","_cell_guid":"80ddd240-8fbc-441b-b2ac-6f908cb1ca87","trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"a474d430-8443-41b1-9b66-7119f7c388fc","_cell_guid":"7690fb54-d587-4bf2-aa54-0ec0aa6e5ef4","trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"47699eca-df7f-483c-a1b1-9710478d561f","_cell_guid":"dfa8061d-7b3d-4ed8-b098-35378ffd0e5d","trusted":true},"cell_type":"markdown","source":"# Build a model on TPU (or GPU, or CPU...) with Tensorflow 2.1!\nI tried to work with different architecture and found that ResNet is promising for me."},{"metadata":{"_uuid":"3a077daf-1667-4bda-9d43-3cf4ab1d0079","_cell_guid":"f6145f89-90fb-49b4-ad35-60549c8556a1","trusted":true},"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, Dense, Dropout, MaxPooling2D, Input, Flatten, BatchNormalization\n\n# with strategy.scope():    \n#     pretrained_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False ,\n# input_shape=[*IMAGE_SIZE, 3])\n#     pretrained_model.trainable = True # transfer learning\n    \n#     model = tf.keras.Sequential([\n#         pretrained_model,\n#         tf.keras.layers.GlobalAveragePooling2D(),\n#         tf.keras.layers.Dense(256, activation='relu'),\n#         tf.keras.layers.Dropout(0.25),\n#         tf.keras.layers.Dense(104, activation='softmax')\n#     ])\n\nwith strategy.scope(): \n    pretrained_model = tf.keras.applications.ResNet152V2(\n        weights='imagenet',\n        include_top=False ,\n        input_shape=[*IMAGE_SIZE, 3]\n    )\n    pretrained_model.trainable = False\n    \n    model = tf.keras.Sequential([\n        # To a base pretrained on ImageNet to extract features from images...\n        pretrained_model,\n        # ... attach a new head to act as a classifier.\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(512, activation='relu'),\n        tf.keras.layers.Dense(256, activation='relu'),\n        tf.keras.layers.Dropout(0.5),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n    model.compile(\n        optimizer='adam',\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy'],\n    )\n\nmodel.summary()\n\n\ndef get_model(IMAGE_SIZE):\n    model = Sequential()\n    model.add(Conv2D(32, (3, 3), activation = 'relu', input_shape = (IMAGE_SIZE[0], IMAGE_SIZE[1], 3), data_format = 'channels_last'))\n    model.add(Conv2D(32, (3, 3), activation='relu'))\n#     model.add(Conv2D(32, (3, 3), activation='relu'))\n#     model.add(BatchNormalization())\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n\n    model.add(Conv2D(64, (3, 3), activation='relu'))\n    model.add(Conv2D(64, (3, 3), activation='relu'))\n#     model.add(Conv2D(64, (3, 3), activation='relu'))\n#     model.add(BatchNormalization())\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    \n    model.add(Conv2D(128, (3, 3), activation='relu'))\n    model.add(Conv2D(128, (3, 3), activation='relu'))\n#     model.add(Conv2D(128, (5, 5), activation='relu'))\n#     model.add(BatchNormalization())\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    \n    model.add(Conv2D(256, (5, 5), activation='relu'))\n    model.add(Conv2D(256, (5, 5), activation='relu'))\n#     model.add(Conv2D(256, (5, 5), activation='relu'))\n#     model.add(BatchNormalization())\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    \n    model.add(Flatten())\n    model.add(Dense(512, activation='relu'))\n    model.add(Dense(256, activation='relu'))\n    model.add(Dropout(0.2))\n    model.add(Dense(104, activation='softmax'))\n\n    model.summary()\n    return model\n\n# with strategy.scope():\n#     model = get_model(IMAGE_SIZE)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"099ec571-1be6-4099-b8a3-472dc87df304","_cell_guid":"021cb8bc-ef21-41f9-bf09-a9bac209c88e","trusted":true},"cell_type":"code","source":"# model.compile(\n#     optimizer='nadam',\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=15, \n          validation_data=validation_dataset)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"eee9179a-8ce1-4ba8-9688-fb261320d4be","_cell_guid":"e08baf0b-4179-4bff-af27-162f380466bb","trusted":true},"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":{"_uuid":"2d238f9d-37b7-4765-8581-330e22fe51b1","_cell_guid":"0abfebcb-61bc-40d6-94af-1af3a9a5b1e8","trusted":true},"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='')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"c61d7b00-17e8-425e-9a1d-f98151989566","_cell_guid":"800e4a03-407d-46c1-86cf-ea2dd846c2bb","trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}