{"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":"**[Click here for the training notebook](https://www.kaggle.com/xhlulu/ranzcr-efficientnet-b7-tpu-training)**\n\n**[Click here for updated discussions](https://www.kaggle.com/c/ranzcr-clip-catheter-line-classification/discussion/204950)**\n\nThis is the submission notebook for the EfficientNet model trained on TPU using Keras.","metadata":{}},{"cell_type":"code","source":"#!pip install /kaggle/input/kerasapplications -q\n#!pip install /kaggle/input/efficientnet-keras-source-code/ -q --no-deps","metadata":{"execution":{"iopub.status.busy":"2022-09-23T23:45:59.704156Z","iopub.execute_input":"2022-09-23T23:45:59.704498Z","iopub.status.idle":"2022-09-23T23:45:59.711054Z","shell.execute_reply.started":"2022-09-23T23:45:59.704465Z","shell.execute_reply":"2022-09-23T23:45:59.709476Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\n\n#import efficientnet.tfkeras as efn\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-09-23T23:45:59.715462Z","iopub.execute_input":"2022-09-23T23:45:59.716206Z","iopub.status.idle":"2022-09-23T23:46:04.609627Z","shell.execute_reply.started":"2022-09-23T23:45:59.716113Z","shell.execute_reply":"2022-09-23T23:46:04.608858Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Unhide below to see helper functions:","metadata":{}},{"cell_type":"code","source":"def auto_select_accelerator():\n    try:\n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n        tf.config.experimental_connect_to_cluster(tpu)\n        tf.tpu.experimental.initialize_tpu_system(tpu)\n        strategy = tf.distribute.experimental.TPUStrategy(tpu)\n        print(\"Running on TPU:\", tpu.master())\n    except ValueError:\n        strategy = tf.distribute.get_strategy()\n    print(f\"Running on {strategy.num_replicas_in_sync} replicas\")\n    \n    return strategy\n\n\ndef build_decoder(with_labels=True, target_size=(300, 300), ext='jpg'):\n    def decode(path):\n        file_bytes = tf.io.read_file(path)\n        if ext == 'png':\n            img = tf.image.decode_png(file_bytes, channels=3)\n        elif ext in ['jpg', 'jpeg']:\n            img = tf.image.decode_jpeg(file_bytes, channels=3)\n        else:\n            raise ValueError(\"Image extension not supported\")\n\n        img = tf.cast(img, tf.float32) / 255.0\n        img = tf.image.resize(img, target_size)\n\n        return img\n    \n    def decode_with_labels(path, label):\n        return decode(path), label\n    \n    return decode_with_labels if with_labels else decode\n\n\ndef build_augmenter(with_labels=True):\n    def augment(img):\n        img = tf.image.random_flip_left_right(img)\n        img = tf.image.random_flip_up_down(img)\n        return img\n    \n    def augment_with_labels(img, label):\n        return augment(img), label\n    \n    return augment_with_labels if with_labels else augment\n\n\ndef build_dataset(paths, labels=None, bsize=32, cache=True,\n                  decode_fn=None, augment_fn=None,\n                  augment=True, repeat=True, shuffle=1024, \n                  cache_dir=\"\"):\n    if cache_dir != \"\" and cache is True:\n        os.makedirs(cache_dir, exist_ok=True)\n    \n    if decode_fn is None:\n        decode_fn = build_decoder(labels is not None)\n    \n    if augment_fn is None:\n        augment_fn = build_augmenter(labels is not None)\n    \n    AUTO = tf.data.experimental.AUTOTUNE\n    slices = paths if labels is None else (paths, labels)\n    \n    dset = tf.data.Dataset.from_tensor_slices(slices)\n    dset = dset.map(decode_fn, num_parallel_calls=AUTO)\n    dset = dset.cache(cache_dir) if cache else dset\n    dset = dset.map(augment_fn, num_parallel_calls=AUTO) if augment else dset\n    dset = dset.repeat() if repeat else dset\n    dset = dset.shuffle(shuffle) if shuffle else dset\n    dset = dset.batch(bsize).prefetch(AUTO)\n    \n    return dset","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_kg_hide-output":false,"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-09-23T23:46:04.611771Z","iopub.execute_input":"2022-09-23T23:46:04.612149Z","iopub.status.idle":"2022-09-23T23:46:04.630886Z","shell.execute_reply.started":"2022-09-23T23:46:04.612109Z","shell.execute_reply":"2022-09-23T23:46:04.630032Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"COMPETITION_NAME = \"rsna-2022-cervical-spine-fracture-detection\"\nstrategy = auto_select_accelerator()\nBATCH_SIZE = strategy.num_replicas_in_sync * 16","metadata":{"execution":{"iopub.status.busy":"2022-09-23T23:46:04.632565Z","iopub.execute_input":"2022-09-23T23:46:04.633172Z","iopub.status.idle":"2022-09-23T23:46:04.651844Z","shell.execute_reply.started":"2022-09-23T23:46:04.633132Z","shell.execute_reply":"2022-09-23T23:46:04.650745Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_paths[0]","metadata":{"execution":{"iopub.status.busy":"2022-09-23T23:49:38.807038Z","iopub.execute_input":"2022-09-23T23:49:38.807366Z","iopub.status.idle":"2022-09-23T23:49:38.812549Z","shell.execute_reply.started":"2022-09-23T23:49:38.807331Z","shell.execute_reply":"2022-09-23T23:49:38.811569Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMSIZE = (224, 240, 260, 300, 380, 456, 528, 600)\n\nload_dir = f\"/kaggle/input/{COMPETITION_NAME}/\"\nsub_df = pd.read_csv(load_dir + 'test.csv')\ntest_paths = load_dir + \"test/\" + sub_df['row_id'] + '.jpg'\n\n# Get the multi-labels\nlabel_cols = sub_df.columns[1:]\n\ntest_decoder = build_decoder(with_labels=False, target_size=(IMSIZE[7], IMSIZE[7]))\ndtest = build_dataset(\n    test_paths, bsize=BATCH_SIZE, repeat=False, \n    shuffle=False, augment=False, cache=False,\n    decode_fn=test_decoder\n)","metadata":{"execution":{"iopub.status.busy":"2022-09-23T23:48:50.549314Z","iopub.execute_input":"2022-09-23T23:48:50.549655Z","iopub.status.idle":"2022-09-23T23:48:52.822365Z","shell.execute_reply.started":"2022-09-23T23:48:50.549622Z","shell.execute_reply":"2022-09-23T23:48:52.821413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Load model and submit","metadata":{}},{"cell_type":"code","source":"with strategy.scope():\n    model = tf.keras.models.load_model(\n        '../input/ranzcr-efficientnet-tpu-training/model.h5'\n    )\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-09-23T23:46:04.966657Z","iopub.status.idle":"2022-09-23T23:46:04.967124Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub_df[label_cols] = model.predict(dtest, verbose=1)\nsub_df.to_csv('submission.csv', index=False)\n\nsub_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-09-23T23:46:04.970388Z","iopub.status.idle":"2022-09-23T23:46:04.971122Z"},"trusted":true},"execution_count":null,"outputs":[]}]}