{"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":"thanks to https://www.kaggle.com/sreevishnudamodaran/siim-effnetv2-l-cascadercnn-mmdetection-infer \n\nthanks to https://www.kaggle.com/h053473666/siim-cov19-efnb7-yolov5-infer \n\nthanks to https://www.kaggle.com/pvtien96/weights-of-yolov5-150-epochs","metadata":{}},{"cell_type":"code","source":"!conda install '/kaggle/input/pydicom-conda-helper/libjpeg-turbo-2.1.0-h7f98852_0.tar.bz2' -c conda-forge -y\n!conda install '/kaggle/input/pydicom-conda-helper/libgcc-ng-9.3.0-h2828fa1_19.tar.bz2' -c conda-forge -y\n!conda install '/kaggle/input/pydicom-conda-helper/gdcm-2.8.9-py37h500ead1_1.tar.bz2' -c conda-forge -y\n!conda install '/kaggle/input/pydicom-conda-helper/conda-4.10.1-py37h89c1867_0.tar.bz2' -c conda-forge -y\n!conda install '/kaggle/input/pydicom-conda-helper/certifi-2020.12.5-py37h89c1867_1.tar.bz2' -c conda-forge -y\n!conda install '/kaggle/input/pydicom-conda-helper/openssl-1.1.1k-h7f98852_0.tar.bz2' -c conda-forge -y","metadata":{"_kg_hide-output":true,"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-08-08T07:48:04.546289Z","iopub.execute_input":"2021-08-08T07:48:04.546767Z","iopub.status.idle":"2021-08-08T07:49:13.048638Z","shell.execute_reply.started":"2021-08-08T07:48:04.546684Z","shell.execute_reply":"2021-08-08T07:49:13.047503Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\n\nfrom PIL import Image\nimport pandas as pd\nfrom tqdm.auto import tqdm","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-08-08T07:49:13.053820Z","iopub.execute_input":"2021-08-08T07:49:13.056182Z","iopub.status.idle":"2021-08-08T07:49:13.072135Z","shell.execute_reply.started":"2021-08-08T07:49:13.056133Z","shell.execute_reply":"2021-08-08T07:49:13.071213Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/siim-covid19-detection/sample_submission.csv')\nif df.shape[0] == 2477:\n    fast_sub = True\n    fast_df = pd.DataFrame(([['00086460a852_study', 'negative 1 0 0 1 1'], \n                         ['000c9c05fd14_study', 'negative 1 0 0 1 1'], \n                         ['65761e66de9f_image', 'none 1 0 0 1 1'], \n                         ['51759b5579bc_image', 'none 1 0 0 1 1']]), \n                       columns=['id', 'PredictionString'])\nelse:\n    fast_sub = False\n","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:49:13.077614Z","iopub.execute_input":"2021-08-08T07:49:13.080218Z","iopub.status.idle":"2021-08-08T07:49:13.104966Z","shell.execute_reply.started":"2021-08-08T07:49:13.080177Z","shell.execute_reply":"2021-08-08T07:49:13.104207Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# .dcm to .png","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\n\ndef read_xray(path, voi_lut = True, fix_monochrome = True):\n    # Original from: https://www.kaggle.com/raddar/convert-dicom-to-np-array-the-correct-way\n    dicom = pydicom.read_file(path)\n    \n    # VOI LUT (if available by DICOM device) is used to transform raw DICOM data to \n    # \"human-friendly\" view\n    if voi_lut:\n        data = apply_voi_lut(dicom.pixel_array, dicom)\n    else:\n        data = dicom.pixel_array\n               \n    # depending on this value, X-ray may look inverted - fix that:\n    if fix_monochrome and dicom.PhotometricInterpretation == \"MONOCHROME1\":\n        data = np.amax(data) - data\n        \n    data = data - np.min(data)\n    data = data / np.max(data)\n    data = (data * 255).astype(np.uint8)\n        \n    return data","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:49:13.108837Z","iopub.execute_input":"2021-08-08T07:49:13.110873Z","iopub.status.idle":"2021-08-08T07:49:13.379418Z","shell.execute_reply.started":"2021-08-08T07:49:13.110836Z","shell.execute_reply":"2021-08-08T07:49:13.378450Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def resize(array, size, keep_ratio=False, resample=Image.LANCZOS):\n    # Original from: https://www.kaggle.com/xhlulu/vinbigdata-process-and-resize-to-image\n    im = Image.fromarray(array)\n    \n    if keep_ratio:\n        im.thumbnail((size, size), resample)\n    else:\n        im = im.resize((size, size), resample)\n    \n    return im","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:49:13.380846Z","iopub.execute_input":"2021-08-08T07:49:13.381475Z","iopub.status.idle":"2021-08-08T07:49:13.387989Z","shell.execute_reply.started":"2021-08-08T07:49:13.381420Z","shell.execute_reply":"2021-08-08T07:49:13.386903Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nsplit = 'test'\nsave_dir = f'/kaggle/tmp/{split}/'\n\nos.makedirs(save_dir, exist_ok=True)\n\nsave_dir_study1 = f'/kaggle/tmp/{split}/study1/'\nos.makedirs(save_dir_study1, exist_ok=True)\nif fast_sub:\n    xray = read_xray('/kaggle/input/siim-covid19-detection/train/00086460a852/9e8302230c91/65761e66de9f.dcm')\n    im = resize(xray, size=600)  \n    study = '00086460a852' + '_study.png'\n    im.save(os.path.join(save_dir_study1, study))\n    xray = read_xray('/kaggle/input/siim-covid19-detection/train/000c9c05fd14/e555410bd2cd/51759b5579bc.dcm')\n    im = resize(xray, size=600)  \n    study = '000c9c05fd14' + '_study.png'\n    im.save(os.path.join(save_dir_study1, study))\nelse:   \n    for dirname, _, filenames in tqdm(os.walk(f'/kaggle/input/siim-covid19-detection/{split}')):\n        for file in filenames:\n            # set keep_ratio=True to have original aspect ratio\n            xray = read_xray(os.path.join(dirname, file))\n            im = resize(xray, size=600)  \n            study = dirname.split('/')[-2] + '_study.png'\n            im.save(os.path.join(save_dir_study1, study))\n","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:49:13.389492Z","iopub.execute_input":"2021-08-08T07:49:13.389877Z","iopub.status.idle":"2021-08-08T07:49:15.097998Z","shell.execute_reply.started":"2021-08-08T07:49:13.389826Z","shell.execute_reply":"2021-08-08T07:49:15.097117Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"save_dir_study2 = f'/kaggle/tmp/{split}/study2/'\nos.makedirs(save_dir_study2, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:49:15.099487Z","iopub.execute_input":"2021-08-08T07:49:15.099866Z","iopub.status.idle":"2021-08-08T07:49:15.105743Z","shell.execute_reply.started":"2021-08-08T07:49:15.099830Z","shell.execute_reply":"2021-08-08T07:49:15.104778Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nif fast_sub:\n    xray = read_xray('/kaggle/input/siim-covid19-detection/train/00086460a852/9e8302230c91/65761e66de9f.dcm')\n    im = resize(xray, size=768)  \n    study = '00086460a852' + '_study.png'\n    im.save(os.path.join(save_dir_study2, study))\n    xray = read_xray('/kaggle/input/siim-covid19-detection/train/000c9c05fd14/e555410bd2cd/51759b5579bc.dcm')\n    im = resize(xray, size=768)  \n    study = '000c9c05fd14' + '_study.png'\n    im.save(os.path.join(save_dir_study2, study))\nelse:   \n    for dirname, _, filenames in tqdm(os.walk(f'/kaggle/input/siim-covid19-detection/{split}')):\n        for file in filenames:\n            # set keep_ratio=True to have original aspect ratio\n            xray = read_xray(os.path.join(dirname, file))\n            im = resize(xray, size=768)  \n            study = dirname.split('/')[-2] + '_study.png'\n            im.save(os.path.join(save_dir_study2, study))","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:49:15.109333Z","iopub.execute_input":"2021-08-08T07:49:15.109824Z","iopub.status.idle":"2021-08-08T07:49:15.736581Z","shell.execute_reply.started":"2021-08-08T07:49:15.109791Z","shell.execute_reply":"2021-08-08T07:49:15.735610Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_id = []\ndim0 = []\ndim1 = []\nsplits = []\nsave_dir_image = f'/kaggle/tmp/{split}/image/'\nos.makedirs(save_dir_image, exist_ok=True)\nif fast_sub:\n    xray = read_xray('/kaggle/input/siim-covid19-detection/train/00086460a852/9e8302230c91/65761e66de9f.dcm')\n    im = resize(xray, size=512)  \n    im.save(os.path.join(save_dir_image,'65761e66de9f_image.png'))\n    image_id.append('65761e66de9f.dcm'.replace('.dcm', ''))\n    dim0.append(xray.shape[0])\n    dim1.append(xray.shape[1])\n    splits.append(split)\n    xray = read_xray('/kaggle/input/siim-covid19-detection/train/000c9c05fd14/e555410bd2cd/51759b5579bc.dcm')\n    im = resize(xray, size=512)  \n    im.save(os.path.join(save_dir_image, '51759b5579bc_image.png'))\n    image_id.append('51759b5579bc.dcm'.replace('.dcm', ''))\n    dim0.append(xray.shape[0])\n    dim1.append(xray.shape[1])\n    splits.append(split)\nelse:\n    for dirname, _, filenames in tqdm(os.walk(f'/kaggle/input/siim-covid19-detection/{split}')):\n        for file in filenames:\n            # set keep_ratio=True to have original aspect ratio\n            xray = read_xray(os.path.join(dirname, file))\n            im = resize(xray, size=512)  \n            im.save(os.path.join(save_dir_image, file.replace('.dcm', '_image.png')))\n            image_id.append(file.replace('.dcm', ''))\n            dim0.append(xray.shape[0])\n            dim1.append(xray.shape[1])\n            splits.append(split)\nmeta = pd.DataFrame.from_dict({'image_id': image_id, 'dim0': dim0, 'dim1': dim1, 'split': splits})","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:49:15.738640Z","iopub.execute_input":"2021-08-08T07:49:15.739001Z","iopub.status.idle":"2021-08-08T07:49:16.134469Z","shell.execute_reply.started":"2021-08-08T07:49:15.738962Z","shell.execute_reply":"2021-08-08T07:49:16.133468Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# B7_study predict","metadata":{}},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd\nif fast_sub:\n    df = fast_df.copy()\nelse:\n    df = pd.read_csv('../input/siim-covid19-detection/sample_submission.csv')\nid_laststr_list  = []\nfor i in range(df.shape[0]):\n    id_laststr_list.append(df.loc[i,'id'][-1])\ndf['id_last_str'] = id_laststr_list\n\nstudy_len = df[df['id_last_str'] == 'y'].shape[0]","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:49:16.135911Z","iopub.execute_input":"2021-08-08T07:49:16.136453Z","iopub.status.idle":"2021-08-08T07:49:16.151636Z","shell.execute_reply.started":"2021-08-08T07:49:16.136415Z","shell.execute_reply":"2021-08-08T07:49:16.150418Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install /kaggle/input/kerasapplications -q\n!pip install /kaggle/input/efficientnet-keras-source-code/ -q --no-deps\n\nimport os\n\nimport efficientnet.tfkeras as efn\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\ndef 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\n\n#COMPETITION_NAME = \"siim-cov19-test-img512-study-600\"\nstrategy = auto_select_accelerator()\nBATCH_SIZE = strategy.num_replicas_in_sync * 16\n\n\nIMSIZE = (224, 240, 260, 300, 380, 456, 528, 600, 512, 768)\n\n#load_dir = f\"/kaggle/input/{COMPETITION_NAME}/\"\nif fast_sub:\n    sub_df_study1 = fast_df.copy()\nelse:\n    sub_df_study1 = pd.read_csv('../input/siim-covid19-detection/sample_submission.csv')\nsub_df_study1 = sub_df_study1[:study_len]\ntest_study1_paths = f'/kaggle/tmp/{split}/study1/' + sub_df_study1['id'] +'.png'\n\nsub_df_study1['negative'] = 0\nsub_df_study1['typical'] = 0\nsub_df_study1['indeterminate'] = 0\nsub_df_study1['atypical'] = 0\n\n\nlabel_cols = sub_df_study1.columns[2:]\n\ntest_decoder_study1 = build_decoder(with_labels=False, target_size=(IMSIZE[7], IMSIZE[7]), ext='png')\ndtest_study1 = build_dataset(\n    test_study1_paths, bsize=BATCH_SIZE, repeat=False, \n    shuffle=False, augment=False, cache=False,\n    decode_fn=test_decoder_study1\n)\n\n\n\n\n\n# with strategy.scope():\n    \n#     models_study1 = []\n    \n#     models0_study1 = tf.keras.models.load_model(\n#         '/kaggle/input/siim-covid19-efnb7-train-study/model0.h5'\n#     )\n#     models1_study1 = tf.keras.models.load_model(\n#         '/kaggle/input/siim-covid19-efnb7-train-study/model1.h5'\n#     )\n#     models2_study1 = tf.keras.models.load_model(\n#         '/kaggle/input/siim-covid19-efnb7-train-study/model2.h5'\n#     )\n#     models3_study1 = tf.keras.models.load_model(\n#         '/kaggle/input/siim-covid19-efnb7-train-study/model3.h5'\n#     )\n#     models4_study1 = tf.keras.models.load_model(\n#         '/kaggle/input/siim-covid19-efnb7-train-study/model4.h5'\n#     )\n    \n#     models_study1.append(models0_study1)\n#     models_study1.append(models1_study1)\n#     models_study1.append(models2_study1)\n#     models_study1.append(models3_study1)\n#     models_study1.append(models4_study1)\n\n    \n    \n    \n# sub_df_study1[label_cols] = sum([model.predict(dtest_study1, verbose=1) for model in models_study1]) / len(models_study1)\n\n# import gc\n\n# del models_study1\n# del models0_study1, models1_study1, models2_study1, models3_study1, models4_study1\n# del dtest_study1, test_decoder_study1\n# gc.collect()","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:49:16.153440Z","iopub.execute_input":"2021-08-08T07:49:16.153903Z","iopub.status.idle":"2021-08-08T07:49:34.957464Z","shell.execute_reply.started":"2021-08-08T07:49:16.153857Z","shell.execute_reply":"2021-08-08T07:49:34.956487Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# V2_study predict","metadata":{}},{"cell_type":"code","source":"import tensorflow_hub as tfhub\n\nif fast_sub:\n    sub_df_study2 = fast_df.copy()\nelse:\n    sub_df_study2 = pd.read_csv('../input/siim-covid19-detection/sample_submission.csv')\nsub_df_study2 = sub_df_study2[:study_len]\ntest_study2_paths = f'/kaggle/tmp/{split}/study2/' + sub_df_study2['id'] +'.png'\n\nsub_df_study2['negative'] = 0\nsub_df_study2['typical'] = 0\nsub_df_study2['indeterminate'] = 0\nsub_df_study2['atypical'] = 0\n\n\nlabel_cols = sub_df_study2.columns[2:]\n\ntest_decoder_study2 = build_decoder(with_labels=False, target_size=(IMSIZE[9], IMSIZE[9]), ext='png')\ndtest_study2 = build_dataset(\n    test_study2_paths, bsize=BATCH_SIZE, repeat=False, \n    shuffle=False, augment=False, cache=False,\n    decode_fn=test_decoder_study2\n)\n\nMODEL_PATH = '../input/siim-effnetv2-keras-study-train-tpu-cv0-805'\nMODEL_ARCH = 'efficientnetv2-l-21k-ft1k'\nhub_type = 'feature_vector'\nMODEL_ARCH_PATH = f'/kaggle/input/efficientnetv2-tfhub-weight-files/tfhub_models/{MODEL_ARCH}/{hub_type}'\nclass KerasLayerWrapper(tfhub.KerasLayer):\n    def __init__(self, handle, **kwargs):\n        handle = tfhub.KerasLayer(tfhub.load(MODEL_ARCH_PATH))\n        super().__init__(handle, **kwargs)\n        \nwith strategy.scope():\n    models_study2 = []\n    \n    models0_study2 = tf.keras.models.load_model(f'{MODEL_PATH}/model0.h5',\n                                         custom_objects={'KerasLayer': KerasLayerWrapper})\n    \n    models1_study2 = tf.keras.models.load_model(f'{MODEL_PATH}/model1.h5',\n                                         custom_objects={'KerasLayer': KerasLayerWrapper})\n    \n    models2_study2 = tf.keras.models.load_model(f'{MODEL_PATH}/model2.h5',\n                                         custom_objects={'KerasLayer': KerasLayerWrapper})\n    \n    models3_study2 = tf.keras.models.load_model(f'{MODEL_PATH}/model3.h5',\n                                         custom_objects={'KerasLayer': KerasLayerWrapper})\n    \n    models4_study2 = tf.keras.models.load_model(f'{MODEL_PATH}/model4.h5',\n                                         custom_objects={'KerasLayer': KerasLayerWrapper})\n    \n    models_study2.append(models0_study2)\n    models_study2.append(models1_study2)\n    models_study2.append(models2_study2)\n    models_study2.append(models3_study2)\n    models_study2.append(models4_study2)\n    \nsub_df_study2[label_cols] = sum([model.predict(dtest_study2, verbose=1) for model in models_study2]) / len(models_study2)","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:49:34.958981Z","iopub.execute_input":"2021-08-08T07:49:34.959571Z","iopub.status.idle":"2021-08-08T07:53:12.027213Z","shell.execute_reply.started":"2021-08-08T07:49:34.959529Z","shell.execute_reply":"2021-08-08T07:53:12.026367Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import gc\ndel models_study2\ndel models0_study2, models1_study2, models2_study2, models3_study2, models4_study2\ndel dtest_study2, test_decoder_study2\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:53:12.028802Z","iopub.execute_input":"2021-08-08T07:53:12.029155Z","iopub.status.idle":"2021-08-08T07:53:24.944071Z","shell.execute_reply.started":"2021-08-08T07:53:12.029112Z","shell.execute_reply":"2021-08-08T07:53:24.943269Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub_df_study1.columns =['id', 'PredictionString1', 'negative', 'typical', 'indeterminate', 'atypical']\nsub_df_study2.columns =['id', 'PredictionString1', 'negative', 'typical', 'indeterminate', 'atypical']\ndf = pd.merge(df, sub_df_study2, on = 'id', how = 'left')","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:53:24.949450Z","iopub.execute_input":"2021-08-08T07:53:24.949713Z","iopub.status.idle":"2021-08-08T07:53:24.976839Z","shell.execute_reply.started":"2021-08-08T07:53:24.949687Z","shell.execute_reply":"2021-08-08T07:53:24.976095Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# study string","metadata":{}},{"cell_type":"code","source":"'''\nfor i in range(study_len):\n    negative = sub_df_study2.loc[i,'negative']\n    typical = sub_df_study2.loc[i,'typical']\n    indeterminate = sub_df_study2.loc[i,'indeterminate']\n    atypical = sub_df_study2.loc[i,'atypical']\n    df.loc[i, 'PredictionString'] = f'negative {negative} 0 0 1 1 typical {typical} 0 0 1 1 indeterminate {indeterminate} 0 0 1 1 atypical {atypical} 0 0 1 1'\n'''","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:53:24.978242Z","iopub.execute_input":"2021-08-08T07:53:24.978739Z","iopub.status.idle":"2021-08-08T07:53:24.984928Z","shell.execute_reply.started":"2021-08-08T07:53:24.978700Z","shell.execute_reply":"2021-08-08T07:53:24.983991Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(study_len):\n    negative_study1 = sub_df_study1.loc[i,'negative']\n    typical_study1 = sub_df_study1.loc[i,'typical']\n    indeterminate_study1 = sub_df_study1.loc[i,'indeterminate']\n    atypical_study1 = sub_df_study1.loc[i,'atypical']\n    negative_study2 = sub_df_study2.loc[i,'negative']\n    typical_study2 = sub_df_study2.loc[i,'typical']\n    indeterminate_study2 = sub_df_study2.loc[i,'indeterminate']\n    atypical_study2 = sub_df_study2.loc[i,'atypical']\n    negative = (negative_study1 + negative_study2)/2\n    typical = (typical_study1 + typical_study2)/2\n    indeterminate = (indeterminate_study1 + indeterminate_study2)/2\n    atypical = (atypical_study1 + atypical_study2)/2\n    df.loc[i, 'PredictionString'] = f'negative {negative} 0 0 1 1 typical {typical} 0 0 1 1 indeterminate {indeterminate} 0 0 1 1 atypical {atypical} 0 0 1 1'","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:53:24.986373Z","iopub.execute_input":"2021-08-08T07:53:24.986905Z","iopub.status.idle":"2021-08-08T07:53:24.997765Z","shell.execute_reply.started":"2021-08-08T07:53:24.986864Z","shell.execute_reply":"2021-08-08T07:53:24.996881Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_study = df[['id', 'PredictionString']]","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:53:24.999065Z","iopub.execute_input":"2021-08-08T07:53:24.999568Z","iopub.status.idle":"2021-08-08T07:53:25.007269Z","shell.execute_reply.started":"2021-08-08T07:53:24.999532Z","shell.execute_reply":"2021-08-08T07:53:25.006446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_study.head()","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:53:25.008555Z","iopub.execute_input":"2021-08-08T07:53:25.008917Z","iopub.status.idle":"2021-08-08T07:53:25.023785Z","shell.execute_reply.started":"2021-08-08T07:53:25.008880Z","shell.execute_reply":"2021-08-08T07:53:25.022994Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 2 class","metadata":{}},{"cell_type":"markdown","source":"# b7 2 class","metadata":{}},{"cell_type":"code","source":"if fast_sub:\n    sub_df = fast_df.copy()\nelse:\n    sub_df = pd.read_csv('/kaggle/input/siim-covid19-detection/sample_submission.csv')\nsub_df = sub_df[study_len:]\ntest_paths = f'/kaggle/tmp/{split}/image/' + sub_df['id'] +'.png'\nsub_df['none'] = 0\n\nlabel_cols = sub_df.columns[2]\n\ntest_decoder = build_decoder(with_labels=False, target_size=(IMSIZE[8], IMSIZE[8]), ext='png')\ndtest = build_dataset(\n    test_paths, bsize=BATCH_SIZE, repeat=False, \n    shuffle=False, augment=False, cache=False,\n    decode_fn=test_decoder\n)\n\nwith strategy.scope():\n    \n    models = []\n    models0 = tf.keras.models.load_model(\n        '/kaggle/input/siim-covid19-efnb7-train-fold0-5-2class/model0.h5'\n    )\n    models1 = tf.keras.models.load_model(\n        '/kaggle/input/siim-covid19-efnb7-train-fold0-5-2class/model1.h5'\n    )\n    models2 = tf.keras.models.load_model(\n        '/kaggle/input/siim-covid19-efnb7-train-fold0-5-2class/model2.h5'\n    )\n    models3 = tf.keras.models.load_model(\n        '/kaggle/input/siim-covid19-efnb7-train-fold0-5-2class/model3.h5'\n    )\n    models4 = tf.keras.models.load_model(\n        '/kaggle/input/siim-covid19-efnb7-train-fold0-5-2class/model4.h5'\n    )\n    models5 = tf.keras.models.load_model(\n        '../input/effi-b7/model0.h5'\n    )\n    models6 = tf.keras.models.load_model(\n        '../input/effi-b7/model1.h5'\n    )\n    models7 = tf.keras.models.load_model(\n        '../input/effi-b7/model2.h5'\n    )\n    models8 = tf.keras.models.load_model(\n        '../input/effi-b7/model3.h5'\n    )\n    models9 = tf.keras.models.load_model(\n        '../input/effi-b7/model4.h5'\n    )\n    models10 = tf.keras.models.load_model(\n        '../input/resnet152v2-ifti/model0.h5'\n    )\n    models11 = tf.keras.models.load_model(\n        '../input/resnet152v2-ifti/model4.h5'\n    )\n    models12 = tf.keras.models.load_model(\n        '../input/tf-with-resnet101-train/model0.h5'\n    )\n    models13 = tf.keras.models.load_model(\n        '../input/tf-with-resnet101-train/model2.h5'\n    )\n    models14 = tf.keras.models.load_model(\n        '../input/effib5/model0.h5'\n    )\n    models15 = tf.keras.models.load_model(\n        '../input/effib5/model1.h5'\n    )\n    models16 = tf.keras.models.load_model(\n        '../input/ext-data-vinbig-augs/model0.h5'\n    )\n    models17 = tf.keras.models.load_model(\n        '../input/resnet152v2-ifti/model1.h5'\n    )\n    models18 = tf.keras.models.load_model(\n        '../input/resnet152v2-ifti/model2.h5'\n    )\n    models19 = tf.keras.models.load_model(\n        '../input/resnet152v2-ifti/model3.h5'\n    )\n#     models20 = tf.keras.models.load_model(\n#         '../input/mminnat-dataset/model.01-1.5455.h5'\n#     )\n#     models21 = tf.keras.models.load_model(\n#         '../input/mminnat-dataset/model.04-1.3618.h5'\n#     )\n#     models22 = tf.keras.models.load_model(\n#         '../input/mminnat-dataset/model.06-1.2751.h5'\n#     )\n#     models23 = tf.keras.models.load_model(\n#         '../input/mminnat-dataset/model.07-1.1769.h5'\n#     )\n#     models24 = tf.keras.models.load_model(\n#         '../input/mminnat-dataset/model.08-1.0582.h5'\n#     )\n    models.append(models0)\n    models.append(models1)\n    models.append(models2)\n    models.append(models3)\n    models.append(models4)\n    models.append(models5)\n    models.append(models6)\n    models.append(models7)\n    models.append(models8)\n    models.append(models9)\n    models.append(models10)\n    models.append(models11)\n    models.append(models12)\n    models.append(models13)\n    models.append(models14)\n    models.append(models15)\n    models.append(models16)\n    models.append(models17)\n    models.append(models18)\n    models.append(models19)\n#     models.append(models20)\n#     models.append(models21)\n#     models.append(models22)\n#     models.append(models23)\n#     models.append(models24)\n    \n\n# weights = {\n#     0: 2,\n#     1: 2,\n#     2: 2,\n#     3: 2,\n#     4: 2,\n#     5: 2,\n#     6: 1,\n#     7: 1,\n#     8: 1,\n#     9: 2,\n#     10: 3,\n#     11: 3,\n#     12: 1,\n#     13: 1,\n#     14: 1,\n#     15: 1,\n#     16: 2\n# }\n\nweights = {\n    0: 2,\n    1: 2,\n    2: 2,\n    3: 2,\n    4: 2,\n    5: 2,\n    6: 1,\n    7: 1,\n    8: 1,\n    9: 2,\n    10: 3,\n    11: 3,\n    12: 1,\n    13: 1,\n    14: 1,\n    15: 1,\n    16: 3,\n    17: 3,\n    18: 3,\n    19: 3,\n#     20: 2,\n#     21: 2,\n#     22: 2,\n#     23: 2,\n#     24: 2\n}\n\n\nweights_sum = sum(weights.values())\nweights = {k: v/weights_sum for k, v in weights.items()}\n\npredictions = [model.predict(dtest, verbose=1) for model in models]\nfor i, pred in enumerate(predictions):\n    predictions[i] = weights[i] * pred\n    \n# image_df[label_cols] = sum(predictions)\n    \nsub_df[label_cols] = sum(predictions)\nsub_df = sub_df.reset_index(drop=True)\n\ndel models\ndel models0, models1, models2, models3, models4, models5, models6, models7, models8, models9, models10, models11, models12, models13, models14, models15, models16, models17, models18, models19 #, models20, models21, models22, models23, models24\ndel dtest, test_decoder\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2021-08-08T08:09:19.580849Z","iopub.execute_input":"2021-08-08T08:09:19.581207Z","iopub.status.idle":"2021-08-08T08:09:26.698317Z","shell.execute_reply.started":"2021-08-08T08:09:19.581173Z","shell.execute_reply":"2021-08-08T08:09:26.695361Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# assert False","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:53:33.282677Z","iopub.status.idle":"2021-08-08T07:53:33.283045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# V2 2class","metadata":{}},{"cell_type":"code","source":"df_2class = sub_df.reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:53:33.284203Z","iopub.status.idle":"2021-08-08T07:53:33.284846Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from numba import cuda\nimport torch\ncuda.select_device(0)\ncuda.close()\ncuda.select_device(0)","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:53:33.286398Z","iopub.status.idle":"2021-08-08T07:53:33.286948Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# yolov5 predict","metadata":{}},{"cell_type":"code","source":"import numpy as np, pandas as pd\nfrom glob import glob\nimport shutil, os\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import GroupKFold\nfrom tqdm.notebook import tqdm\nimport seaborn as sns\nimport torch","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:53:33.288054Z","iopub.status.idle":"2021-08-08T07:53:33.288704Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"meta = meta[meta['split'] == 'test']\nif fast_sub:\n    test_df = fast_df.copy()\nelse:\n    test_df = pd.read_csv('/kaggle/input/siim-covid19-detection/sample_submission.csv')\ntest_df = df[study_len:].reset_index(drop=True) \nmeta['image_id'] = meta['image_id'] + '_image'\nmeta.columns = ['id', 'dim0', 'dim1', 'split']\ntest_df = pd.merge(test_df, meta, on = 'id', how = 'left')\n","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:53:33.289822Z","iopub.status.idle":"2021-08-08T07:53:33.290431Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dim = 512 #1024, 256, 'original'\ntest_dir = f'/kaggle/tmp/{split}/image'\nweights_dir = '/kaggle/input/weights-of-yolov5-150-epochs/best.pt'\n\nshutil.copytree('/kaggle/input/yolov5-official-v31-dataset/yolov5', '/kaggle/working/yolov5')\nos.chdir('/kaggle/working/yolov5') # install dependencies\n\nimport torch\n#from IPython.display import Image, clear_output  # to display images\n\n#clear_output()\n#print('Setup complete. Using torch %s %s' % (torch.__version__, torch.cuda.get_device_properties(0) if torch.cuda.is_available() else 'CPU'))\n\n#python detect.py --weights yolov5s.pt --img 832 --source data/images --augment\n\n!python detect.py --weights $weights_dir\\\n--img 512\\\n--conf 0.001\\\n--iou 0.5\\\n--source $test_dir\\\n--save-txt --save-conf --exist-ok\\\n--augment\ndef yolo2voc(image_height, image_width, bboxes):\n    \"\"\"\n    yolo => [xmid, ymid, w, h] (normalized)\n    voc  => [x1, y1, x2, y1]\n\n    \"\"\" \n    bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n\n    bboxes[..., [0, 2]] = bboxes[..., [0, 2]]* image_width\n    bboxes[..., [1, 3]] = bboxes[..., [1, 3]]* image_height\n\n    bboxes[..., [0, 1]] = bboxes[..., [0, 1]] - bboxes[..., [2, 3]]/2\n    bboxes[..., [2, 3]] = bboxes[..., [0, 1]] + bboxes[..., [2, 3]]\n\n    return bboxes\nimage_ids = []\nPredictionStrings = []\n\nfor file_path in tqdm(glob('runs/detect/exp/labels/*.txt')):\n    image_id = file_path.split('/')[-1].split('.')[0]\n    w, h = test_df.loc[test_df.id==image_id,['dim1', 'dim0']].values[0]\n    f = open(file_path, 'r')\n    data = np.array(f.read().replace('\\n', ' ').strip().split(' ')).astype(np.float32).reshape(-1, 6)\n    data = data[:, [0, 5, 1, 2, 3, 4]]\n    bboxes = list(np.round(np.concatenate((data[:, :2], np.round(yolo2voc(h, w, data[:, 2:]))), axis =1).reshape(-1), 12).astype(str))\n    for idx in range(len(bboxes)):\n        bboxes[idx] = str(int(float(bboxes[idx]))) if idx%6!=1 else bboxes[idx]\n    image_ids.append(image_id)\n    PredictionStrings.append(' '.join(bboxes))\n\n\npred_df = pd.DataFrame({'id':image_ids,\n                        'PredictionString':PredictionStrings})","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:53:33.291553Z","iopub.status.idle":"2021-08-08T07:53:33.292156Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df = test_df.drop(['PredictionString'], axis=1)\nsub_df = pd.merge(test_df, pred_df, on = 'id', how = 'left').fillna(\"none 1 0 0 1 1\")\nsub_df = sub_df[['id', 'PredictionString']]\nfor i in range(sub_df.shape[0]):\n    if sub_df.loc[i,'PredictionString'] == \"none 1 0 0 1 1\":\n        continue\n    sub_df_split = sub_df.loc[i,'PredictionString'].split()\n    sub_df_list = []\n    for j in range(int(len(sub_df_split) / 6)):\n        sub_df_list.append('opacity')\n        sub_df_list.append(sub_df_split[6 * j + 1])\n        sub_df_list.append(sub_df_split[6 * j + 2])\n        sub_df_list.append(sub_df_split[6 * j + 3])\n        sub_df_list.append(sub_df_split[6 * j + 4])\n        sub_df_list.append(sub_df_split[6 * j + 5])\n    sub_df.loc[i,'PredictionString'] = ' '.join(sub_df_list)\nsub_df['none'] = df_2class['none'] \nfor i in range(sub_df.shape[0]):\n    if sub_df.loc[i,'PredictionString'] != 'none 1 0 0 1 1':\n        sub_df.loc[i,'PredictionString'] = sub_df.loc[i,'PredictionString'] + ' none ' + str(sub_df.loc[i,'none']) + ' 0 0 1 1'\nsub_df = sub_df[['id', 'PredictionString']]   \ndf_study = df_study[:study_len]\ndf_study = df_study.append(sub_df).reset_index(drop=True)\ndf_study.to_csv('/kaggle/working/submission.csv',index = False)  \nshutil.rmtree('/kaggle/working/yolov5')","metadata":{"execution":{"iopub.status.busy":"2021-08-08T07:53:33.293320Z","iopub.status.idle":"2021-08-08T07:53:33.293987Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}