{"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":"!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\n!pip install '../input/library1/efficientnet_pytorch-0.7.1/dist/efficientnet_pytorch-0.7.1.tar'\n!pip install '../input/library1/timm-0.4.12-py3-none-any.whl'","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:36:57.385651Z","iopub.execute_input":"2021-07-20T04:36:57.385972Z","iopub.status.idle":"2021-07-20T04:37:45.69057Z","shell.execute_reply.started":"2021-07-20T04:36:57.385939Z","shell.execute_reply":"2021-07-20T04:37:45.689595Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport efficientnet_pytorch\nfrom PIL import Image\nimport pandas as pd\nfrom tqdm.auto import tqdm","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:41:13.489568Z","iopub.execute_input":"2021-07-20T04:41:13.489945Z","iopub.status.idle":"2021-07-20T04:41:13.494565Z","shell.execute_reply.started":"2021-07-20T04:41:13.489915Z","shell.execute_reply":"2021-07-20T04:41:13.493351Z"},"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","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:41:18.887406Z","iopub.execute_input":"2021-07-20T04:41:18.887743Z","iopub.status.idle":"2021-07-20T04:41:18.902523Z","shell.execute_reply.started":"2021-07-20T04:41:18.887712Z","shell.execute_reply":"2021-07-20T04:41:18.901692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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    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    # 近似3个标准差内数据，参考:http://www.kaggle.com/yukiszk/robust-pixel-array-scaling\n    q1,q2,q3 = np.quantile(data, [.15865,.5,.84135]) \n    iqr = q3 - q1\n    multiplier = 1.5\n    mask = ((q2 - multiplier * iqr) < data) & (data < (q2 + multiplier * iqr))\n    \n    if data[mask].size != 0:\n        p = .001\n        data = data.astype(np.float32) - np.quantile(data[mask], p)\n        data = data / np.quantile(data[mask], 1-p)\n    else:\n        data = data - np.min(data)\n        data = data / np.max(data)\n\n    data = np.clip(data, 0, 1)\n    data = (data * 255).astype(np.uint8)\n        \n    return data","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:41:22.618387Z","iopub.execute_input":"2021-07-20T04:41:22.618699Z","iopub.status.idle":"2021-07-20T04:41:22.627952Z","shell.execute_reply.started":"2021-07-20T04:41:22.61867Z","shell.execute_reply":"2021-07-20T04:41:22.626643Z"},"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-07-20T04:41:25.314776Z","iopub.execute_input":"2021-07-20T04:41:25.315093Z","iopub.status.idle":"2021-07-20T04:41:25.322074Z","shell.execute_reply.started":"2021-07-20T04:41:25.315064Z","shell.execute_reply":"2021-07-20T04:41:25.321247Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\nsplit = 'test'\nsave_dir = f'/kaggle/tmp/{split}/'\nos.makedirs(save_dir, exist_ok=True)\n\nsave_dir = f'/kaggle/tmp/{split}/study/'\nos.makedirs(save_dir, 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, 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, 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, study))\n'''\n\nimport time\nimport cv2\nimport torch\nimport torchvision\nfrom skimage import io, transform,color\nfrom glob import glob\nfrom collections import Counter\nfrom skimage import exposure\nfrom torchvision import transforms\nimport torch.nn.functional as F\nimport torch\nfrom torch.autograd import Variable\nimport albumentations as A\n\nsplit = 'test'\nsave_dir = f'/kaggle/tmp/{split}/'\nos.makedirs(save_dir, exist_ok=True)\n\nimg_size = 640\nstudy, image, raw_h, raw_w = [], [], [], []\nfor dirname, _, filenames in tqdm(os.walk(f'../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        h, w = xray.shape\n        #print(h,w)\n        img = resize(xray, size=img_size)\n        image_id = file.split('.')[0]\n        study_id = dirname.split('/')[-2]\n\n        image.append(image_id)\n        study.append(study_id)\n        raw_h.append(h)\n        raw_w.append(w)\n        img.save(f'{save_dir}/{image_id}.png')\n        \ndata = {\"ID\": image, \"StudyInstanceUID\": study, \"Raw H\": raw_h, \"Raw W\": raw_w}\ntest_df = pd.DataFrame(data)\n\ntrans = A.Compose([A.Resize(512,512),\n                   A.Normalize(mean=(0.485,0.456,0.406), std=(0.229, 0.224, 0.225))\n])\n\n# input data preprocess\ndef inference(img_path, input_size, model, mode='study'):\n    ip_img = cv2.imread(img_path)\n    ip_img = cv2.cvtColor(ip_img, cv2.COLOR_BGR2RGB)\n    img_pre = trans(image=ip_img)\n    img_pre = img_pre['image']\n    to_tensor = transforms.ToTensor()\n    input_tensor = to_tensor(img_pre)\n    input_tensor = Variable(torch.unsqueeze(input_tensor, dim=0).float(), requires_grad=False).cuda()\n    outputs = model(input_tensor)\n    op_sfmax = F.softmax(outputs,dim=1).cpu().detach().numpy()[0]\n    #print(op_sfmax)\n    if mode == 'study':\n        return np.argmax(op_sfmax),op_sfmax\n        #return outputs\n    else:\n        pred = non_max_suppression(torch.tensor(outputs[0]), conf_thres = 0.15, iou_thres = 0.5)\n        return pred\n    \n\nclasses_map = {\n    2: 'negative',\n    3: 'typical',\n    1: 'indeterminate',\n    0: 'atypical',\n}\n\n#if __name__ == \"__main__\":\n\ninput_size_study = 512\ninput_size_img = 512\n\npath = f'./../input/siim-covid19-detection/'\ntest_dir = f'/kaggle/tmp/test/'\nsub_df = pd.read_csv(f'{path}/sample_submission.csv')\n# init model\nworker_study = torch.load(f'./../input/b7k5acc2/model_b7_ce_3.pth')\nworker_study2 = torch.load(f'./../input/b7k5accc/model_b7_ce_acc_3.pth')\nworker_study3 = torch.load(f'../input/b7k5accc/model_b7_ce_acc_1.pth')\nworker_study4 = torch.load(f'../input/b7k5acc3/model_b7_ce_3.pth')\nworker_study5 = torch.load(f'../input/b7k5accmulticlass/model_b7_mtclass_2.pth')\n# worker_study = ONNXModel(f'./../input/efnetb0/efnet.onnx')\n#worker_img = ONNXModel(f'./../input/models/yolov5m.onnx')\n\nfor index, row in sub_df.iterrows():\n    #print(row['id'])\n    mode = row['id'].split('_')[-1]\n    if mode == 'study':\n        study_id = row['id'].split('_')[0]\n        image_paths = glob(f'{path}/test/{study_id}/*/*')\n        pre_str = ''\n        #for image_path in image_paths:\n        image_path = image_paths[0]\n        image_id = image_path.split('/')[-1].replace('.dcm', '')\n        img_path = f'{test_dir}/{image_id}.png'\n        img_cls,prob_list = inference(img_path, input_size_study, worker_study, mode='study')\n        img_cls2,prob_list2 = inference(img_path, input_size_study, worker_study2, mode='study')\n        img_cls3,prob_list3 = inference(img_path, input_size_study, worker_study3, mode='study')\n        img_cls4,prob_list4 = inference(img_path, input_size_study, worker_study4, mode='study')\n        img_cls5,prob_list5 = inference(img_path, input_size_study, worker_study5, mode='study')\n\n        for i in classes_map:\n             pre_str = pre_str + classes_map[i] + ' ' + str((prob_list[i]*0.22+prob_list2[i]*0.22+prob_list3[i]*0.22+prob_list4[i]*0.25+prob_list5[i]*0.09)) + ' 0 0 1 1 '\n\n        sub_df.loc[index, \"PredictionString\"] = pre_str.rstrip()\n    \ndf_study = sub_df\n\ndel worker_study, worker_study2,worker_study3,worker_study4,worker_study5","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:41:44.502382Z","iopub.execute_input":"2021-07-20T04:41:44.502694Z","iopub.status.idle":"2021-07-20T04:41:44.618138Z","shell.execute_reply.started":"2021-07-20T04:41:44.502663Z","shell.execute_reply":"2021-07-20T04:41:44.616286Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_id = []\ndim0 = []\ndim1 = []\nsplits = []\nsave_dir = f'/kaggle/tmp/{split}/image/'\nos.makedirs(save_dir, exist_ok=True)\nsave_dir_512 = f'/kaggle/tmp/{split}/image512/'\nos.makedirs(save_dir_512, exist_ok=True)\nsave_dir_1024 = f'/kaggle/tmp/{split}/image1024/'\nos.makedirs(save_dir_1024, 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=640)  \n    im.save(os.path.join(save_dir,'65761e66de9f_image.png'))\n    im_512 = resize(xray, size=512)  \n    im_512.save(os.path.join(save_dir_512,'65761e66de9f_image.png'))\n    im_1024 = resize(xray, size=1024)  \n    im_1024.save(os.path.join(save_dir_1024,'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=640)  \n    im.save(os.path.join(save_dir, '51759b5579bc_image.png'))\n    im_512 = resize(xray, size=512)  \n    im_512.save(os.path.join(save_dir_512, '51759b5579bc_image.png'))\n    im_1024 = resize(xray, size=1024)  \n    im_1024.save(os.path.join(save_dir_1024,'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=640)  \n            im.save(os.path.join(save_dir, file.replace('.dcm', '_image.png')))\n            im_512 = resize(xray, size=512) \n            im_512.save(os.path.join(save_dir_512, file.replace('.dcm', '_image.png')))\n            im_1024 = resize(xray, size=1024) \n            im_1024.save(os.path.join(save_dir_1024, 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-07-20T04:37:45.885581Z","iopub.status.idle":"2021-07-20T04:37:45.885942Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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('/kaggle/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-07-20T04:37:45.887514Z","iopub.status.idle":"2021-07-20T04:37:45.888058Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-07-20T04:37:45.889384Z","iopub.status.idle":"2021-07-20T04:37:45.889934Z"},"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('../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')","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.891388Z","iopub.status.idle":"2021-07-20T04:37:45.89193Z"},"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\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","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.893302Z","iopub.status.idle":"2021-07-20T04:37:45.893839Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"strategy = auto_select_accelerator()\nBATCH_SIZE = strategy.num_replicas_in_sync * 16\n\nIMSIZE = (224, 240, 260, 300, 380, 456, 528, 600, 512)\n\n'''\nif fast_sub:\n    sub_df = fast_df.copy()\nelse:\n    sub_df = pd.read_csv('../input/siim-covid19-detection/sample_submission.csv')\nsub_df = sub_df[:study_len]\ntest_paths = f'/kaggle/tmp/{split}/study/' + sub_df['id'] +'.png'\n\nsub_df['negative'] = 0\nsub_df['typical'] = 0\nsub_df['indeterminate'] = 0\nsub_df['atypical'] = 0\n\nlabel_cols = sub_df.columns[2:]\n\ntest_decoder = build_decoder(with_labels=False, target_size=(IMSIZE[7], IMSIZE[7]), 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    \n    models0 = tf.keras.models.load_model(\n        '../input/model00/model0.h5'\n    )\n    models1 = tf.keras.models.load_model(\n        '../input/model00/model1.h5'\n    )\n    models2 = tf.keras.models.load_model(\n        '../input/model00/model2.h5'\n    )\n    models3 = tf.keras.models.load_model(\n        '../input/model00/model3.h5'\n    )\n    models4 = tf.keras.models.load_model(\n        '../input/model00/model4.h5'\n    )\n    models5 = tf.keras.models.load_model(\n        '../input/k/h053473666/siim-covid19-efnb7-train-study/model0.h5'\n    )\n    models6 = tf.keras.models.load_model(\n        '../input/k/h053473666/siim-covid19-efnb7-train-study/model1.h5'\n    )\n    models7 = tf.keras.models.load_model(\n        '../input/k/h053473666/siim-covid19-efnb7-train-study/model2.h5'\n    )\n    models8 = tf.keras.models.load_model(\n        '../input/k/h053473666/siim-covid19-efnb7-train-study/model3.h5'\n    )\n    models9 = tf.keras.models.load_model(\n        '../input/k/h053473666/siim-covid19-efnb7-train-study/model4.h5'\n    )\n#     models5 = tf.keras.models.load_model(\n#         '../input/siim-covid19-efnb7-train-study/model0.h5'\n#     )\n#     models6 = tf.keras.models.load_model(\n#         '../input/siim-covid19-efnb7-train-study/model1.h5'\n#     )\n#     models7 = tf.keras.models.load_model(\n#         '../input/siim-covid19-efnb7-train-study/model2.h5'\n#     )\n#     models8 = tf.keras.models.load_model(\n#         '../input/siim-covid19-efnb7-train-study/model3.h5'\n#     )\n#     models9 = tf.keras.models.load_model(\n#         '../input/siim-covid19-efnb7-train-study/model4.h5'\n#     )\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\n    \nsub_df[label_cols] = sum([model.predict(dtest, verbose=1) for model in models]) / len(models)\n'''","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.895291Z","iopub.status.idle":"2021-07-20T04:37:45.895838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\nsub_df.columns = ['id', 'PredictionString1', 'negative', 'typical', 'indeterminate', 'atypical']\ndf = pd.merge(df, sub_df, on = 'id', how = 'left')\nfor i in range(study_len):\n    negative = df.loc[i,'negative']\n    typical = df.loc[i,'typical']\n    indeterminate = df.loc[i,'indeterminate']\n    atypical = df.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\ndf_study = df[['id', 'PredictionString']]\n'''","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.897165Z","iopub.status.idle":"2021-07-20T04:37:45.897721Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"strategy = auto_select_accelerator()\nBATCH_SIZE = strategy.num_replicas_in_sync * 16\n\nIMSIZE = (224, 240, 260, 300, 380, 456, 528, 600, 512)\nif fast_sub:\n    sub_df = fast_df.copy()\nelse:\n    sub_df = pd.read_csv('../input/siim-covid19-detection/sample_submission.csv')\nsub_df = sub_df[study_len:]\ntest_paths = f'/kaggle/tmp/{split}/image512/' + 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    \n    models0 = tf.keras.models.load_model(\n        '../input/siim-covid19-efnb7-train-2class-image/model0.h5'\n    )\n    models1 = tf.keras.models.load_model(\n        '../input/siim-covid19-efnb7-train-2class-image/model1.h5'\n    )\n    models2 = tf.keras.models.load_model(\n        '../input/siim-covid19-efnb7-train-2class-image/model2.h5'\n    )\n    models3 = tf.keras.models.load_model(\n        '../input/siim-covid19-efnb7-train-2class-image/model3.h5'\n    )\n    models4 = tf.keras.models.load_model(\n        '../input/siim-covid19-efnb7-train-2class-image/model4.h5'\n    )\n    \n    models.append(models0)\n    models.append(models1)\n    models.append(models2)\n    models.append(models3)\n    models.append(models4)\n\n    \nsub_df[label_cols] = sum([model.predict(dtest, verbose=1) for model in models]) / len(models)\ndf_2class = sub_df.reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.899127Z","iopub.status.idle":"2021-07-20T04:37:45.8997Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del models\ndel models0, models1, models2, models3, models4","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.901157Z","iopub.status.idle":"2021-07-20T04:37:45.901714Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 切换至GPU\nfrom numba import cuda\nimport torch\n#cuda.select_device(0)\n#cuda.close()\n#cuda.select_device(0)","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.902967Z","iopub.status.idle":"2021-07-20T04:37:45.903555Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dim = 640 #1024, 256, 'original'\ntest_dir = f'/kaggle/tmp/{split}/image'\n\nshutil.copytree('/kaggle/input/d/xuxiaoxi/yolov5min/yolo5-640', '/kaggle/working/yolo5-640')\nos.chdir('/kaggle/working/yolo5-640') # install dependencies","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.905168Z","iopub.status.idle":"2021-07-20T04:37:45.905729Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from common import *\nfrom configure import *\n\nfrom yolo5.models.yolo import *\nfrom yolo5.utils.torch_utils import *\nfrom yolo5.utils.general import bbox_iou, xywh2xyxy\n\nclass Net1(nn.Module):\n    def __init__(self):\n        super(Net1, self).__init__()\n\n        model_cfg_file = 'yolo5/models/yolov5x.yaml'\n        pretrain_file  = '/kaggle/input/ultralyticsyolov5aweights/yolov5x.pt'\n        e = Model(\n            cfg=model_cfg_file,\n            ch=3,\n            nc=1,\n            anchors=np.array(anchor_size).reshape(num_head,-1).tolist(),\n        )\n        state_dict = torch.load(pretrain_file, map_location=lambda storage, loc: storage)['model'].float().state_dict()\n        state_dict = intersect_dicts(state_dict, e.state_dict(), exclude=['anchor'])  # intersect\n        e.load_state_dict(state_dict, strict=False)\n\n        #---\n        # remove detect layer\n        assert (e.save[-3:] == e.model[-1].f)\n        removed = list(e.model.children())[:-1]\n        self.backbone = torch.nn.Sequential(*removed)\n        self.index = e.save\n        #print(self.index)\n\n        #---\n        self.head = nn.ModuleList([\n            nn.Conv2d(320, num_anchor*6, kernel_size=1),\n            nn.Conv2d(640, num_anchor*6, kernel_size=1),\n            nn.Conv2d(1280, num_anchor*6, kernel_size=1),\n        ])\n\n        #---\n        #<todo> add image classification head\n        # self.index.append( ... add feature layer no to use ...)\n        self.logit=nn.Sequential(\n            nn.Conv2d(1280, 256, kernel_size=1),\n            nn.BatchNorm2d(256),\n            nn.ReLU(inplace=True),\n            nn.Conv2d(256, 128, kernel_size=1),\n            nn.BatchNorm2d(128),\n            nn.ReLU(inplace=True),\n            nn.AdaptiveAvgPool2d(1),\n            nn.Conv2d(128, 2, kernel_size=1),\n        )\n\n\n    def forward(self, image):\n        batch_size = len(image)\n        x = 2*image-1\n\n        # yolov5 backbone ----------------------\n        # predict = self.e(x)\n        z = []\n        for m in self.backbone:\n            if m.f != -1:  # if not from previous layer\n                if isinstance(m.f, int):\n                    x = z[m.f]\n                else:\n                    x = [x if i == -1 else z[i] for i in m.f]\n            x = m(x)  # run\n            z.append(x if m.i in self.index else None)  # cache output\n        z = [z[i] for i in self.index[-3:]]\n        #--------------------------------------\n        predict = []\n        for n in range(num_head):\n            p = self.head[n](z[n])\n            batch_size, num_anchor_dim, h, w = p.shape\n            dim = num_anchor_dim//num_anchor\n            p = p.reshape(batch_size, num_anchor, dim, h, w).permute(0, 1, 3, 4, 2).contiguous()\n            predict.append(p)\n        logit = self.logit(z[-1]).reshape(batch_size, 2)\n\n        return predict, logit\n","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.907044Z","iopub.status.idle":"2021-07-20T04:37:45.90762Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device(\"cuda\")\nprint(device)","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.908992Z","iopub.status.idle":"2021-07-20T04:37:45.909573Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\n#os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n\nfrom model import *\n\ndef scale_coords(image_height, image_width, bboxes):\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    return bboxes\n\ndef data_process(img_path, input_size):\n    img_raw = cv2.imread(img_path)\n    img_resize = cv2.resize(img_raw, (input_size, input_size))\n    img = img_resize.astype(np.float32)\n    img /= 255.0\n    img = img.transpose(2, 0, 1).astype(np.float32)\n    input_tensor = torch.from_numpy(np.expand_dims(img, axis=0))\n    return input_tensor\n    \ndef softmax(x):\n    row_max = np.max(x, axis=1).reshape(-1,1)\n    x -= row_max\n    x_exp = np.exp(x)\n    return x_exp / np.sum(x_exp, axis=1, keepdims=True)\n\ndef do_predict(net, input_tensor, tta=[]):\n    net.eval()\n    with torch.no_grad():\n        predict, logit = net(input_tensor)\n        predict = infer_prediction(predict)\n        predict_flat = pyramid_to_flat(predict)\n        \n        detection = do_non_max_suppression(\n            predict_flat,\n            nms_objectness_threshold=0.0001,\n            nms_iou_threshold = 0.4,\n            nms_pre_max_num=500,\n            nms_post_max_num=25 \n        )\n    return detection, softmax(logit.cpu().numpy())\n\nboxes_list = []\nscores_list = []\nlabels_list = []\n\nweights_dir = ['/kaggle/input/models-yolo-f0/f0_00021000_model.pth',\n    '/kaggle/input/models-yolo-f1/f1_00020500_model.pth',\n    '/kaggle/input/models-yolo-f2/f2_00019000_model.pth',\n    '/kaggle/input/models-yolo-f3/f3_00019500_model.pth',\n    '/kaggle/input/models-yolo-f4/f4_00018000_model.pth'  \n]\ndevice = torch.device(\"cuda\")\nfor flod in [0,1,2,3,4]:\n    \n    net = Net1().cuda()\n    #net= net.to(device)\n    net.load_state_dict(torch.load(weights_dir[flod])['state_dict'], strict=True)\n    \n    b_list = []\n    s_list = []\n    l_list = []\n    for img in os.listdir(test_dir):\n        img_id = img.replace('.png', '')\n        img_path = f'{test_dir}/{img}'\n        input_tensor = data_process(img_path, dim).cuda()\n    \n        detection, img_cls = do_predict(net, input_tensor)\n        bboxes = (detection[0][:, :4] / 640).tolist()\n        scores = detection[0][:, 4].tolist()\n        b_list.append(bboxes)\n        s_list.append(scores)\n        l_list.append([0] * len(bboxes))\n    boxes_list.append(b_list)\n    scores_list.append(s_list)\n    labels_list.append(l_list)","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.910909Z","iopub.status.idle":"2021-07-20T04:37:45.911496Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install /kaggle/input/mmdetectionv2130/src/addict-2.4.0-py3-none-any.whl\n!pip install /kaggle/input/mmdetectionv2130/src/yapf-0.31.0-py2.py3-none-any.whl\n!pip install /kaggle/input/mmdetectionv2130/src/mmcv_full-1.3.7-cp37-cp37m-manylinux1_x86_64.whl\n!rsync -a /kaggle/input/mmdetectionv2130/mmdetection /kaggle/\n!pip install /kaggle/input/mmdetectionv2130/src/mmpycocotools-12.0.3\n!pip install /kaggle/input/pycocotools202/pycocotools-2.0.2-cp37-cp37m-linux_x86_64.whl\n!pip install /kaggle/input/ensemble-boxes/ensemble_boxes-1.0.6-py3-none-any.whl\n!cd /kaggle/mmdetection && pip install -e .","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.912767Z","iopub.status.idle":"2021-07-20T04:37:45.913341Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nsys.path.insert(0, \"/kaggle/mmdetection\")\nimport cv2\nfrom pathlib import Path\nfrom ensemble_boxes import *\nimport mmcv\nfrom mmcv import Config\nfrom mmdet.models import build_detector\nfrom mmcv.runner import load_checkpoint\nfrom mmcv.parallel import MMDataParallel\nfrom mmdet.datasets import build_dataloader, build_dataset\nfrom mmdet.apis import single_gpu_test\nfrom mmdet.apis import init_detector, inference_detector, show_result_pyplot","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.914626Z","iopub.status.idle":"2021-07-20T04:37:45.915195Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mmdet_models = ['retinanet', 'vfnet', 'faster_rcnn', 'cascade_rcnn', 'retinanet1024', 'vfnet1024']\nmmdet_models_1024 = ['retinanet1024','vfnet1024']\nmodels_config = {'retinanet': \"/kaggle/mmdetection/configs/retinanet/retinanet_r101_fpn_1x_coco.py\",\n                 'vfnet': \"/kaggle/mmdetection/configs/vfnet/vfnet_r101_fpn_1x_coco.py\", \n                 'faster_rcnn': \"/kaggle/mmdetection/configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py\", \n                 'cascade_rcnn': \"/kaggle/mmdetection/configs/cascade_rcnn/cascade_rcnn_r50_fpn_1x_coco.py\",\n                 'retinanet1024': \"/kaggle/mmdetection/configs/retinanet/retinanet_r101_fpn_1x_coco.py\", \n                 'vfnet1024': \"/kaggle/mmdetection/configs/vfnet/vfnet_r101_fpn_1x_coco.py\"\n                }\n\nmodels_checkpoint = {'retinanet': \"/kaggle/input/mmdetmodel0707/retinanet_r101.pth\",\n                 'vfnet': \"/kaggle/input/models-mmdet-v1/vfnet_r101.pth\", \n                 'faster_rcnn': \"/kaggle/input/mmdetmodels/faster_rcnn50.pth\", \n                 'cascade_rcnn': \"/kaggle/input/mmdetmodels/cascade_rcnn50.pth\",\n                 'retinanet1024': \"/kaggle/input/mmdet-model1024-0714/retinanet_1024.pth\",\n                 'vfnet1024': \"/kaggle/input/mmdet-model1024-0714/vfnet_1024.pth\"\n                }\nbatch_size = 1\nscore_threshold = 0.0001\niou_threshold = 0.4\nfor mmdet_model in mmdet_models:\n    baseline_cfg_path = models_config[mmdet_model]\n    cfg = Config.fromfile(baseline_cfg_path)\n    cfg.data.samples_per_gpu = batch_size # Batch size of a single GPU used in testing\n    cfg.data.workers_per_gpu = 2 # Worker to pre-fetch data for each single GPU\n    cfg.test_pipeline = [\n        dict(type='LoadImageFromFile'),\n        dict(\n            type='MultiScaleFlipAug',\n            img_scale=(640, 640),\n            flip=False,\n            transforms=[\n                dict(type='Resize', keep_ratio=True),\n                dict(type='RandomFlip'),\n                dict(\n                    type='Normalize',\n                    mean=[123.675, 116.28, 103.53],\n                    std=[58.395, 57.12, 57.375],\n                    to_rgb=True),\n                dict(type='Pad', size_divisor=32),\n                dict(type='ImageToTensor', keys=['img']),\n                dict(type='Collect', keys=['img'])\n            ])\n    ]\n    if mmdet_model == 'retinanet':\n        cfg.model.bbox_head.num_classes = 2 # retinanet vfnet\n        cfg.model.bbox_head.anchor_generator.ratios = [0.25, 0.5, 1.0, 2.0, 4.0] # retinanet\n        cfg.model.test_cfg.score_thr=score_threshold\n        cfg.model.test_cfg.nms.iou_threshold=iou_threshold\n        \n    elif mmdet_model == 'vfnet':\n        cfg.model.bbox_head.num_classes = 2 # retinanet vfnet\n        cfg.model.test_cfg.score_thr=score_threshold\n        cfg.model.test_cfg.nms.iou_threshold=iou_threshold\n        \n    elif mmdet_model == 'faster_rcnn':\n        cfg.model.roi_head.bbox_head.num_classes = 2 # faster rcnn\n        cfg.model.rpn_head.anchor_generator.ratios = [0.25, 0.5, 1.0, 2.0, 4.0] # rcnn\n        cfg.model.test_cfg.rcnn.score_thr=score_threshold # rcnn\n        cfg.model.test_cfg.rcnn.nms.iou_threshold=iou_threshold # rcnn\n        \n    elif mmdet_model == 'cascade_rcnn':\n        cfg.model.roi_head.bbox_head[0].num_classes = 2 # cascade rcnn\n        cfg.model.roi_head.bbox_head[1].num_classes = 2\n        cfg.model.roi_head.bbox_head[2].num_classes = 2\n        cfg.model.rpn_head.anchor_generator.ratios = [0.25, 0.5, 1.0, 2.0, 4.0] # rcnn\n        cfg.model.test_cfg.rcnn.score_thr=score_threshold # rcnn\n        cfg.model.test_cfg.rcnn.nms.iou_threshold=iou_threshold # rcnn\n    elif mmdet_model == 'retinanet1024':\n        cfg.model.bbox_head.num_classes = 2 # retinanet vfnet\n        cfg.model.bbox_head.anchor_generator.ratios = [0.25, 0.5, 1.0, 2.0, 4.0] # retinanet\n        cfg.model.test_cfg.score_thr=score_threshold\n        cfg.model.test_cfg.nms.iou_threshold=iou_threshold\n        cfg.test_pipeline[1]['img_scale'] = (1024, 1024)\n        \n    elif mmdet_model == 'vfnet1024':\n        cfg.model.bbox_head.num_classes = 2 # retinanet vfnet\n        cfg.model.test_cfg.score_thr=score_threshold\n        cfg.model.test_cfg.nms.iou_threshold=iou_threshold\n        cfg.test_pipeline[1]['img_scale'] = (1024, 1024)\n    if mmdet_model in mmdet_models_1024:\n        cfg_path = f'/kaggle/working/1024{Path(baseline_cfg_path).name}'\n        print(cfg_path)\n    else:\n        cfg_path = f'/kaggle/working/{Path(baseline_cfg_path).name}'\n        print(cfg_path)\n\n    # Save config file for inference later\n    cfg.dump(cfg_path)\n    #print(f'Config:\\n{cfg.pretty_text}')    ","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.916549Z","iopub.status.idle":"2021-07-20T04:37:45.917093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"imgs_path = f'/kaggle/tmp/{split}/image/'\ntest_paths = f'/kaggle/tmp/{split}/image/' + test_df['id'] +'.png'\ntest_imgs = test_paths.tolist()\nfor mmdet_model in mmdet_models:\n    print(\"Loading weights from:\", models_checkpoint[mmdet_model])\n    if mmdet_model in mmdet_models_1024:\n        cfg_path = f'/kaggle/working/1024{Path(models_config[mmdet_model]).name}'\n    else:\n        cfg_path = f'/kaggle/working/{Path(models_config[mmdet_model]).name}'\n    cfg = Config.fromfile(cfg_path)\n    model = init_detector(cfg, models_checkpoint[mmdet_model], device='cuda:0')\n    \n    b_mm_list, s_mm_list, l_mm_list = [],[],[]\n    \n    if mmdet_model in mmdet_models_1024:\n        test_dir = f'/kaggle/tmp/{split}/image1024'\n        rescal_size = 1024\n    else:\n        test_dir = f'/kaggle/tmp/{split}/image'\n        rescal_size = 640\n    for img in os.listdir(test_dir):\n        img_id = img.replace('.png', '')\n        img_path = f'{test_dir}/{img}'\n        imgs = cv2.imread(img_path)\n        #print(imgs.shape)\n        results = inference_detector(model, imgs)\n        result = results[1]\n        #print(results[0])\n        results_filtered = result[result[:, 4]>0.001]\n        bboxes = (results_filtered[:, :4] / rescal_size).tolist()\n        scores = results_filtered[:, 4].tolist()\n        b_mm_list.append(bboxes)\n        s_mm_list.append(scores)\n        l_mm_list.append([0] * len(bboxes))\n        \n    boxes_list.append(b_mm_list)\n    scores_list.append(s_mm_list)\n    labels_list.append(l_mm_list)","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.918451Z","iopub.status.idle":"2021-07-20T04:37:45.918997Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"weights = [2,1,2,1,2,3,2,1,1,3,2]\n# weights_final = [5,4,3,2]\n\niou_thr = 0.5 #  0.5 0.55 0.25\nskip_box_thr = 0.001 # 0.1\nsigma = 0.1\n        \nimage_ids = []\nPredictionStrings = []\nnum=0\nfor img in os.listdir(test_dir):\n    img_id = img.replace('.png', '')\n    image_ids.append(img_id)\n    boxes_l, scores_l, labels_l = [], [], []\n    for i in range(len(weights)):\n        boxes_l.append(boxes_list[i][num])\n        scores_l.append(scores_list[i][num])\n        labels_l.append(labels_list[i][num])\n    num+=1\n    \n    boxes, scores, labels = weighted_boxes_fusion(boxes_l, scores_l, labels_l, weights=weights, iou_thr=iou_thr, skip_box_thr=skip_box_thr)  \n    \n    pre_str = ''\n    if len(boxes) > 0:\n        w, h = test_df.loc[test_df.id==img_id,['dim1', 'dim0']].values[0]\n        bboxes = scale_coords(h, w, boxes)\n        for i in range(len(bboxes)):\n            pre_str = pre_str + 'opacity %.3f %.0f %.0f %.0f %.0f ' %(scores[i], bboxes[i][0], bboxes[i][1], bboxes[i][2], bboxes[i][3])\n\n    PredictionStrings.append(pre_str.rstrip())\n\npred_df = pd.DataFrame({'id':image_ids,\n                        'PredictionString':PredictionStrings})","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.920326Z","iopub.status.idle":"2021-07-20T04:37:45.920872Z"},"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']]\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']]   \n#df = pd.read_csv('/kaggle/input/siim-covid19-detection/sample_submission.csv')\n#df_study = df[:study_len]\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)\n#sub_df.to_csv('/kaggle/working/submission.csv',index = False)\n#df_study","metadata":{"execution":{"iopub.status.busy":"2021-07-20T04:37:45.922223Z","iopub.status.idle":"2021-07-20T04:37:45.92277Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}