{"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":"# RSNA Breast Baseline - Faster Inference\n\nThis notebook shows a simple PyTorch inference pipeline based on the pregenerated datasets.\nDicom preprocessing is accelerated on GPU !","metadata":{}},{"cell_type":"code","source":"DEBUG = False","metadata":{"execution":{"iopub.status.busy":"2022-12-20T09:58:43.776356Z","iopub.execute_input":"2022-12-20T09:58:43.777327Z","iopub.status.idle":"2022-12-20T09:58:43.784001Z","shell.execute_reply.started":"2022-12-20T09:58:43.777278Z","shell.execute_reply":"2022-12-20T09:58:43.782079Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Initialization\n- Install Dali + Overwrite a file to handle UINT16\n- Install dicomsdl, pylibjpeg","metadata":{}},{"cell_type":"code","source":"!pip install /kaggle/input/rsna-2022-whl/{pydicom-2.3.0-py3-none-any.whl,pylibjpeg-1.4.0-py3-none-any.whl,python_gdcm-3.0.15-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl}\n!pip install /kaggle/input/nvidia-dali-wheel/nvidia_dali_nightly_cuda110-1.22.0.dev20221213-6757685-py3-none-manylinux2014_x86_64.whl\n!pip install /kaggle/input/nvidia-dali-wheel/dicomsdl-0.109.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_kg_hide-input":true,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2022-12-20T09:58:47.170463Z","iopub.execute_input":"2022-12-20T09:58:47.171166Z","iopub.status.idle":"2022-12-20T10:00:28.471575Z","shell.execute_reply.started":"2022-12-20T09:58:47.171125Z","shell.execute_reply":"2022-12-20T10:00:28.470382Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%writefile /opt/conda/lib/python3.7/site-packages/nvidia/dali/plugin/pytorch.py\n\n\nfrom nvidia.dali.backend import TensorGPU, TensorListGPU\nfrom nvidia.dali.pipeline import Pipeline\nimport nvidia.dali.ops as ops\nfrom nvidia.dali import types\nfrom nvidia.dali.plugin.base_iterator import _DaliBaseIterator\nfrom nvidia.dali.plugin.base_iterator import LastBatchPolicy\nimport torch\nimport torch.utils.dlpack as torch_dlpack\nimport ctypes\nimport numpy as np\n\nto_torch_type = {\n    types.DALIDataType.FLOAT:   torch.float32,\n    types.DALIDataType.FLOAT64: torch.float64,\n    types.DALIDataType.FLOAT16: torch.float16,\n    types.DALIDataType.UINT8:   torch.uint8,\n    types.DALIDataType.INT8:    torch.int8,\n    types.DALIDataType.UINT16:  torch.int16,\n    types.DALIDataType.INT16:   torch.int16,\n    types.DALIDataType.INT32:   torch.int32,\n    types.DALIDataType.INT64:   torch.int64\n}\n\n\ndef feed_ndarray(dali_tensor, arr, cuda_stream=None):\n    \"\"\"\n    Copy contents of DALI tensor to PyTorch's Tensor.\n\n    Parameters\n    ----------\n    `dali_tensor` : nvidia.dali.backend.TensorCPU or nvidia.dali.backend.TensorGPU\n                    Tensor from which to copy\n    `arr` : torch.Tensor\n            Destination of the copy\n    `cuda_stream` : torch.cuda.Stream, cudaStream_t or any value that can be cast to cudaStream_t.\n                    CUDA stream to be used for the copy\n                    (if not provided, an internal user stream will be selected)\n                    In most cases, using pytorch's current stream is expected (for example,\n                    if we are copying to a tensor allocated with torch.zeros(...))\n    \"\"\"\n    dali_type = to_torch_type[dali_tensor.dtype]\n\n    assert dali_type == arr.dtype, (\"The element type of DALI Tensor/TensorList\"\n                                    \" doesn't match the element type of the target PyTorch Tensor: \"\n                                    \"{} vs {}\".format(dali_type, arr.dtype))\n    assert dali_tensor.shape() == list(arr.size()), \\\n        (\"Shapes do not match: DALI tensor has size {0}, but PyTorch Tensor has size {1}\".\n            format(dali_tensor.shape(), list(arr.size())))\n    cuda_stream = types._raw_cuda_stream(cuda_stream)\n\n    # turn raw int to a c void pointer\n    c_type_pointer = ctypes.c_void_p(arr.data_ptr())\n    if isinstance(dali_tensor, (TensorGPU, TensorListGPU)):\n        stream = None if cuda_stream is None else ctypes.c_void_p(cuda_stream)\n        dali_tensor.copy_to_external(c_type_pointer, stream, non_blocking=True)\n    else:\n        dali_tensor.copy_to_external(c_type_pointer)\n    return arr\n\n\nclass DALIGenericIterator(_DaliBaseIterator):\n    \"\"\"\n    General DALI iterator for PyTorch. It can return any number of\n    outputs from the DALI pipeline in the form of PyTorch's Tensors.\n\n    Parameters\n    ----------\n    pipelines : list of nvidia.dali.Pipeline\n                List of pipelines to use\n    output_map : list of str\n                List of strings which maps consecutive outputs\n                of DALI pipelines to user specified name.\n                Outputs will be returned from iterator as dictionary\n                of those names.\n                Each name should be distinct\n    size : int, default = -1\n                Number of samples in the shard for the wrapped pipeline (if there is more than\n                one it is a sum)\n                Providing -1 means that the iterator will work until StopIteration is raised\n                from the inside of iter_setup(). The options `last_batch_policy` and\n                `last_batch_padded` don't work in such case. It works with only one pipeline inside\n                the iterator.\n                Mutually exclusive with `reader_name` argument\n    reader_name : str, default = None\n                Name of the reader which will be queried to the shard size, number of shards and\n                all other properties necessary to count properly the number of relevant and padded\n                samples that iterator needs to deal with. It automatically sets `last_batch_policy`\n                to PARTIAL when the FILL is used, and `last_batch_padded` accordingly to match\n                the reader's configuration\n    auto_reset : string or bool, optional, default = False\n                Whether the iterator resets itself for the next epoch or it requires reset() to be\n                called explicitly.\n\n                It can be one of the following values:\n\n                * ``\"no\"``, ``False`` or ``None`` - at the end of epoch StopIteration is raised\n                  and reset() needs to be called\n                * ``\"yes\"`` or ``\"True\"``- at the end of epoch StopIteration is raised but reset()\n                  is called internally automatically\n\n    dynamic_shape : any, optional,\n                Parameter used only for backward compatibility.\n    fill_last_batch : bool, optional, default = None\n                **Deprecated** Please use ``last_batch_policy`` instead\n\n                Whether to fill the last batch with data up to 'self.batch_size'.\n                The iterator would return the first integer multiple\n                of self._num_gpus * self.batch_size entries which exceeds 'size'.\n                Setting this flag to False will cause the iterator to return\n                exactly 'size' entries.\n    last_batch_policy: optional, default = LastBatchPolicy.FILL\n                What to do with the last batch when there are not enough samples in the epoch\n                to fully fill it. See :meth:`nvidia.dali.plugin.base_iterator.LastBatchPolicy`\n    last_batch_padded : bool, optional, default = False\n                Whether the last batch provided by DALI is padded with the last sample\n                or it just wraps up. In the conjunction with ``last_batch_policy`` it tells\n                if the iterator returning last batch with data only partially filled with\n                data from the current epoch is dropping padding samples or samples from\n                the next epoch. If set to ``False`` next\n                epoch will end sooner as data from it was consumed but dropped. If set to\n                True next epoch would be the same length as the first one. For this to happen,\n                the option `pad_last_batch` in the reader needs to be set to True as well.\n                It is overwritten when `reader_name` argument is provided\n    prepare_first_batch : bool, optional, default = True\n                Whether DALI should buffer the first batch right after the creation of the iterator,\n                so one batch is already prepared when the iterator is prompted for the data\n\n    Example\n    -------\n    With the data set ``[1,2,3,4,5,6,7]`` and the batch size 2:\n\n    last_batch_policy = LastBatchPolicy.PARTIAL, last_batch_padded = True  -> last batch = ``[7]``,\n    next iteration will return ``[1, 2]``\n\n    last_batch_policy = LastBatchPolicy.PARTIAL, last_batch_padded = False -> last batch = ``[7]``,\n    next iteration will return ``[2, 3]``\n\n    last_batch_policy = LastBatchPolicy.FILL, last_batch_padded = True   -> last batch = ``[7, 7]``,\n    next iteration will return ``[1, 2]``\n\n    last_batch_policy = LastBatchPolicy.FILL, last_batch_padded = False  -> last batch = ``[7, 1]``,\n    next iteration will return ``[2, 3]``\n\n    last_batch_policy = LastBatchPolicy.DROP, last_batch_padded = True   -> last batch = ``[5, 6]``,\n    next iteration will return ``[1, 2]``\n\n    last_batch_policy = LastBatchPolicy.DROP, last_batch_padded = False  -> last batch = ``[5, 6]``,\n    next iteration will return ``[2, 3]``\n    \"\"\"\n\n    def __init__(self,\n                 pipelines,\n                 output_map,\n                 size=-1,\n                 reader_name=None,\n                 auto_reset=False,\n                 fill_last_batch=None,\n                 dynamic_shape=False,\n                 last_batch_padded=False,\n                 last_batch_policy=LastBatchPolicy.FILL,\n                 prepare_first_batch=True):\n\n        # check the assert first as _DaliBaseIterator would run the prefetch\n        assert len(set(output_map)) == len(output_map), \"output_map names should be distinct\"\n        self._output_categories = set(output_map)\n        self.output_map = output_map\n\n        _DaliBaseIterator.__init__(self,\n                                   pipelines,\n                                   size,\n                                   reader_name,\n                                   auto_reset,\n                                   fill_last_batch,\n                                   last_batch_padded,\n                                   last_batch_policy,\n                                   prepare_first_batch=prepare_first_batch)\n\n        self._first_batch = None\n        if self._prepare_first_batch:\n            try:\n                self._first_batch = DALIGenericIterator.__next__(self)\n                # call to `next` sets _ever_consumed to True but if we are just calling it from\n                # here we should set if to False again\n                self._ever_consumed = False\n            except StopIteration:\n                assert False, \"It seems that there is no data in the pipeline. This may happen \" \\\n                       \"if `last_batch_policy` is set to PARTIAL and the requested batch size is \" \\\n                       \"greater than the shard size.\"\n\n    def __next__(self):\n        self._ever_consumed = True\n        if self._first_batch is not None:\n            batch = self._first_batch\n            self._first_batch = None\n            return batch\n\n        # Gather outputs\n        outputs = self._get_outputs()\n\n        data_batches = [None for i in range(self._num_gpus)]\n        for i in range(self._num_gpus):\n            dev_id = self._pipes[i].device_id\n            # initialize dict for all output categories\n            category_outputs = dict()\n            # segregate outputs into categories\n            for j, out in enumerate(outputs[i]):\n                category_outputs[self.output_map[j]] = out\n\n            # Change DALI TensorLists into Tensors\n            category_tensors = dict()\n            category_shapes = dict()\n            for category, out in category_outputs.items():\n                category_tensors[category] = out.as_tensor()\n                category_shapes[category] = category_tensors[category].shape()\n\n            category_torch_type = dict()\n            category_device = dict()\n            torch_gpu_device = None\n            torch_cpu_device = torch.device('cpu')\n            # check category and device\n            for category in self._output_categories:\n                category_torch_type[category] = to_torch_type[category_tensors[category].dtype]\n                if type(category_tensors[category]) is TensorGPU:\n                    if not torch_gpu_device:\n                        torch_gpu_device = torch.device('cuda', dev_id)\n                    category_device[category] = torch_gpu_device\n                else:\n                    category_device[category] = torch_cpu_device\n\n            pyt_tensors = dict()\n            for category in self._output_categories:\n                pyt_tensors[category] = torch.empty(category_shapes[category],\n                                                    dtype=category_torch_type[category],\n                                                    device=category_device[category])\n\n            data_batches[i] = pyt_tensors\n\n            # Copy data from DALI Tensors to torch tensors\n            for category, tensor in category_tensors.items():\n                if isinstance(tensor, (TensorGPU, TensorListGPU)):\n                    # Using same cuda_stream used by torch.zeros to set the memory\n                    stream = torch.cuda.current_stream(device=pyt_tensors[category].device)\n                    feed_ndarray(tensor, pyt_tensors[category], cuda_stream=stream)\n                else:\n                    feed_ndarray(tensor, pyt_tensors[category])\n\n        self._schedule_runs()\n\n        self._advance_and_check_drop_last()\n\n        if self._reader_name:\n            if_drop, left = self._remove_padded()\n            if np.any(if_drop):\n                output = []\n                for batch, to_copy in zip(data_batches, left):\n                    batch = batch.copy()\n                    for category in self._output_categories:\n                        batch[category] = batch[category][0:to_copy]\n                    output.append(batch)\n                return output\n\n        else:\n            if self._last_batch_policy == LastBatchPolicy.PARTIAL and (\n                                          self._counter > self._size) and self._size > 0:\n                # First calculate how much data is required to return exactly self._size entries.\n                diff = self._num_gpus * self.batch_size - (self._counter - self._size)\n                # Figure out how many GPUs to grab from.\n                numGPUs_tograb = int(np.ceil(diff / self.batch_size))\n                # Figure out how many results to grab from the last GPU\n                # (as a fractional GPU batch may be required to bring us\n                # right up to self._size).\n                mod_diff = diff % self.batch_size\n                data_fromlastGPU = mod_diff if mod_diff else self.batch_size\n\n                # Grab the relevant data.\n                # 1) Grab everything from the relevant GPUs.\n                # 2) Grab the right data from the last GPU.\n                # 3) Append data together correctly and return.\n                output = data_batches[0:numGPUs_tograb]\n                output[-1] = output[-1].copy()\n                for category in self._output_categories:\n                    output[-1][category] = output[-1][category][0:data_fromlastGPU]\n                return output\n\n        return data_batches\n\n\nclass DALIClassificationIterator(DALIGenericIterator):\n    \"\"\"\n    DALI iterator for classification tasks for PyTorch. It returns 2 outputs\n    (data and label) in the form of PyTorch's Tensor.\n\n    Calling\n\n    .. code-block:: python\n\n       DALIClassificationIterator(pipelines, reader_name)\n\n    is equivalent to calling\n\n    .. code-block:: python\n\n       DALIGenericIterator(pipelines, [\"data\", \"label\"], reader_name)\n\n    Parameters\n    ----------\n    pipelines : list of nvidia.dali.Pipeline\n                List of pipelines to use\n    size : int, default = -1\n                Number of samples in the shard for the wrapped pipeline (if there is more than\n                one it is a sum)\n                Providing -1 means that the iterator will work until StopIteration is raised\n                from the inside of iter_setup(). The options `last_batch_policy` and\n                `last_batch_padded` don't work in such case. It works with only one pipeline inside\n                the iterator.\n                Mutually exclusive with `reader_name` argument\n    reader_name : str, default = None\n                Name of the reader which will be queried to the shard size, number of shards and\n                all other properties necessary to count properly the number of relevant and padded\n                samples that iterator needs to deal with. It automatically sets `last_batch_policy`\n                to PARTIAL when the FILL is used, and `last_batch_padded` accordingly to match\n                the reader's configuration\n    auto_reset : string or bool, optional, default = False\n                Whether the iterator resets itself for the next epoch or it requires reset() to be\n                called explicitly.\n\n                It can be one of the following values:\n\n                * ``\"no\"``, ``False`` or ``None`` - at the end of epoch StopIteration is raised\n                  and reset() needs to be called\n                * ``\"yes\"`` or ``\"True\"``- at the end of epoch StopIteration is raised but reset()\n                  is called internally automatically\n\n    dynamic_shape : any, optional,\n                Parameter used only for backward compatibility.\n    fill_last_batch : bool, optional, default = None\n                **Deprecated** Please use ``last_batch_policy`` instead\n\n                Whether to fill the last batch with data up to 'self.batch_size'.\n                The iterator would return the first integer multiple\n                of self._num_gpus * self.batch_size entries which exceeds 'size'.\n                Setting this flag to False will cause the iterator to return\n                exactly 'size' entries.\n    last_batch_policy: optional, default = LastBatchPolicy.FILL\n                What to do with the last batch when there are not enough samples in the epoch\n                to fully fill it. See :meth:`nvidia.dali.plugin.base_iterator.LastBatchPolicy`\n    last_batch_padded : bool, optional, default = False\n                Whether the last batch provided by DALI is padded with the last sample\n                or it just wraps up. In the conjunction with ``last_batch_policy`` it tells\n                if the iterator returning last batch with data only partially filled with\n                data from the current epoch is dropping padding samples or samples from\n                the next epoch. If set to ``False`` next\n                epoch will end sooner as data from it was consumed but dropped. If set to\n                True next epoch would be the same length as the first one. For this to happen,\n                the option `pad_last_batch` in the reader needs to be set to True as well.\n                It is overwritten when `reader_name` argument is provided\n    prepare_first_batch : bool, optional, default = True\n                Whether DALI should buffer the first batch right after the creation of the iterator,\n                so one batch is already prepared when the iterator is prompted for the data\n\n    Example\n    -------\n    With the data set ``[1,2,3,4,5,6,7]`` and the batch size 2:\n\n    last_batch_policy = LastBatchPolicy.PARTIAL, last_batch_padded = True  -> last batch = ``[7]``,\n    next iteration will return ``[1, 2]``\n\n    last_batch_policy = LastBatchPolicy.PARTIAL, last_batch_padded = False -> last batch = ``[7]``,\n    next iteration will return ``[2, 3]``\n\n    last_batch_policy = LastBatchPolicy.FILL, last_batch_padded = True   -> last batch = ``[7, 7]``,\n    next iteration will return ``[1, 2]``\n\n    last_batch_policy = LastBatchPolicy.FILL, last_batch_padded = False  -> last batch = ``[7, 1]``,\n    next iteration will return ``[2, 3]``\n\n    last_batch_policy = LastBatchPolicy.DROP, last_batch_padded = True   -> last batch = ``[5, 6]``,\n    next iteration will return ``[1, 2]``\n\n    last_batch_policy = LastBatchPolicy.DROP, last_batch_padded = False  -> last batch = ``[5, 6]``,\n    next iteration will return ``[2, 3]``\n    \"\"\"\n\n    def __init__(self,\n                 pipelines,\n                 size=-1,\n                 reader_name=None,\n                 auto_reset=False,\n                 fill_last_batch=None,\n                 dynamic_shape=False,\n                 last_batch_padded=False,\n                 last_batch_policy=LastBatchPolicy.FILL,\n                 prepare_first_batch=True):\n        super(DALIClassificationIterator, self).__init__(pipelines, [\"data\", \"label\"],\n                                                         size,\n                                                         reader_name=reader_name,\n                                                         auto_reset=auto_reset,\n                                                         fill_last_batch=fill_last_batch,\n                                                         dynamic_shape=dynamic_shape,\n                                                         last_batch_padded=last_batch_padded,\n                                                         last_batch_policy=last_batch_policy,\n                                                         prepare_first_batch=prepare_first_batch)\n\n\nclass TorchPythonFunction(ops.PythonFunctionBase):\n    schema_name = \"TorchPythonFunction\"\n    ops.register_cpu_op('TorchPythonFunction')\n    ops.register_gpu_op('TorchPythonFunction')\n\n    def _torch_stream_wrapper(self, function, *ins):\n        with torch.cuda.stream(self.stream):\n            out = function(*ins)\n        self.stream.synchronize()\n        return out\n\n    def torch_wrapper(self, batch_processing, function, device, *args):\n        func = function if device == 'cpu' else \\\n               lambda *ins: self._torch_stream_wrapper(function, *ins)\n        if batch_processing:\n            return ops.PythonFunction.function_wrapper_batch(func,\n                                                             self.num_outputs,\n                                                             torch.utils.dlpack.from_dlpack,\n                                                             torch.utils.dlpack.to_dlpack,\n                                                             *args)\n        else:\n            return ops.PythonFunction.function_wrapper_per_sample(func,\n                                                                  self.num_outputs,\n                                                                  torch_dlpack.from_dlpack,\n                                                                  torch_dlpack.to_dlpack,\n                                                                  *args)\n\n    def __call__(self, *inputs, **kwargs):\n        pipeline = Pipeline.current()\n        if pipeline is None:\n            Pipeline._raise_no_current_pipeline(\"TorchPythonFunction\")\n        if self.stream is None:\n            self.stream = torch.cuda.Stream(device=pipeline.device_id)\n        return super(TorchPythonFunction, self).__call__(*inputs, **kwargs)\n\n    def __init__(self, function, num_outputs=1, device='cpu', batch_processing=False, **kwargs):\n        self.stream = None\n        super(TorchPythonFunction, self).__init__(impl_name=\"DLTensorPythonFunctionImpl\",\n                                                  function=lambda *ins:\n                                                  self.torch_wrapper(batch_processing,\n                                                                     function, device,\n                                                                     *ins),\n                                                  num_outputs=num_outputs, device=device,\n                                                  batch_processing=batch_processing, **kwargs)\n\n\nops._wrap_op(TorchPythonFunction, \"fn\", __name__)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-20T10:00:35.984861Z","iopub.execute_input":"2022-12-20T10:00:35.985251Z","iopub.status.idle":"2022-12-20T10:00:36.00559Z","shell.execute_reply.started":"2022-12-20T10:00:35.985204Z","shell.execute_reply":"2022-12-20T10:00:36.004485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport sys\nimport cv2\nimport glob\nimport gdcm\nimport json\nimport shutil\nimport pydicom\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom tqdm.notebook import tqdm\nfrom joblib import Parallel, delayed","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-20T10:00:44.565027Z","iopub.execute_input":"2022-12-20T10:00:44.565386Z","iopub.status.idle":"2022-12-20T10:00:44.796742Z","shell.execute_reply.started":"2022-12-20T10:00:44.565354Z","shell.execute_reply":"2022-12-20T10:00:44.795755Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Data Preparation\n","metadata":{}},{"cell_type":"code","source":"IMG_PATH = \"/kaggle/input/rsna-breast-cancer-detection/test_images/\"\ntest_images = glob.glob(f\"{IMG_PATH}*/*.dcm\")\n\nif DEBUG:\n    IMG_PATH = \"/kaggle/input/rsna-breast-cancer-detection/train_images/\"\n#     test_images = glob.glob(f\"{IMG_PATH}*/*.dcm\")[:1000]\n    test_images = glob.glob(f\"{IMG_PATH}10042/*.dcm\")\n    \nprint(\"Number of images :\", len(test_images))","metadata":{"execution":{"iopub.status.busy":"2022-12-20T10:00:48.673896Z","iopub.execute_input":"2022-12-20T10:00:48.674256Z","iopub.status.idle":"2022-12-20T10:00:48.686796Z","shell.execute_reply.started":"2022-12-20T10:00:48.674224Z","shell.execute_reply":"2022-12-20T10:00:48.685649Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"SAVE_FOLDER = \"/tmp/output/\"\nSIZE = 1024\n\nos.makedirs(SAVE_FOLDER, exist_ok=True)\n\nif len(test_images) > 100:\n    N_CHUNKS = 4\nelse:\n    N_CHUNKS = 1\n\nCHUNKS = [(len(test_images) / N_CHUNKS * k, len(test_images) / N_CHUNKS * (k + 1)) for k in range(N_CHUNKS)]\nCHUNKS = np.array(CHUNKS).astype(int)\n    \nJ2K_FOLDER = \"/tmp/j2k/\"","metadata":{"execution":{"iopub.status.busy":"2022-12-20T10:00:51.883223Z","iopub.execute_input":"2022-12-20T10:00:51.883608Z","iopub.status.idle":"2022-12-20T10:00:51.89145Z","shell.execute_reply.started":"2022-12-20T10:00:51.883575Z","shell.execute_reply":"2022-12-20T10:00:51.890411Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Process jpeg compressed dicoms on GPU\n- Convert files to j2k\n- Load j2k files, resize & scale on GPU !\n- Processing is done per batch not to run out of disk space","metadata":{}},{"cell_type":"code","source":"import torch\nimport torch.nn.functional as F\nimport nvidia.dali.fn as fn\nimport nvidia.dali.types as types\nfrom nvidia.dali import pipeline_def\nfrom nvidia.dali.types import DALIDataType\nfrom pydicom.filebase import DicomBytesIO\nfrom nvidia.dali.plugin.pytorch import feed_ndarray, to_torch_type\n\n\ndef convert_dicom_to_j2k(file, save_folder=\"\"):\n    patient = file.split('/')[-2]\n    image = file.split('/')[-1][:-4]\n    dcmfile = pydicom.dcmread(file)\n\n    if dcmfile.file_meta.TransferSyntaxUID == '1.2.840.10008.1.2.4.90':\n        with open(file, 'rb') as fp:\n            raw = DicomBytesIO(fp.read())\n            ds = pydicom.dcmread(raw)\n        offset = ds.PixelData.find(b\"\\x00\\x00\\x00\\x0C\")  #<---- the jpeg2000 header info we're looking for\n        hackedbitstream = bytearray()\n        hackedbitstream.extend(ds.PixelData[offset:])\n        with open(save_folder + f\"{patient}_{image}.jp2\", \"wb\") as binary_file:\n            binary_file.write(hackedbitstream)\n\n            \n@pipeline_def\ndef j2k_decode_pipeline(j2kfiles):\n    jpegs, _ = fn.readers.file(files=j2kfiles)\n    images = fn.experimental.decoders.image(jpegs, device='mixed', output_type=types.ANY_DATA, dtype=DALIDataType.UINT16)\n    return images","metadata":{"execution":{"iopub.status.busy":"2022-12-20T10:00:55.353505Z","iopub.execute_input":"2022-12-20T10:00:55.353865Z","iopub.status.idle":"2022-12-20T10:00:55.675561Z","shell.execute_reply.started":"2022-12-20T10:00:55.353835Z","shell.execute_reply":"2022-12-20T10:00:55.674628Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for chunk in tqdm(CHUNKS):\n    os.makedirs(J2K_FOLDER, exist_ok=True)\n\n    _ = Parallel(n_jobs=2)(\n        delayed(convert_dicom_to_j2k)(img, save_folder=J2K_FOLDER)\n        for img in test_images[chunk[0]: chunk[1]]\n    )\n    \n    j2kfiles = glob.glob(J2K_FOLDER + \"*.jp2\")\n\n    if not len(j2kfiles):\n        continue\n\n    pipe = j2k_decode_pipeline(j2kfiles, batch_size=1, num_threads=2, device_id=0, debug=True)\n    pipe.build()\n\n    for i, f in enumerate(j2kfiles):\n        patient, image = f.split('/')[-1][:-4].split('_')\n        dicom = pydicom.dcmread(IMG_PATH + f\"{patient}/{image}.dcm\")\n\n        out = pipe.run()\n\n        # Dali -> Torch\n        img = out[0][0]\n        img_torch = torch.empty(img.shape(), dtype=torch.int16, device=\"cuda\")\n        feed_ndarray(img, img_torch, cuda_stream=torch.cuda.current_stream(device=0))\n        img = img_torch.float()\n\n        # Scale, resize, invert on GPU !\n        min_, max_ = img.min(), img.max()\n        img = (img - min_) / (max_ - min_)\n\n        if SIZE:\n            img = F.interpolate(img.view(1, 1, img.size(0), img.size(1)), (SIZE, SIZE), mode=\"bilinear\")[0, 0]\n\n        if dicom.PhotometricInterpretation == \"MONOCHROME1\":\n            img = 1 - img\n\n        # Back to CPU + SAVE\n        img = (img * 255).cpu().numpy().astype(np.uint8)\n\n        cv2.imwrite(SAVE_FOLDER + f\"{patient}_{image}.png\", img)\n\n    shutil.rmtree(J2K_FOLDER)","metadata":{"execution":{"iopub.status.busy":"2022-12-20T10:00:57.703468Z","iopub.execute_input":"2022-12-20T10:00:57.703887Z","iopub.status.idle":"2022-12-20T10:01:02.901684Z","shell.execute_reply.started":"2022-12-20T10:00:57.70385Z","shell.execute_reply":"2022-12-20T10:01:02.900497Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Process the rest on CPU","metadata":{}},{"cell_type":"code","source":"import dicomsdl\n\ndef dicomsdl_to_numpy_image(dicom, index=0):\n    info = dicom.getPixelDataInfo()\n    dtype = info['dtype']\n    if info['SamplesPerPixel'] != 1:\n        raise RuntimeError('SamplesPerPixel != 1')\n    else:\n        shape = [info['Rows'], info['Cols']]\n    outarr = np.empty(shape, dtype=dtype)\n    dicom.copyFrameData(index, outarr)\n    return outarr\n\ndef load_img_dicomsdl(f):\n    return dicomsdl_to_numpy_image(dicomsdl.open(f))","metadata":{"execution":{"iopub.status.busy":"2022-12-20T10:01:08.193809Z","iopub.execute_input":"2022-12-20T10:01:08.194212Z","iopub.status.idle":"2022-12-20T10:01:08.209106Z","shell.execute_reply.started":"2022-12-20T10:01:08.194171Z","shell.execute_reply":"2022-12-20T10:01:08.208035Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def process(f, size=512, save_folder=\"\"):\n    patient = f.split('/')[-2]\n    image = f.split('/')[-1][:-4]\n\n    dicom = pydicom.dcmread(f)\n\n    if dicom.file_meta.TransferSyntaxUID == '1.2.840.10008.1.2.4.90':  # ALREADY PROCESSED\n        return\n\n    try:\n        img = load_img_dicomsdl(f)\n    except:\n        img = dicom.pixel_array\n\n    img = (img - img.min()) / (img.max() - img.min())\n\n    if dicom.PhotometricInterpretation == \"MONOCHROME1\":\n        img = 1 - img\n\n    img = cv2.resize(img, (size, size))\n\n    cv2.imwrite(save_folder + f\"{patient}_{image}.png\", (img * 255).astype(np.uint8))","metadata":{"execution":{"iopub.status.busy":"2022-12-20T10:01:11.363056Z","iopub.execute_input":"2022-12-20T10:01:11.363614Z","iopub.status.idle":"2022-12-20T10:01:11.371701Z","shell.execute_reply.started":"2022-12-20T10:01:11.363547Z","shell.execute_reply":"2022-12-20T10:01:11.370551Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"_ = Parallel(n_jobs=2)(\n    delayed(process)(img, size=SIZE, save_folder=SAVE_FOLDER)\n    for img in tqdm(test_images)\n)","metadata":{"execution":{"iopub.status.busy":"2022-12-20T10:01:22.934878Z","iopub.execute_input":"2022-12-20T10:01:22.935245Z","iopub.status.idle":"2022-12-20T10:01:23.049645Z","shell.execute_reply.started":"2022-12-20T10:01:22.935215Z","shell.execute_reply":"2022-12-20T10:01:23.0488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Config\n","metadata":{}},{"cell_type":"code","source":"class Config:\n    \"\"\"\n    Parameters used for training\n    \"\"\"\n    # General\n    seed = 42\n    verbose = 1\n    device = \"cuda\"\n    save_weights = True\n\n    # Images\n    size = 1024\n\n    # k-fold\n    k = 4  # Stratified GKF\n\n    # Model\n    name = \"tf_efficientnetv2_s\"\n    pretrained_weights = None\n    num_classes = 1\n    n_channels = 3\n\n    # Training    \n    loss_config = {\n        \"name\": \"bce\",\n        \"smoothing\": 0.,\n        \"activation\": \"sigmoid\",\n    }\n\n    data_config = {\n        \"batch_size\": 8,\n        \"val_bs\": 8,\n    }\n\n    optimizer_config = {\n        \"name\": \"AdamW\",\n        \"lr\": 3e-4,\n        \"warmup_prop\": 0.1,\n        \"betas\": (0.9, 0.999),\n        \"max_grad_norm\": 10.,\n    }\n\n    epochs = 4\n    use_fp16 = True\n    \n    ## Other stuff\n    # Augmentations : Only HorizontalFlip","metadata":{"execution":{"iopub.status.busy":"2022-12-20T10:01:31.095047Z","iopub.execute_input":"2022-12-20T10:01:31.095421Z","iopub.status.idle":"2022-12-20T10:01:31.102399Z","shell.execute_reply.started":"2022-12-20T10:01:31.09539Z","shell.execute_reply":"2022-12-20T10:01:31.1013Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Inference","metadata":{}},{"cell_type":"markdown","source":"### Utils","metadata":{}},{"cell_type":"code","source":"import cv2\nimport torch\nfrom torch.utils.data import Dataset\n\n\nclass BreastDataset(Dataset):\n    \"\"\"\n    Image torch Dataset.\n    \"\"\"\n    def __init__(\n        self,\n        df,\n        transforms=None,\n    ):\n        \"\"\"\n        Constructor\n\n        Args:\n            paths (list): Path to images.\n            transforms (albumentation transforms, optional): Transforms to apply. Defaults to None.\n        \"\"\"\n        self.paths = df['path'].values\n        self.transforms = transforms\n        self.targets = df['cancer'].values\n\n    def __len__(self):\n        return len(self.paths)\n\n    def __getitem__(self, idx):\n        \"\"\"\n        Item accessor\n\n        Args:\n            idx (int): Index.\n\n        Returns:\n            np array [H x W x C]: Image.\n            torch tensor [1]: Label.\n            torch tensor [1]: Sample weight.\n        \"\"\"\n        image = cv2.imread(self.paths[idx])\n\n        if self.transforms:\n            image = self.transforms(image=image)[\"image\"]\n\n        y = torch.tensor([self.targets[idx]], dtype=torch.float)\n        w = torch.tensor([1])\n\n        return image, y, w\n","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-20T10:01:49.186945Z","iopub.execute_input":"2022-12-20T10:01:49.187312Z","iopub.status.idle":"2022-12-20T10:01:49.195572Z","shell.execute_reply.started":"2022-12-20T10:01:49.187281Z","shell.execute_reply":"2022-12-20T10:01:49.194313Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nimport albumentations as albu\nfrom albumentations.pytorch import ToTensorV2\n\n\ndef get_transfos(augment=True, visualize=False):\n    \"\"\"\n    Returns transformations.\n\n    Args:\n        augment (bool, optional): Whether to apply augmentations. Defaults to True.\n        visualize (bool, optional): Whether to use transforms for visualization. Defaults to False.\n\n    Returns:\n        albumentation transforms: transforms.\n    \"\"\"\n    return albu.Compose(\n        [\n            albu.Normalize(mean=0, std=1),\n            ToTensorV2(),\n        ],\n        p=1,\n    )","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-20T10:01:52.34345Z","iopub.execute_input":"2022-12-20T10:01:52.344461Z","iopub.status.idle":"2022-12-20T10:01:52.350943Z","shell.execute_reply.started":"2022-12-20T10:01:52.344396Z","shell.execute_reply":"2022-12-20T10:01:52.34998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport torch\nimport random\nimport numpy as np\n\n\ndef load_model_weights(model, filename, verbose=1, cp_folder=\"\", strict=True):\n    \"\"\"\n    Loads the weights of a PyTorch model. The exception handles cpu/gpu incompatibilities.\n\n    Args:\n        model (torch model): Model to load the weights to.\n        filename (str): Name of the checkpoint.\n        verbose (int, optional): Whether to display infos. Defaults to 1.\n        cp_folder (str, optional): Folder to load from. Defaults to \"\".\n\n    Returns:\n        torch model: Model with loaded weights.\n    \"\"\"\n    state_dict = torch.load(os.path.join(cp_folder, filename), map_location=\"cpu\")\n\n    try:\n        model.load_state_dict(state_dict, strict=strict)\n    except BaseException:\n        try:\n            del state_dict['logits.weight'], state_dict['logits.bias']\n            model.load_state_dict(state_dict, strict=strict)\n        except BaseException:\n            del state_dict['encoder.conv_stem.weight']\n            model.load_state_dict(state_dict, strict=strict)\n\n    if verbose:\n        print(f\"\\n -> Loading encoder weights from {os.path.join(cp_folder,filename)}\\n\")\n\n    return model\n","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-20T10:01:54.913455Z","iopub.execute_input":"2022-12-20T10:01:54.913833Z","iopub.status.idle":"2022-12-20T10:01:54.923413Z","shell.execute_reply.started":"2022-12-20T10:01:54.9138Z","shell.execute_reply":"2022-12-20T10:01:54.922197Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport numpy as np\nfrom torch.utils.data import DataLoader\n\nNUM_WORKERS = 2\n\n\ndef predict(model, dataset, loss_config, batch_size=64, device=\"cuda\"):\n    \"\"\"\n    Torch predict function.\n\n    Args:\n        model (torch model): Model to predict with.\n        dataset (CustomDataset): Dataset to predict on.\n        loss_config (dict): Loss config, used for activation functions.\n        batch_size (int, optional): Batch size. Defaults to 64.\n        device (str, optional): Device for torch. Defaults to \"cuda\".\n\n    Returns:\n        numpy array [len(dataset) x num_classes]: Predictions.\n    \"\"\"\n    model.eval()\n    preds = np.empty((0,  model.num_classes))\n\n    loader = DataLoader(\n        dataset, batch_size=batch_size, shuffle=False, num_workers=2\n    )\n\n    with torch.no_grad():\n        for batch in loader:\n            x = batch[0].to(device)\n\n            # Forward\n            pred, pred_aux = model(x)\n\n            # Get probabilities\n            if loss_config['activation'] == \"sigmoid\":\n                pred = pred.sigmoid()\n            elif loss_config['activation'] == \"softmax\":\n                pred = pred.softmax(-1)\n\n            preds = np.concatenate([preds, pred.cpu().numpy()])\n\n    return preds\n","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-20T10:01:57.49247Z","iopub.execute_input":"2022-12-20T10:01:57.493189Z","iopub.status.idle":"2022-12-20T10:01:57.501483Z","shell.execute_reply.started":"2022-12-20T10:01:57.493142Z","shell.execute_reply":"2022-12-20T10:01:57.500398Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nsys.path.append('/kaggle/input/timm-0-6-9/pytorch-image-models-master')\n\nimport timm\nimport torch\nimport torch.nn as nn\n\n\ndef define_model(\n    name,\n    num_classes=1,\n    num_classes_aux=0,\n    n_channels=1,\n    pretrained_weights=\"\",\n    pretrained=True,\n):\n    \"\"\"\n    Loads a pretrained model & builds the architecture.\n    Supports timm models.\n\n    Args:\n        name (str): Model name\n        num_classes (int, optional): Number of classes. Defaults to 1.\n        num_classes_aux (int, optional): Number of aux classes. Defaults to 0.\n        n_channels (int, optional): Number of image channels. Defaults to 3.\n        pretrained_weights (str, optional): Path to pretrained encoder weights. Defaults to ''.\n        pretrained (bool, optional): Whether to load timm pretrained weights.\n\n    Returns:\n        torch model -- Pretrained model.\n    \"\"\"\n    # Load pretrained model\n    encoder = getattr(timm.models, name)(pretrained=pretrained)\n    encoder.name = name\n\n    # Tile Model\n    model = ClsModel(\n        encoder,\n        num_classes=num_classes,\n        num_classes_aux=num_classes_aux,\n        n_channels=n_channels,\n    )\n\n    if pretrained_weights:\n        model = load_model_weights(model, pretrained_weights, verbose=1, strict=False)\n\n    return model\n\n\nclass ClsModel(nn.Module):\n    \"\"\"\n    Model with an attention mechanism.\n    \"\"\"\n    def __init__(\n        self,\n        encoder,\n        num_classes=1,\n        num_classes_aux=0,\n        n_channels=3,\n    ):\n        \"\"\"\n        Constructor.\n\n        Args:\n            encoder (timm model): Encoder.\n            num_classes (int, optional): Number of classes. Defaults to 1.\n            num_classes_aux (int, optional): Number of aux classes. Defaults to 0.\n            n_channels (int, optional): Number of image channels. Defaults to 3.\n        \"\"\"\n        super().__init__()\n\n        self.encoder = encoder\n        self.nb_ft = encoder.num_features\n\n        self.num_classes = num_classes\n        self.num_classes_aux = num_classes_aux\n        self.n_channels = n_channels\n\n        self.logits = nn.Linear(self.nb_ft, num_classes)\n        if self.num_classes_aux:\n            self.logits_aux = nn.Linear(self.nb_ft, num_classes_aux)\n\n        self._update_num_channels()\n\n    def _update_num_channels(self):\n        if self.n_channels != 3:\n            for n, m in self.encoder.named_modules():\n                if n:\n                    # print(\"Replacing\", n)\n                    old_conv = getattr(self.encoder, n)\n                    new_conv = nn.Conv2d(\n                        self.n_channels,\n                        old_conv.out_channels,\n                        kernel_size=old_conv.kernel_size,\n                        stride=old_conv.stride,\n                        padding=old_conv.padding,\n                        bias=old_conv.bias is not None,\n                    )\n                    setattr(self.encoder, n, new_conv)\n                    break\n\n    def extract_features(self, x):\n        \"\"\"\n        Extract features function.\n\n        Args:\n            x (torch tensor [batch_size x 3 x w x h]): Input batch.\n\n        Returns:\n            torch tensor [batch_size x num_features]: Features.\n        \"\"\"\n        fts = self.encoder.forward_features(x)\n\n        while len(fts.size()) > 2:\n            fts = fts.mean(-1)\n\n        return fts\n\n    def get_logits(self, fts):\n        \"\"\"\n        Computes logits.\n\n        Args:\n            fts (torch tensor [batch_size x num_features]): Features.\n\n        Returns:\n            torch tensor [batch_size x num_classes]: logits.\n            torch tensor [batch_size x num_classes_aux]: logits aux.\n        \"\"\"\n        logits = self.logits(fts)\n\n        if self.num_classes_aux:\n            logits_aux = self.logits_aux(fts)\n        else:\n            logits_aux = torch.zeros((fts.size(0)))\n\n        return logits, logits_aux\n\n    def forward(self, x, return_fts=False):\n        \"\"\"\n        Forward function.\n\n        Args:\n            x (torch tensor [batch_size x n_frames x h x w]): Input batch.\n\n        Returns:\n            torch tensor [batch_size x num_classes]: logits.\n            torch tensor [batch_size x num_classes_aux]: logits aux.\n        \"\"\"\n        fts = self.extract_features(x)\n\n        logits, logits_aux = self.get_logits(fts)\n\n        return logits, logits_aux\n","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-12-20T10:02:00.063566Z","iopub.execute_input":"2022-12-20T10:02:00.064089Z","iopub.status.idle":"2022-12-20T10:02:00.080109Z","shell.execute_reply.started":"2022-12-20T10:02:00.064052Z","shell.execute_reply":"2022-12-20T10:02:00.079092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Main","metadata":{}},{"cell_type":"code","source":"df = pd.read_csv(\"/kaggle/input/rsna-breast-cancer-detection/test.csv\")\ndf['cancer'] = 0\n\nif DEBUG:\n    df = pd.read_csv(\"/kaggle/input/rsna-breast-cancer-detection/train.csv\")\n    df['path'] = SAVE_FOLDER + df[\"patient_id\"].astype(str) + \"_\" + df[\"image_id\"].astype(str) + \".png\"\n    df = df[df['path'].apply(lambda x: os.path.exists(x))].reset_index(drop=True)\n\ndf['path'] = SAVE_FOLDER + df[\"patient_id\"].astype(str) + \"_\" + df[\"image_id\"].astype(str) + \".png\"","metadata":{"execution":{"iopub.status.busy":"2022-12-20T10:02:03.904259Z","iopub.execute_input":"2022-12-20T10:02:03.904959Z","iopub.status.idle":"2022-12-20T10:02:03.931921Z","shell.execute_reply.started":"2022-12-20T10:02:03.904918Z","shell.execute_reply":"2022-12-20T10:02:03.930999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"USE_TTA = False\npredict_fct = predict_tta if USE_TTA else predict","metadata":{"execution":{"iopub.status.busy":"2022-12-20T10:02:06.24302Z","iopub.execute_input":"2022-12-20T10:02:06.243824Z","iopub.status.idle":"2022-12-20T10:02:06.250961Z","shell.execute_reply.started":"2022-12-20T10:02:06.243786Z","shell.execute_reply":"2022-12-20T10:02:06.249979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EXP_FOLDERS = [\n    \"/kaggle/input/rsna-breast-weights-public/tf_efficientnetv2_s_1024/\"\n]","metadata":{"execution":{"iopub.status.busy":"2022-12-20T10:02:13.203808Z","iopub.execute_input":"2022-12-20T10:02:13.204207Z","iopub.status.idle":"2022-12-20T10:02:13.208977Z","shell.execute_reply.started":"2022-12-20T10:02:13.204176Z","shell.execute_reply":"2022-12-20T10:02:13.207939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Main loop","metadata":{}},{"cell_type":"code","source":"all_preds = []\nfor exp_folder in EXP_FOLDERS:\n    config = Config\n\n    model = define_model(\n        config.name,\n        num_classes=config.num_classes,\n        num_classes_aux=0,\n        n_channels=3,\n        pretrained=False\n    )\n    model = model.cuda().eval()\n\n    dataset = BreastDataset(\n        df,\n        transforms=get_transfos(augment=False),\n    )\n    \n    weights = sorted(glob.glob(exp_folder + f\"*.pt\"))\n    if not len(weights):\n        print('No weights found, add your own dataset !')\n\n    preds = []\n    for fold, weight in enumerate(weights):\n        model = load_model_weights(model, weight, verbose=1)\n        pred = predict(model, dataset, config.loss_config, batch_size=8)\n        preds.append(pred)\n\n    preds = np.mean(preds, 0)\n    all_preds.append(preds)\n    \npreds_blend = np.mean(all_preds, 0)","metadata":{"execution":{"iopub.status.busy":"2022-12-20T10:02:24.735342Z","iopub.execute_input":"2022-12-20T10:02:24.736146Z","iopub.status.idle":"2022-12-20T10:02:25.197539Z","shell.execute_reply.started":"2022-12-20T10:02:24.736106Z","shell.execute_reply":"2022-12-20T10:02:25.196589Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Blend, PP & Submit","metadata":{}},{"cell_type":"code","source":"THRESHOLD = 0.2\n\ndf[\"cancer\"] = preds_blend\ndf['prediction_id'] = df['patient_id'].astype(str) + \"_\" + df['laterality']\n\nsub = df[['prediction_id', 'cancer']].groupby(\"prediction_id\").mean().reset_index()\nsub[\"cancer\"] = (sub[\"cancer\"] > THRESHOLD).astype(int)\n\nsub.to_csv('/kaggle/working/submission.csv', index=False)\n\nsub.head()","metadata":{"execution":{"iopub.status.busy":"2022-12-20T10:02:44.59036Z","iopub.execute_input":"2022-12-20T10:02:44.591397Z","iopub.status.idle":"2022-12-20T10:02:44.624361Z","shell.execute_reply.started":"2022-12-20T10:02:44.591357Z","shell.execute_reply":"2022-12-20T10:02:44.623389Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Done !","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}