{"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":"\nimport os\nfrom pathlib import Path\nin_folder_path = Path('/kaggle/input/braintumor-train-pl')\nscripts_dir = Path(in_folder_path / 'scripts')\nfrom tqdm import tqdm\n\nclass Config:\n    lr = 2e-5\n    data_dir = Path('../input/rsna-miccai-brain-tumor-radiogenomic-classification/test')\n    mri_types = ['FLAIR', 'T1w', 'T1wCE', 'T2w']\n","metadata":{"_uuid":"39e73306-b3af-4c13-ba7e-111615a4e08c","_cell_guid":"9f632821-fc64-4e85-a0d9-03c5f725114f","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-08-25T17:30:57.187573Z","iopub.execute_input":"2021-08-25T17:30:57.188024Z","iopub.status.idle":"2021-08-25T17:30:57.194047Z","shell.execute_reply.started":"2021-08-25T17:30:57.187992Z","shell.execute_reply":"2021-08-25T17:30:57.193098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from torch.utils.data import DataLoader, Dataset\nfrom torch import nn\nfrom torchvision import transforms\nimport torch\nimport pandas as pd\nimport sys \n\nimport glob\nimport numpy as np\nimport pydicom\nimport cv2\nimport pytorch_lightning as pl\nfrom transformers import DeiTFeatureExtractor, DeiTForImageClassification, AutoConfig\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2021-08-25T17:30:57.195772Z","iopub.execute_input":"2021-08-25T17:30:57.196265Z","iopub.status.idle":"2021-08-25T17:30:57.205116Z","shell.execute_reply.started":"2021-08-25T17:30:57.196225Z","shell.execute_reply":"2021-08-25T17:30:57.204376Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# os.chdir(scripts_dir)\n# exec(Path(\"dataset.py\").read_text())\n# exec(Path(\"model.py\").read_text())\n# os.chdir('/kaggle/working')","metadata":{"_uuid":"5fc3ceff-f47b-48f8-b688-d05d9819f9c3","_cell_guid":"034516c2-f897-4cb2-8c2a-ac4374469ddc","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-08-25T17:30:57.208844Z","iopub.execute_input":"2021-08-25T17:30:57.209130Z","iopub.status.idle":"2021-08-25T17:30:57.214334Z","shell.execute_reply.started":"2021-08-25T17:30:57.209085Z","shell.execute_reply":"2021-08-25T17:30:57.213463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import re\nimport math\nimport collections\nfrom functools import partial\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.utils import model_zoo\n\n########################################################################\n############### HELPERS FUNCTIONS FOR MODEL ARCHITECTURE ###############\n########################################################################\n\n\n# Parameters for the entire model (stem, all blocks, and head)\nGlobalParams = collections.namedtuple('GlobalParams', [\n    'batch_norm_momentum', 'batch_norm_epsilon', 'dropout_rate',\n    'num_classes', 'width_coefficient', 'depth_coefficient',\n    'depth_divisor', 'min_depth', 'drop_connect_rate', 'image_size'])\n\n# Parameters for an individual model block\nBlockArgs = collections.namedtuple('BlockArgs', [\n    'kernel_size', 'num_repeat', 'input_filters', 'output_filters',\n    'expand_ratio', 'id_skip', 'stride', 'se_ratio'])\n\n# Change namedtuple defaults\nGlobalParams.__new__.__defaults__ = (None,) * len(GlobalParams._fields)\nBlockArgs.__new__.__defaults__ = (None,) * len(BlockArgs._fields)\n\n\nclass SwishImplementation(torch.autograd.Function):\n    @staticmethod\n    def forward(ctx, i):\n        result = i * torch.sigmoid(i)\n        ctx.save_for_backward(i)\n        return result\n\n    @staticmethod\n    def backward(ctx, grad_output):\n        i = ctx.saved_variables[0]\n        sigmoid_i = torch.sigmoid(i)\n        return grad_output * (sigmoid_i * (1 + i * (1 - sigmoid_i)))\n\n\nclass MemoryEfficientSwish(nn.Module):\n    def forward(self, x):\n        return SwishImplementation.apply(x)\n\nclass Swish(nn.Module):\n    def forward(self, x):\n        return x * torch.sigmoid(x)\n\n\ndef round_filters(filters, global_params):\n    \"\"\" Calculate and round number of filters based on depth multiplier. \"\"\"\n    multiplier = global_params.width_coefficient\n    if not multiplier:\n        return filters\n    divisor = global_params.depth_divisor\n    min_depth = global_params.min_depth\n    filters *= multiplier\n    min_depth = min_depth or divisor\n    new_filters = max(min_depth, int(filters + divisor / 2) // divisor * divisor)\n    if new_filters < 0.9 * filters:  # prevent rounding by more than 10%\n        new_filters += divisor\n    return int(new_filters)\n\n\ndef round_repeats(repeats, global_params):\n    \"\"\" Round number of filters based on depth multiplier. \"\"\"\n    multiplier = global_params.depth_coefficient\n    if not multiplier:\n        return repeats\n    return int(math.ceil(multiplier * repeats))\n\n\ndef drop_connect(inputs, p, training):\n    \"\"\" Drop connect. \"\"\"\n    if not training: return inputs\n    batch_size = inputs.shape[0]\n    keep_prob = 1 - p\n    random_tensor = keep_prob\n    random_tensor += torch.rand([batch_size, 1, 1, 1, 1], dtype=inputs.dtype, device=inputs.device)\n    binary_tensor = torch.floor(random_tensor)\n    output = inputs / keep_prob * binary_tensor\n    return output\n\n\ndef get_same_padding_conv3d(image_size=None):\n    \"\"\" Chooses static padding if you have specified an image size, and dynamic padding otherwise.\n        Static padding is necessary for ONNX exporting of models. \"\"\"\n    if image_size is None:\n        return Conv3dDynamicSamePadding\n    else:\n        return partial(Conv3dStaticSamePadding, image_size=image_size)\n\n\nclass Conv3dDynamicSamePadding(nn.Conv3d):\n    \"\"\" 3D Convolutions like TensorFlow, for a dynamic image size \"\"\"\n\n    def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, groups=1, bias=True):\n        super().__init__(in_channels, out_channels, kernel_size, stride, 0, dilation, groups, bias)\n        self.stride = self.stride if len(self.stride) == 3 else [self.stride[0]] * 3\n\n    def forward(self, x):\n        ih, iw, iz = x.size()[-3:]\n        kh, kw, kz = self.weight.size()[-3:]\n        sh, sw, sz = self.stride\n        oh, ow, oz = math.ceil(ih / sh), math.ceil(iw / sw), math.ceil(iz / oz)\n        pad_h = max((oh - 1) * self.stride[0] + (kh - 1) * self.dilation[0] + 1 - ih, 0)\n        pad_w = max((ow - 1) * self.stride[1] + (kw - 1) * self.dilation[1] + 1 - iw, 0)\n        pad_z = max((oz - 1) * self.stride[2] + (kz - 1) * self.dilation[2] + 1 - iz, 0)\n        if pad_h > 0 or pad_w > 0 or pad_z > 0:\n            x = F.pad(x, [pad_w // 2, pad_w - pad_w // 2, pad_h // 2, pad_h - pad_h // 2, pad_z // 2, pad_z - pad_z // 2])\n        return F.conv3d(x, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups)\n\n\nclass Conv3dStaticSamePadding(nn.Conv3d):\n    \"\"\" 3D Convolutions like TensorFlow, for a fixed image size\"\"\"\n\n    def __init__(self, in_channels, out_channels, kernel_size, image_size=None, **kwargs):\n        super().__init__(in_channels, out_channels, kernel_size, **kwargs)\n        self.stride = self.stride if len(self.stride) == 3 else [self.stride[0]] * 3\n\n        # Calculate padding based on image size and save it\n        assert image_size is not None\n        ih, iw, iz = image_size if type(image_size) == list else [image_size, image_size, image_size]\n        kh, kw, kz = self.weight.size()[-3:]\n        sh, sw, sz = self.stride\n        oh, ow, oz = math.ceil(ih / sh), math.ceil(iw / sw), math.ceil(iz / sz)\n        pad_h = max((oh - 1) * self.stride[0] + (kh - 1) * self.dilation[0] + 1 - ih, 0)\n        pad_w = max((ow - 1) * self.stride[1] + (kw - 1) * self.dilation[1] + 1 - iw, 0)\n        pad_z = max((oz - 1) * self.stride[2] + (kz - 1) * self.dilation[2] + 1 - iz, 0)\n        if pad_h > 0 or pad_w > 0 or pad_z > 0:\n            self.static_padding = nn.ZeroPad2d((pad_w // 2, pad_w - pad_w // 2, pad_h // 2, pad_h - pad_h // 2, pad_z // 2, pad_z - pad_z // 2))\n        else:\n            self.static_padding = Identity()\n\n    def forward(self, x):\n        x = self.static_padding(x)\n        x = F.conv3d(x, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups)\n        return x\n\n\nclass Identity(nn.Module):\n    def __init__(self, ):\n        super(Identity, self).__init__()\n\n    def forward(self, input):\n        return input\n\n\n########################################################################\n############## HELPERS FUNCTIONS FOR LOADING MODEL PARAMS ##############\n########################################################################\n\n\ndef efficientnet_params(model_name):\n    \"\"\" Map EfficientNet model name to parameter coefficients. \"\"\"\n    params_dict = {\n        # Coefficients:   width,depth,res,dropout\n        'efficientnet-b0': (1.0, 1.0, 224, 0.2),\n        'efficientnet-b1': (1.0, 1.1, 240, 0.2),\n        'efficientnet-b2': (1.1, 1.2, 260, 0.3),\n        'efficientnet-b3': (1.2, 1.4, 300, 0.3),\n        'efficientnet-b4': (1.4, 1.8, 380, 0.4),\n        'efficientnet-b5': (1.6, 2.2, 456, 0.4),\n        'efficientnet-b6': (1.8, 2.6, 528, 0.5),\n        'efficientnet-b7': (2.0, 3.1, 600, 0.5),\n        'efficientnet-b8': (2.2, 3.6, 672, 0.5),\n        'efficientnet-l2': (4.3, 5.3, 800, 0.5),\n    }\n    return params_dict[model_name]\n\n\nclass BlockDecoder(object):\n    \"\"\" Block Decoder for readability, straight from the official TensorFlow repository \"\"\"\n\n    @staticmethod\n    def _decode_block_string(block_string):\n        \"\"\" Gets a block through a string notation of arguments. \"\"\"\n        assert isinstance(block_string, str)\n\n        ops = block_string.split('_')\n        options = {}\n        for op in ops:\n            splits = re.split(r'(\\d.*)', op)\n            if len(splits) >= 2:\n                key, value = splits[:2]\n                options[key] = value\n\n        # Check stride\n        assert (('s' in options and len(options['s']) == 1) or\n                (len(options['s']) == 3 and options['s'][0] == options['s'][1] == options['s'][2]))\n\n        return BlockArgs(\n            kernel_size=int(options['k']),\n            num_repeat=int(options['r']),\n            input_filters=int(options['i']),\n            output_filters=int(options['o']),\n            expand_ratio=int(options['e']),\n            id_skip=('noskip' not in block_string),\n            se_ratio=float(options['se']) if 'se' in options else None,\n            stride=[int(options['s'][0])])\n\n    @staticmethod\n    def _encode_block_string(block):\n        \"\"\"Encodes a block to a string.\"\"\"\n        args = [\n            'r%d' % block.num_repeat,\n            'k%d' % block.kernel_size,\n            's%d%d%d' % (block.strides[0], block.strides[1], block.strides[2]),\n            'e%s' % block.expand_ratio,\n            'i%d' % block.input_filters,\n            'o%d' % block.output_filters\n        ]\n        if 0 < block.se_ratio <= 1:\n            args.append('se%s' % block.se_ratio)\n        if block.id_skip is False:\n            args.append('noskip')\n        return '_'.join(args)\n\n    @staticmethod\n    def decode(string_list):\n        \"\"\"\n        Decodes a list of string notations to specify blocks inside the network.\n\n        :param string_list: a list of strings, each string is a notation of block\n        :return: a list of BlockArgs namedtuples of block args\n        \"\"\"\n        assert isinstance(string_list, list)\n        blocks_args = []\n        for block_string in string_list:\n            blocks_args.append(BlockDecoder._decode_block_string(block_string))\n        return blocks_args\n\n    @staticmethod\n    def encode(blocks_args):\n        \"\"\"\n        Encodes a list of BlockArgs to a list of strings.\n\n        :param blocks_args: a list of BlockArgs namedtuples of block args\n        :return: a list of strings, each string is a notation of block\n        \"\"\"\n        block_strings = []\n        for block in blocks_args:\n            block_strings.append(BlockDecoder._encode_block_string(block))\n        return block_strings\n\n\ndef efficientnet3d(width_coefficient=None, depth_coefficient=None, dropout_rate=0.2,\n                 drop_connect_rate=0.2, image_size=None, num_classes=1000):\n    \"\"\" Creates a efficientnet model. \"\"\"\n\n    blocks_args = [\n        'r1_k3_s222_e1_i32_o16_se0.25', 'r2_k3_s222_e6_i16_o24_se0.25',\n        'r2_k5_s222_e6_i24_o40_se0.25', 'r3_k3_s222_e6_i40_o80_se0.25',\n        'r3_k5_s111_e6_i80_o112_se0.25', 'r4_k5_s222_e6_i112_o192_se0.25',\n        'r1_k3_s111_e6_i192_o320_se0.25',\n    ]\n    blocks_args = BlockDecoder.decode(blocks_args)\n\n    global_params = GlobalParams(\n        batch_norm_momentum=0.99,\n        batch_norm_epsilon=1e-3,\n        dropout_rate=dropout_rate,\n        drop_connect_rate=drop_connect_rate,\n        # data_format='channels_last',  # removed, this is always true in PyTorch\n        num_classes=num_classes,\n        width_coefficient=width_coefficient,\n        depth_coefficient=depth_coefficient,\n        depth_divisor=8,\n        min_depth=None,\n        image_size=image_size,\n    )\n\n    return blocks_args, global_params\n\n\ndef get_model_params(model_name, override_params):\n    \"\"\" Get the block args and global params for a given model \"\"\"\n    if model_name.startswith('efficientnet'):\n        w, d, s, p = efficientnet_params(model_name)\n        # note: all models have drop connect rate = 0.2\n        blocks_args, global_params = efficientnet3d(\n            width_coefficient=w, depth_coefficient=d, dropout_rate=p, image_size=s)\n    else:\n        raise NotImplementedError('model name is not pre-defined: %s' % model_name)\n    if override_params:\n        # ValueError will be raised here if override_params has fields not included in global_params.\n        global_params = global_params._replace(**override_params)\n    return blocks_args, global_params\n","metadata":{"execution":{"iopub.status.busy":"2021-08-25T17:30:57.329021Z","iopub.execute_input":"2021-08-25T17:30:57.329400Z","iopub.status.idle":"2021-08-25T17:30:57.382245Z","shell.execute_reply.started":"2021-08-25T17:30:57.329363Z","shell.execute_reply":"2021-08-25T17:30:57.381213Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\n\nclass MBConvBlock3D(nn.Module):\n    \"\"\"\n    Mobile Inverted Residual Bottleneck Block\n\n    Args:\n        block_args (namedtuple): BlockArgs, see above\n        global_params (namedtuple): GlobalParam, see above\n\n    Attributes:\n        has_se (bool): Whether the block contains a Squeeze and Excitation layer.\n    \"\"\"\n\n    def __init__(self, block_args, global_params):\n        super().__init__()\n        self._block_args = block_args\n        self._bn_mom = 1 - global_params.batch_norm_momentum\n        self._bn_eps = global_params.batch_norm_epsilon\n        self.has_se = (self._block_args.se_ratio is not None) and (0 < self._block_args.se_ratio <= 1)\n        self.id_skip = block_args.id_skip  # skip connection and drop connect\n\n        # Get static or dynamic convolution depending on image size\n        Conv3d = get_same_padding_conv3d(image_size=global_params.image_size)\n\n        # Expansion phase\n        inp = self._block_args.input_filters  # number of input channels\n        oup = self._block_args.input_filters * self._block_args.expand_ratio  # number of output channels\n        if self._block_args.expand_ratio != 1:\n            self._expand_conv = Conv3d(in_channels=inp, out_channels=oup, kernel_size=1, bias=False)\n            self._bn0 = nn.BatchNorm3d(num_features=oup, momentum=self._bn_mom, eps=self._bn_eps)\n\n        # Depthwise convolution phase\n        k = self._block_args.kernel_size\n        s = self._block_args.stride\n        self._depthwise_conv = Conv3d(\n            in_channels=oup, out_channels=oup, groups=oup,  # groups makes it depthwise\n            kernel_size=k, stride=s, bias=False)\n        self._bn1 = nn.BatchNorm3d(num_features=oup, momentum=self._bn_mom, eps=self._bn_eps)\n\n        # Squeeze and Excitation layer, if desired\n        if self.has_se:\n            num_squeezed_channels = max(1, int(self._block_args.input_filters * self._block_args.se_ratio))\n            self._se_reduce = Conv3d(in_channels=oup, out_channels=num_squeezed_channels, kernel_size=1)\n            self._se_expand = Conv3d(in_channels=num_squeezed_channels, out_channels=oup, kernel_size=1)\n\n        # Output phase\n        final_oup = self._block_args.output_filters\n        self._project_conv = Conv3d(in_channels=oup, out_channels=final_oup, kernel_size=1, bias=False)\n        self._bn2 = nn.BatchNorm3d(num_features=final_oup, momentum=self._bn_mom, eps=self._bn_eps)\n        self._swish = MemoryEfficientSwish()\n\n    def forward(self, inputs, drop_connect_rate=None):\n        \"\"\"\n        :param inputs: input tensor\n        :param drop_connect_rate: drop connect rate (float, between 0 and 1)\n        :return: output of block\n        \"\"\"\n\n        # Expansion and Depthwise Convolution\n        x = inputs\n        if self._block_args.expand_ratio != 1:\n            x = self._swish(self._bn0(self._expand_conv(inputs)))\n        x = self._swish(self._bn1(self._depthwise_conv(x)))\n\n        # Squeeze and Excitation\n        if self.has_se:\n            x_squeezed = F.adaptive_avg_pool3d(x, 1)\n            x_squeezed = self._se_expand(self._swish(self._se_reduce(x_squeezed)))\n            x = torch.sigmoid(x_squeezed) * x\n\n        x = self._bn2(self._project_conv(x))\n\n        # Skip connection and drop connect\n        input_filters, output_filters = self._block_args.input_filters, self._block_args.output_filters\n        if self.id_skip and self._block_args.stride == 1 and input_filters == output_filters:\n            if drop_connect_rate:\n                x = drop_connect(x, p=drop_connect_rate, training=self.training)\n            x = x + inputs  # skip connection\n        return x\n\n    def set_swish(self, memory_efficient=True):\n        \"\"\"Sets swish function as memory efficient (for training) or standard (for export)\"\"\"\n        self._swish = MemoryEfficientSwish() if memory_efficient else Swish()\n\n\nclass EfficientNet3D(nn.Module):\n    \"\"\"\n    An EfficientNet model. Most easily loaded with the .from_name or .from_pretrained methods\n\n    Args:\n        blocks_args (list): A list of BlockArgs to construct blocks\n        global_params (namedtuple): A set of GlobalParams shared between blocks\n\n    Example:\n        model = EfficientNet3D.from_pretrained('efficientnet-b0')\n\n    \"\"\"\n\n    def __init__(self, blocks_args=None, global_params=None, in_channels=3):\n        super().__init__()\n        assert isinstance(blocks_args, list), 'blocks_args should be a list'\n        assert len(blocks_args) > 0, 'block args must be greater than 0'\n        self._global_params = global_params\n        self._blocks_args = blocks_args\n\n        # Get static or dynamic convolution depending on image size\n        Conv3d = get_same_padding_conv3d(image_size=global_params.image_size)\n\n        # Batch norm parameters\n        bn_mom = 1 - self._global_params.batch_norm_momentum\n        bn_eps = self._global_params.batch_norm_epsilon\n\n        # Stem\n        out_channels = round_filters(32, self._global_params)  # number of output channels\n        self._conv_stem = Conv3d(in_channels, out_channels, kernel_size=3, stride=2, bias=False)\n        self._bn0 = nn.BatchNorm3d(num_features=out_channels, momentum=bn_mom, eps=bn_eps)\n\n        # Build blocks\n        self._blocks = nn.ModuleList([])\n        for block_args in self._blocks_args:\n\n            # Update block input and output filters based on depth multiplier.\n            block_args = block_args._replace(\n                input_filters=round_filters(block_args.input_filters, self._global_params),\n                output_filters=round_filters(block_args.output_filters, self._global_params),\n                num_repeat=round_repeats(block_args.num_repeat, self._global_params)\n            )\n\n            # The first block needs to take care of stride and filter size increase.\n            self._blocks.append(MBConvBlock3D(block_args, self._global_params))\n            if block_args.num_repeat > 1:\n                block_args = block_args._replace(input_filters=block_args.output_filters, stride=1)\n            for _ in range(block_args.num_repeat - 1):\n                self._blocks.append(MBConvBlock3D(block_args, self._global_params))\n\n        # Head\n        in_channels = block_args.output_filters  # output of final block\n        out_channels = round_filters(1280, self._global_params)\n        self._conv_head = Conv3d(in_channels, out_channels, kernel_size=1, bias=False)\n        self._bn1 = nn.BatchNorm3d(num_features=out_channels, momentum=bn_mom, eps=bn_eps)\n\n        # Final linear layer\n        self._avg_pooling = nn.AdaptiveAvgPool3d(1)\n        self._dropout = nn.Dropout(self._global_params.dropout_rate)\n        self._fc = nn.Linear(out_channels, self._global_params.num_classes)\n        self._swish = MemoryEfficientSwish()\n\n    def set_swish(self, memory_efficient=True):\n        \"\"\"Sets swish function as memory efficient (for training) or standard (for export)\"\"\"\n        self._swish = MemoryEfficientSwish() if memory_efficient else Swish()\n        for block in self._blocks:\n            block.set_swish(memory_efficient)\n\n\n    def extract_features(self, inputs):\n        \"\"\" Returns output of the final convolution layer \"\"\"\n\n        # Stem\n        x = self._swish(self._bn0(self._conv_stem(inputs)))\n\n        # Blocks\n        for idx, block in enumerate(self._blocks):\n            drop_connect_rate = self._global_params.drop_connect_rate\n            if drop_connect_rate:\n                drop_connect_rate *= float(idx) / len(self._blocks)\n            x = block(x, drop_connect_rate=drop_connect_rate)\n\n        # Head\n        x = self._swish(self._bn1(self._conv_head(x)))\n\n        return x\n\n    def forward(self, inputs):\n        \"\"\" Calls extract_features to extract features, applies final linear layer, and returns logits. \"\"\"\n        bs = inputs.size(0)\n        # Convolution layers\n        x = self.extract_features(inputs)\n\n        # Pooling and final linear layer\n        x = self._avg_pooling(x)\n        x = x.view(bs, -1)\n        x = self._dropout(x)\n        x = self._fc(x)\n        return x\n\n    @classmethod\n    def from_name(cls, model_name, override_params=None, in_channels=3):\n        cls._check_model_name_is_valid(model_name)\n        blocks_args, global_params = get_model_params(model_name, override_params)\n        return cls(blocks_args, global_params, in_channels)\n\n    @classmethod\n    def get_image_size(cls, model_name):\n        cls._check_model_name_is_valid(model_name)\n        _, _, res, _ = efficientnet_params(model_name)\n        return res\n\n    @classmethod\n    def _check_model_name_is_valid(cls, model_name):\n        \"\"\" Validates model name. \"\"\" \n        valid_models = ['efficientnet-b'+str(i) for i in range(9)]\n        if model_name not in valid_models:\n            raise ValueError('model_name should be one of: ' + ', '.join(valid_models))","metadata":{"execution":{"iopub.status.busy":"2021-08-25T17:30:57.383941Z","iopub.execute_input":"2021-08-25T17:30:57.384323Z","iopub.status.idle":"2021-08-25T17:30:57.419576Z","shell.execute_reply.started":"2021-08-25T17:30:57.384266Z","shell.execute_reply":"2021-08-25T17:30:57.418615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import sys\n# sys.path.append('../input/efficientnetpyttorch3d/EfficientNet-PyTorch-3D')\n# from efficientnet_pytorch_3d import EfficientNet3D\n\nnet = EfficientNet3D.from_name(\"efficientnet-b4\", override_params={'num_classes': 1}, in_channels=4)\n","metadata":{"execution":{"iopub.status.busy":"2021-08-25T17:30:57.421907Z","iopub.execute_input":"2021-08-25T17:30:57.422330Z","iopub.status.idle":"2021-08-25T17:30:57.629889Z","shell.execute_reply.started":"2021-08-25T17:30:57.422289Z","shell.execute_reply":"2021-08-25T17:30:57.629014Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df = pd.read_csv(\"../input/rsna-miccai-brain-tumor-radiogenomic-classification/sample_submission.csv\", dtype={'BraTS21ID': str})\n","metadata":{"execution":{"iopub.status.busy":"2021-08-25T17:30:57.632483Z","iopub.execute_input":"2021-08-25T17:30:57.633002Z","iopub.status.idle":"2021-08-25T17:30:57.646641Z","shell.execute_reply.started":"2021-08-25T17:30:57.632963Z","shell.execute_reply":"2021-08-25T17:30:57.645732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_image_plane(data):\n    x1, y1, _, x2, y2, _ = [round(j) for j in data.ImageOrientationPatient]\n    cords = [x1, y1, x2, y2]\n\n    if cords == [1, 0, 0, 0]:\n        return 'Coronal'\n    elif cords == [1, 0, 0, 1]:\n        return 'Axial'\n    elif cords == [0, 1, 0, 0]:\n        return 'Sagittal'\n    else:\n        return 'Unknown'\n\ndef get_voxel(study_id, scan_type):\n    imgs = []\n    dcm_dir = Config.data_dir / study_id / scan_type\n    dcm_paths = sorted(dcm_dir.glob(\"*.dcm\"), key=lambda x: int(x.stem.split(\"-\")[-1]))\n    positions = []\n    for dcm_path in dcm_paths:\n        img = pydicom.dcmread(str(dcm_path))\n        imgs.append(img.pixel_array)\n        positions.append(img.ImagePositionPatient)\n        \n    plane = get_image_plane(img)\n    voxel = np.stack(imgs)\n    \n    # reorder planes if needed and rotate voxel\n    if plane == \"Coronal\":\n        if positions[0][1] < positions[-1][1]:\n            voxel = voxel[::-1]\n            print(f\"{study_id} {scan_type} {plane} reordered\")\n        voxel = voxel.transpose((1, 0, 2))\n    elif plane == \"Sagittal\":\n        if positions[0][0] < positions[-1][0]:\n            voxel = voxel[::-1]\n            print(f\"{study_id} {scan_type} {plane} reordered\")\n        voxel = voxel.transpose((1, 2, 0))\n        voxel = np.rot90(voxel, 2, axes=(1, 2))\n    elif plane == \"Axial\":\n        if positions[0][2] > positions[-1][2]:\n            voxel = voxel[::-1]\n            print(f\"{study_id} {scan_type} {plane} reordered\")\n        voxel = np.rot90(voxel, 2)\n    else:\n        raise ValueError(f\"Unknown plane {plane}\")\n    return voxel, plane\n\n\ndef normalize_contrast(voxel):\n    if voxel.sum() == 0:\n        return voxel\n    voxel = voxel - np.min(voxel)\n    voxel = voxel / np.max(voxel)\n    voxel = (voxel * 255).astype(np.uint8)\n    return voxel\n\ndef crop_voxel(voxel):\n    if voxel.sum() == 0:\n        return voxel\n    keep = (voxel.mean(axis=(0, 1)) > 0)\n    voxel = voxel[:, :, keep]\n    keep = (voxel.mean(axis=(0, 2)) > 0)\n    voxel = voxel[:, keep]\n    keep = (voxel.mean(axis=(1, 2)) > 0)\n    voxel = voxel[keep]\n    return voxel\n\ndef resize_voxel(voxel, sz=64):\n    output = np.zeros((sz, sz, sz), dtype=np.uint8)\n\n    if np.argmax(voxel.shape) == 0:\n        for i, s in enumerate(np.linspace(0, voxel.shape[0] - 1, sz)):\n            output[i] = cv2.resize(voxel[int(s)], (sz, sz))\n    elif np.argmax(voxel.shape) == 1:\n        for i, s in enumerate(np.linspace(0, voxel.shape[1] - 1, sz)):\n            output[:, i] = cv2.resize(voxel[:, int(s)], (sz, sz))\n    elif np.argmax(voxel.shape) == 2:\n        for i, s in enumerate(np.linspace(0, voxel.shape[2] - 1, sz)):\n            output[:, :, i] = cv2.resize(voxel[:, :, int(s)], (sz, sz))\n\n    return output","metadata":{"execution":{"iopub.status.busy":"2021-08-25T17:30:57.647937Z","iopub.execute_input":"2021-08-25T17:30:57.648250Z","iopub.status.idle":"2021-08-25T17:30:57.668656Z","shell.execute_reply.started":"2021-08-25T17:30:57.648218Z","shell.execute_reply":"2021-08-25T17:30:57.667707Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_volume(dp_id, split=\"test\"):\n    mri_volumes = []\n    for mri_type in Config.mri_types:\n        volume = np.load(Config.data_dir / split / dp_id / f'{mri_type}.npy')\n        mri_volumes.append(volume)\n        \n    mri_volumes = np.stack(mri_volumes)\n    mri_volumes = mri_volumes / 255\n    mri_volumes = mri_volumes - mri_volumes.mean()\n\n    return mri_volumes\n\nclass DataRetriever(Dataset):\n    def __init__(self, paths, files_dir, mri_types, targets=None):\n        \n        self.paths = paths\n        self.targets = targets\n        self.files_dir = files_dir\n        self.mri_types = mri_types \n        \n        if self.targets is None:\n            self.split = 'test'\n        else:\n            self.split = 'train'\n        \n    def __len__(self):\n        return len(self.paths)\n    \n    def __getitem__(self, index):\n        study_id = self.paths[index]\n        \n        mri_volumes = []\n        for mri_type in self.mri_types:\n            volume, _ = get_voxel(study_id, mri_type)\n            volume = normalize_contrast(volume)\n            volume = crop_voxel(volume)\n            volume = resize_voxel(volume, sz=128)\n            mri_volumes.append(volume)\n            \n        mri_volumes = np.stack(mri_volumes)\n        mri_volumes = mri_volumes / 255\n        mri_volumes = mri_volumes - mri_volumes.mean()     \n#         for i in range(4):\n#             plt.imshow(mri_volumes[i, 64], cmap='gray')\n#             plt.show()\n                    \n        if not self.targets is None:\n            y = torch.tensor(abs(self.targets[index]), dtype=torch.float)\n        else:\n            y = []\n            \n        return {\"X\": torch.tensor(mri_volumes).float(), 'y': y}","metadata":{"execution":{"iopub.status.busy":"2021-08-25T17:30:57.670109Z","iopub.execute_input":"2021-08-25T17:30:57.670595Z","iopub.status.idle":"2021-08-25T17:30:57.683421Z","shell.execute_reply.started":"2021-08-25T17:30:57.670557Z","shell.execute_reply":"2021-08-25T17:30:57.682613Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ds = DataRetriever(\n    test_df[\"BraTS21ID\"].values,        \n    '../input/rsna-miccai-brain-tumor-radiogenomic-classification/test',\n    mri_types=Config.mri_types\n)\n\nf_study = test_ds[0]","metadata":{"execution":{"iopub.status.busy":"2021-08-25T17:30:57.684835Z","iopub.execute_input":"2021-08-25T17:30:57.685274Z","iopub.status.idle":"2021-08-25T17:31:04.700110Z","shell.execute_reply.started":"2021-08-25T17:30:57.685239Z","shell.execute_reply":"2021-08-25T17:31:04.699260Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Model(pl.LightningModule):\n    def __init__(self, net):\n        super().__init__()\n\n        self.net = net\n    \n    def forward(self, x):\n        out = self.net(x)\n        return out\n    \n    def training_step(self, batch, batch_idx):\n        X, y = batch['X'], batch['y']\n        y_hat = self(X).squeeze(1)\n        loss = F.binary_cross_entropy_with_logits(y_hat, y)  \n        \n        return {\n            'loss': loss,\n            'y': y,\n            'y_hat': y_hat\n        }\n    \n    \n    def validation_step(self, batch, batch_idx):\n        self.train()\n        X, y = batch['X'], batch['y']\n        y_hat = self(X).squeeze(1)\n        loss = F.binary_cross_entropy_with_logits(y_hat, y)  \n\n        return {\n            'loss': loss,\n            'y': y,\n            'y_hat': y_hat\n        }\n    \n    def predict_step(self, batch, batch_idx: int, dataloader_idx: int = None):\n        self.train()\n        X = batch['X']\n        return self(X)    \n    \n    def configure_optimizers(self):\n        optimizer = torch.optim.Adam(self.parameters(), lr=self.lr)\n        return optimizer","metadata":{"execution":{"iopub.status.busy":"2021-08-25T17:31:04.702358Z","iopub.execute_input":"2021-08-25T17:31:04.702721Z","iopub.status.idle":"2021-08-25T17:31:04.711924Z","shell.execute_reply.started":"2021-08-25T17:31:04.702683Z","shell.execute_reply":"2021-08-25T17:31:04.710797Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"models_folder_path = Path(in_folder_path / 'models')\nn_models = 5\n\nmodel_paths = [\n    '../input/braintumor-train-pl/models/model_0_epoch=8_roc_auc=0.635.ckpt',\n    '../input/braintumor-train-pl/models/model_1_epoch=4_roc_auc=0.599.ckpt',\n    '../input/braintumor-train-pl/models/model_2_epoch=1_roc_auc=0.559.ckpt',\n    '../input/braintumor-train-pl/models/model_3_epoch=9_roc_auc=0.571.ckpt',\n    '../input/braintumor-train-pl/models/model_4_epoch=4_roc_auc=0.55.ckpt'\n]\n\nmri_types_preds = []\n\nfor model_path in model_paths:\n    models_preds = []\n    print(model_path)\n    test_ds = DataRetriever(\n        test_df[\"BraTS21ID\"].values,        \n        '../input/rsna-miccai-brain-tumor-radiogenomic-classification/test',\n        mri_types=Config.mri_types\n\n   )\n    \n    test_dl = DataLoader(\n        test_ds,\n        batch_size=4,\n        shuffle=False,\n        num_workers=8,\n    )\n\n    trainer = pl.Trainer(gpus=1, num_sanity_val_steps=0)\n#     model = Model.load_from_checkpoint(model_path, net=net)\n#     model = Model(net)\n#     preds = trainer.predict(model, test_dl)\n#     flat_preds = []\n#     for p in preds:\n#         flat_preds += p.flatten().tolist()\n\n#     models_preds.append(flat_preds)\n        \n#     mri_types_preds.append(np.array(models_preds).mean(axis=0))","metadata":{"_uuid":"785f7ab5-01f8-4c91-a76c-40c0f9286a94","_cell_guid":"0b990ba7-b05d-4c53-995c-9c4c2de43150","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-08-25T17:31:04.713561Z","iopub.execute_input":"2021-08-25T17:31:04.713913Z","iopub.status.idle":"2021-08-25T17:31:04.736721Z","shell.execute_reply.started":"2021-08-25T17:31:04.713876Z","shell.execute_reply":"2021-08-25T17:31:04.735550Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"avg_mri_types_preds = np.array(mri_types_preds).mean(axis=0)","metadata":{"execution":{"iopub.status.busy":"2021-08-25T17:31:04.738320Z","iopub.execute_input":"2021-08-25T17:31:04.738679Z","iopub.status.idle":"2021-08-25T17:31:04.745936Z","shell.execute_reply.started":"2021-08-25T17:31:04.738643Z","shell.execute_reply":"2021-08-25T17:31:04.745003Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame({\"BraTS21ID\": test_df.BraTS21ID})\nsubmission['MGMT_value'] = 0.4\nsubmission.to_csv(\"submission.csv\", index=False)\nsubmission.head(30)","metadata":{"_uuid":"3d8cc2be-46e9-43af-ae99-e4e545c8b5ca","_cell_guid":"4764a32d-5781-4187-b681-a3259565122c","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-08-25T17:31:04.747760Z","iopub.execute_input":"2021-08-25T17:31:04.748180Z","iopub.status.idle":"2021-08-25T17:31:04.767242Z","shell.execute_reply.started":"2021-08-25T17:31:04.748144Z","shell.execute_reply":"2021-08-25T17:31:04.766211Z"},"trusted":true},"execution_count":null,"outputs":[]}]}