text_html_output_1.png
from albumentations import Compose, HorizontalFlip

from skimage.transform import resize

from torch.utils.data import Dataset, DataLoader

from torch.utils.data import Dataset,DataLoader

import SimpleITK as sitk

import SimpleITK as sitk

import numpy as np

import numpy as np

import numpy as np

import numpy as np

import os

import os

import os

import os

import pandas as pd

import pandas as pd

import torch

import torch

import torch

import torch.nn as nn

import torch.nn as nn

import torch.nn.functional as F

import torch.nn.functional as F

labels = pd.read_csv('../input/rsna-miccai-brain-tumor-radiogenomic-classification/train_labels.csv')

data_len = 1000
labels['imfolder'] = ['{0:05d}'.format(s) for s in labels['BraTS21ID']]
path = '../input/rsna-miccai-brain-tumor-radiogenomic-classification/test/'
labels['path'] = [os.path.join(path, f) for f in labels['imfolder']]
train = labels[:data_len]
val_len = int(data_len * 0.2)

train = labels[:0]
path = '../input/rsna-miccai-brain-tumor-radiogenomic-classification/test/'
p = []
d = []
for i in range(1010):
    id_ = '{0:05d}'.format(i)
    if os.path.exists(path + id_):
        p.append(path + id_)
        d.append(id_)

def load(path, kind, image_size=128, depth=64):
    directory = path + '/' + kind
    reader = sitk.ImageSeriesReader()
    dicom_names = reader.GetGDCMSeriesFileNames(directory)
    reader.SetFileNames(dicom_names)
    image = reader.Execute()
    image = sitk.GetArrayFromImage(image)
    mid = int(image.shape[0] / 2)
    if image.shape[0] >= 64:
        image = image[mid - 32:mid + 32, :, :]
    image = resize(image, (64, 128, 128), preserve_range=True)
    image = torch.tensor(image)
    return image

class BratsDataset(Dataset):
    def __init__(self, df: pd.DataFrame, phase: str='test', is_resize: bool=False):
        self.df = df
        self.phase = phase
        self.augmentations = get_augmentations(phase)
        self.data_types = ['FLAIR', 'T1w', 'T1wCE', 'T2w']
        self.is_resize = is_resize
    def __len__(self):
        return self.df.shape[0]
    def __getitem__(self, idx):
        id_ = self.df['imfolder'][idx]
        path = self.df['path'][idx]
        id_ = str(id_)
        images = []
        for data_type in self.data_types:
            img_path = path
            img = self.load_img(img_path, data_type)
            img = img.reshape(64, 128, 128)
            img = img.numpy()
            img = self.normalize(img)
            images.append(img)
        img = np.stack(images)
        img = np.moveaxis(img, (0, 1, 2, 3), (0, 3, 2, 1))
        if self.phase != 'test':
            augmented = self.augmentations(image=img.astype(np.float32))
            img = augmented['image']
            return {'Id': id_, 'image': img}
        return {'Id': id_, 'image': img}
    def load_img(self, file_path, data_type):
        data = load(file_path, data_type)
        return data
    def normalize(self, data: np.ndarray):
        data_min = 0
        return (data - data_min) / (np.amax(data) - data_min)

def get_augmentations(phase):
    list_transforms = []
    list_trfms = Compose(list_transforms)
    return list_trfms
def get_dataloader(dataset: torch.utils.data.Dataset, path_to_csv: str, phase: str, fold: int=0, batch_size: int=1, num_workers: int=0):
    """Returns: dataloader for the model training"""
    df = pd.read_csv(path_to_csv)
    dataset = dataset(df, phase)
    dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, pin_memory=False, shuffle=True)
    return dataloader

class DoubleConv(nn.Module):
    """(Conv3D -> BN -> ReLU) * 2"""
    def __init__(self, in_channels, out_channels, num_groups=8):
        super().__init__()
        self.double_conv = nn.Sequential(nn.Conv3d(in_channels, out_channels, kernel_size=3, stride=1, padding=1), nn.GroupNorm(num_groups=num_groups, num_channels=out_channels), nn.ReLU(inplace=True), nn.Conv3d(out_channels, out_channels, kernel_size=3, stride=1, padding=1), nn.GroupNorm(num_groups=num_groups, num_channels=out_channels), nn.ReLU(inplace=True))
    def forward(self, x):
        return self.double_conv(x)
class Down(nn.Module):
    def __init__(self, in_channels, out_channels):
        super().__init__()
        self.encoder = nn.Sequential(nn.MaxPool3d(2, 2), DoubleConv(in_channels, out_channels))
    def forward(self, x):
        return self.encoder(x)
class Up(nn.Module):
    def __init__(self, in_channels, out_channels, trilinear=False):
        super().__init__()
        if trilinear:
            self.up = nn.Upsample(scale_factor=2, mode='trilinear', align_corners=True)
        else:
            self.up = nn.ConvTranspose3d(in_channels // 2, in_channels // 2, kernel_size=2, stride=2)
        self.conv = DoubleConv(in_channels, out_channels)
    def forward(self, x1, x2):
        x1 = self.up(x1)
        diffZ = x2.size()[2] - x1.size()[2]
        diffY = x2.size()[3] - x1.size()[3]
        diffX = x2.size()[4] - x1.size()[4]
        x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2, diffY // 2, diffY - diffY // 2, diffZ // 2, diffZ - diffZ // 2])
        x = torch.cat([x2, x1], dim=1)
        return self.conv(x)
class Out(nn.Module):
    def __init__(self, in_channels, out_channels):
        super().__init__()
        self.conv = nn.Conv3d(in_channels, out_channels, kernel_size=1)
    def forward(self, x):
        return self.conv(x)
class UNet3d(nn.Module):
    def __init__(self, in_channels, n_classes, n_channels):
        super().__init__()
        self.in_channels = in_channels
        self.n_classes = n_classes
        self.n_channels = n_channels
        self.conv = DoubleConv(in_channels, n_channels)
        self.enc1 = Down(n_channels, 2 * n_channels)
        self.enc2 = Down(2 * n_channels, 4 * n_channels)
        self.enc3 = Down(4 * n_channels, 8 * n_channels)
        self.enc4 = Down(8 * n_channels, 8 * n_channels)
        self.dec1 = Up(16 * n_channels, 4 * n_channels)
        self.dec2 = Up(8 * n_channels, 2 * n_channels)
        self.dec3 = Up(4 * n_channels, n_channels)
        self.dec4 = Up(2 * n_channels, n_channels)
        self.out = Out(n_channels, n_classes)
    def forward(self, x):
        x1 = self.conv(x)
        x2 = self.enc1(x1)
        x3 = self.enc2(x2)
        x4 = self.enc3(x3)
        x5 = self.enc4(x4)
        mask = self.dec1(x5, x4)
        mask = self.dec2(mask, x3)
        mask = self.dec3(mask, x2)
        mask = self.dec4(mask, x1)
        mask = self.out(mask)
        return mask

model = UNet3d(in_channels=4, n_classes=3, n_channels=24)

model.load_state_dict(torch.load('../input/seg-model/best_model_0.17.pth'))