{"cells":[{"metadata":{"_cell_guid":"81da3795-73d5-44ba-8796-d0f2ba1bb207","_uuid":"cb13f157-51a3-4351-9fb2-7bdf171656d9","trusted":false},"cell_type":"code","source":"!pip install -q efficientnet","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"968de18c-bb29-4812-846d-f02563c968a6","_uuid":"27b62702-e536-4194-ae10-b8a2d0cbaebd","trusted":false},"cell_type":"code","source":"import os\nimport re\n\nimport numpy as np\nimport pandas as pd\nimport math\n\nfrom matplotlib import pyplot as plt\n\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\nimport tensorflow.keras.layers as L\n\nimport efficientnet.tfkeras as efn\n#from tensorflow.keras.applications import Xception\nfrom kaggle_datasets import KaggleDatasets","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"c9298357-6972-4621-ad54-f6ab5d7244e2","_uuid":"14962c57-df8f-44f5-9aec-3c1d9e991b9c","trusted":false},"cell_type":"code","source":"import random\nSEED = 8888\nos.environ['PYTHONHASHSEED']=str(SEED)\ntf.random.set_seed(SEED)\nnp.random.seed(SEED)\nrandom.seed(SEED)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"d44094e0-dfd7-4a15-b525-ad428a48d9c8","_uuid":"3bbc607c-f501-4dbd-9ec8-165eef5e9d5a"},"cell_type":"markdown","source":"## TPU Strategy and other configs","execution_count":null},{"metadata":{"_cell_guid":"ef5644b0-1707-4d15-a56f-00a7bfb62600","_uuid":"05b41250-c7ef-4b36-b30b-ef0664f24a57","trusted":false},"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy\ntry:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is\n    # set: this is always the case on Kaggle.\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    # Default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"a66ab59a-c399-4e8b-8cc9-022a62defe34","_uuid":"c8199412-45ab-4fd3-bc23-24466f456504","trusted":false},"cell_type":"code","source":"# For tf.dataset\nAUTO = tf.data.experimental.AUTOTUNE\n\n# Data access\nGCS_PATH = KaggleDatasets().get_gcs_path('siim-isic-melanoma-classification')\n\n# Configuration\nEPOCHS = 15\nBATCH_SIZE = 8 * strategy.num_replicas_in_sync\nIMAGE_SIZE = [1024, 1024]","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"958691ec-4ec4-432f-af73-fee644c90413","_uuid":"b9f71772-3699-4c7a-868f-3b62f31134d0"},"cell_type":"markdown","source":"## Load label and paths","execution_count":null},{"metadata":{"_cell_guid":"d7b28eaf-8c5c-459b-b14f-8abc6085b56d","_uuid":"c226c3c1-e38a-48b5-94b3-2cdcc2396550","trusted":false},"cell_type":"code","source":"def append_path(pre):\n    return np.vectorize(lambda file: os.path.join(GCS_DS_PATH, pre, file))","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"77c7269c-9765-4c3e-a6f5-3e872aa097f6","_uuid":"bbc39f0e-c4cb-4bbc-8642-badb5b85d5e1","trusted":false},"cell_type":"code","source":"sub = pd.read_csv('/kaggle/input/siim-isic-melanoma-classification/sample_submission.csv')\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/tfrecords/train*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/tfrecords/test*.tfrec')","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"a724b261-8b8f-4fb9-b844-8e22b40061d0","_uuid":"dfbe91ef-452f-403e-bcfb-0d360ed23656","trusted":false},"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        \"target\": 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    label = tf.cast(example['target'], 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        \"image_name\": 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['image_name']\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, num_parallel_reads=AUTO) # 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, num_parallel_calls=AUTO)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef data_augment(image, label):\n    # data augmentation. Thanks to the dataset.prefetch(AUTO) statement in the next function (below),\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 = tf.image.random_flip_left_right(image)\n    #image = tf.image.random_saturation(image, 0, 2)\n    return image, label   \n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\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.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint('Dataset: {} training images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_TEST_IMAGES))","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"3dc919e7-a921-4a0a-a353-dd7561017616","_uuid":"b55be276-0461-41de-9d1b-cb47c71525f6"},"cell_type":"markdown","source":"### Helper Functions","execution_count":null},{"metadata":{"_cell_guid":"ab439052-42a1-4fe5-af35-a7d3fbc09ab6","_uuid":"3a050e22-9c76-4709-a36f-fc4c2164b27d","trusted":false},"cell_type":"code","source":"def build_lrfn(lr_start=0.00001, lr_max=0.000075, \n               lr_min=0.000001, lr_rampup_epochs=20, \n               lr_sustain_epochs=0, lr_exp_decay=.8):\n    lr_max = lr_max * strategy.num_replicas_in_sync\n\n    def lrfn(epoch):\n        if epoch < lr_rampup_epochs:\n            lr = (lr_max - lr_start) / lr_rampup_epochs * epoch + lr_start\n        elif epoch < lr_rampup_epochs + lr_sustain_epochs:\n            lr = lr_max\n        else:\n            lr = (lr_max - lr_min) * lr_exp_decay**(epoch - lr_rampup_epochs - lr_sustain_epochs) + lr_min\n        return lr\n    \n    return lrfn","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"accbfdfd-54b7-4fc8-91d2-36204a533b26","_uuid":"8084e0f4-9750-420e-8fe7-d0ed0870ca4f"},"cell_type":"markdown","source":"### Load Model into TPU","execution_count":null},{"metadata":{"_cell_guid":"f27fc64d-68b0-4445-a974-000bd38a5dc7","_uuid":"482a4d0b-abe2-4bc2-9d17-07ff04fd003a","trusted":false},"cell_type":"code","source":" \nwith strategy.scope():\n        EfficientNet=efn.EfficientNetB3(\n            input_shape=(*IMAGE_SIZE, 3),\n            weights='imagenet',\n            include_top=False\n            )\n            \n\n\n        model11 = tf.keras.Sequential([\n                EfficientNet,\n                L.GlobalAveragePooling2D(),\n                L.Dense(1, activation='sigmoid')\n                    ])\n\n\nmodel11.compile(\n    optimizer='adam',\n    loss = 'binary_crossentropy',\n    metrics=['binary_crossentropy']\n)\nmodel11.summary()  \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"with strategy.scope():\n    enet = efn.EfficientNetB4(\n        input_shape=(*IMAGE_SIZE, 3),\n        weights='imagenet',\n        include_top=False\n    )\n\n    model12 = tf.keras.Sequential([\n        enet,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(1, activation='sigmoid')\n    ]) \n\nmodel12.compile(\n    optimizer='adam',\n    loss = 'binary_crossentropy',\n    metrics=['binary_crossentropy']\n)\nmodel12.summary()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"with strategy.scope():\n    enet = efn.EfficientNetB6(\n        input_shape=(*IMAGE_SIZE, 3),\n        weights='imagenet',\n        include_top=False\n    )\n\n    model14 = tf.keras.Sequential([\n        enet,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(1, activation='sigmoid')\n    ]) \n\nmodel14.compile(\n    optimizer='adam',\n    loss = 'binary_crossentropy',\n    metrics=['binary_crossentropy']\n)\n\nmodel14.summary()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"model11a = tf.keras.Sequential()\nfor layer in model11.layers[:-2]:\n    model11a.add(layer)\n    \nfor layer in model11a.layers:\n    layer.trainable = False\n    \nmodel22 = tf.keras.Sequential()\nfor layer in model12.layers[:-2]:\n    model22.add(layer)\nfor layer in model22.layers:\n    layer.trainable = False\n\nmodel44 = tf.keras.Sequential()\nfor layer in model14.layers[:-2]:\n    model44.add(layer)\nfor layer in model44.layers:\n    layer.trainable = False","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"with strategy.scope():\n    \n    x = tf.keras.Input(shape = (*IMAGE_SIZE, 3))\n    x1 = model11a(x)\n    x2 = model22(x)\n   # x3 = model33(x)\n    x4 = model44(x)\n    x5 = tf.keras.layers.concatenate([x1, x2, x4], axis = 3)\n    x6 = tf.keras.layers.GlobalAveragePooling2D()(x5)\n    x6 = tf.keras.layers.Dropout(0.75)(x6)\n    x6 = tf.keras.layers.Dense(1, activation='sigmoid')(x6)\n    out = tf.keras.Model(inputs = x, outputs = x6)\n\nout.compile(\n    optimizer='adam',\n    loss = 'binary_crossentropy',\n    metrics=['binary_crossentropy']\n)\n\nout.summary()","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"87a5d3a0-544a-46ea-9005-65477b2825e2","_uuid":"842c2155-0292-4bac-bf7e-2aae4c8b9a1b","trusted":false},"cell_type":"code","source":"train_dataset = get_training_dataset()","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"36617e4f-6445-4e94-a376-9869d6d1d33f","_uuid":"c2889c1e-c0e7-441c-8e9c-bb7412bb773c","trusted":false},"cell_type":"code","source":"lrfn = build_lrfn()\nlr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\n\nhistory = out.fit(\n    train_dataset, \n    epochs=EPOCHS, \n    callbacks=[lr_schedule],\n    steps_per_epoch=STEPS_PER_EPOCH\n    #validation_data=valid_dataset\n)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"c5d187e6-aed8-43b1-83ba-0a59186505d1","_uuid":"225efd5b-c7dc-46f7-a8a4-824b5a949899"},"cell_type":"markdown","source":"## Submission","execution_count":null},{"metadata":{"_cell_guid":"a5a43bd2-e22a-4a90-9538-cc695786d9b1","_uuid":"6d897025-09f8-43d1-82a0-39af8fff673b","trusted":false},"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = out.predict(test_images_ds)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"a4be65e2-7003-4df2-8c27-9a96cd00e234","_uuid":"e1adaa7f-6370-45c2-bc16-b72d1ae8a53a","trusted":false},"cell_type":"code","source":"print('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","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"fa28fba1-fa1f-43d4-8ef4-1769cc0e4974","_uuid":"6c6d0cf4-22a4-4778-84bb-a795eda1d886","trusted":false},"cell_type":"code","source":"pred_df = pd.DataFrame({'image_name': test_ids, 'target': np.concatenate(probabilities)})\npred_df.head()","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"16c991f6-e865-4413-9bf5-37649562b3c8","_uuid":"dee53697-ff41-442f-9d5f-341625021177","trusted":false},"cell_type":"code","source":"sub.tail()","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"9cd48082-2ce8-4901-ba16-4774434256e0","_uuid":"fbbecad7-3cfc-4c53-9984-2deb4081e7b3","trusted":false},"cell_type":"code","source":"del sub['target']\nsub = sub.merge(pred_df, on='image_name')\nsub.to_csv('submission.csv', index=False)\nsub.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"# serialize weights to HDF5\nout.save(\"efficientnets.h5\")\nprint(\"Saved model to disk\")","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}