{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"!conda install gdcm -c conda-forge -y","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport gdcm\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models\nfrom torchvision.datasets import ImageNet\nimport matplotlib.pyplot as plt\nimport pydicom\nfrom skimage import io, transform\nfrom torch.utils.data import Dataset, DataLoader\nimport glob\nprint(\"Imports Done\")\ninput_dir = glob.glob('../input/rsna-str-pulmonary-embolism-detection/train/*/*/*.dcm')\nprint(\"Imports Done\")\n# Ignore warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nplt.ion()   # interactive mode","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain_file,test_file= train_test_split(input_dir,test_size = 0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(train_file)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def y_data(test_file):\n    f=test_file\n    StudyInstanceUID = f.split('/')[-3]\n    SeriesInstanceUID = f.split('/')[-2]\n    SOPInstanceUID = f.split('/')[-1].split('.')[0]\n    csv_data = pd.read_csv('../input/rsna-str-pulmonary-embolism-detection/train.csv')\n    dat = csv_data[csv_data['StudyInstanceUID']==StudyInstanceUID][csv_data['SeriesInstanceUID']==SeriesInstanceUID][csv_data['SOPInstanceUID']==SOPInstanceUID]\n    y = dat.drop(columns=['StudyInstanceUID','SeriesInstanceUID','SOPInstanceUID']).values\n    return np.squeeze(y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class trainDataset(Dataset):\n    def __init__(self,file_list,csv_file, transform=None):\n        self.csv_file = pd.read_csv(csv_file)\n        self.file_list = file_list\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.file_list)\n\n    def __getitem__(self, index):\n        imagepath = self.file_list[index]\n        image = pydicom.dcmread(imagepath)\n        image = image.pixel_array\n        image = image.astype(np.float32())\n        image_train = torch.from_numpy(image)\n        image_train = image_train.unsqueeze(0)\n        \n        y = y_data(imagepath)\n        y = y.astype(np.float32())\n        y_train = torch.from_numpy(y)\n        if self.transform:\n            sample = self.transform(sample)\n        return image_train, y_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dataset = trainDataset(file_list=train_file,csv_file='../input/rsna-str-pulmonary-embolism-detection/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def validy_data(test_file):\n    f=test_file\n    StudyInstanceUID = f.split('/')[-3]\n    SeriesInstanceUID = f.split('/')[-2]\n    SOPInstanceUID = f.split('/')[-1].split('.')[0]\n    csv_data = pd.read_csv('../input/rsna-str-pulmonary-embolism-detection/train.csv')\n    dat = csv_data[csv_data['StudyInstanceUID']==StudyInstanceUID][csv_data['SeriesInstanceUID']==SeriesInstanceUID][csv_data['SOPInstanceUID']==SOPInstanceUID]\n    y = dat.drop(columns=['StudyInstanceUID','SeriesInstanceUID','SOPInstanceUID']).values\n    return np.squeeze(y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class validDataset(Dataset):\n    def __init__(self,file_list,csv_file, transform=None):\n        self.csv_file = pd.read_csv(csv_file)\n        self.file_list = file_list\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.file_list)\n\n    def __getitem__(self, index):\n        imagepath = self.file_list[index]\n        image = pydicom.dcmread(imagepath)\n        image = image.pixel_array\n        image = image.astype(np.float32)\n        image_valid = torch.from_numpy(image) \n        image_valid = image_valid.unsqueeze(0)\n        \n        y = validy_data(imagepath)\n        y = y.astype(np.float32)\n        y_valid = torch.from_numpy(y) \n        if self.transform:\n            sample = self.transform(sample)\n        return image_valid, y_valid","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_dataset = validDataset(file_list=test_file,csv_file='../input/rsna-str-pulmonary-embolism-detection/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for t in train_dataset:\n    print(len(t))\n    print(type(t[0]))\n    print(type(t[1]))\n    print(t[1].shape,t[0].shape)\n    break","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for u in test_dataset:\n    print(u[1].shape)\n    break","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trainloader = DataLoader(train_dataset, batch_size=4, shuffle=True, num_workers=0)\ntestloader = DataLoader(test_dataset, batch_size=4, shuffle=True, num_workers=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for s in trainloader:\n    print(s[0].shape)\n    print(s[1].shape)\n    break","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#s[0].shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import torch\nfrom torch import Tensor\nimport torch.nn as nn\nfrom typing import Type, Any, Callable, Union, List, Optional\nfrom torch.hub import load_state_dict_from_url\n#from torch.utils.model_zoo import load_url as load_state_dict_from_url\n\n\n__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',\n           'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',\n           'wide_resnet50_2', 'wide_resnet101_2']\n\n\nmodel_urls = {\n    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\n    'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\n    'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n    'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n    'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\n    'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',\n    'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',\n    'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',\n    'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',\n}\n\n\ndef conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d:\n    \"\"\"3x3 convolution with padding\"\"\"\n    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n                     padding=dilation, groups=groups, bias=False, dilation=dilation)\n\n\ndef conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:\n    \"\"\"1x1 convolution\"\"\"\n    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass BasicBlock(nn.Module):\n    expansion: int = 1\n\n    def __init__(\n        self,\n        inplanes: int,\n        planes: int,\n        stride: int = 1,\n        downsample: Optional[nn.Module] = None,\n        groups: int = 1,\n        base_width: int = 64,\n        dilation: int = 1,\n        norm_layer: Optional[Callable[..., nn.Module]] = None\n    ) -> None:\n        super(BasicBlock, self).__init__()\n        if norm_layer is None:\n            norm_layer = nn.BatchNorm2d\n        if groups != 1 or base_width != 64:\n            raise ValueError('BasicBlock only supports groups=1 and base_width=64')\n        if dilation > 1:\n            raise NotImplementedError(\"Dilation > 1 not supported in BasicBlock\")\n        # Both self.conv1 and self.downsample layers downsample the input when stride != 1\n        self.conv1 = conv3x3(inplanes, planes, stride)\n        self.bn1 = norm_layer(planes)\n        self.relu = nn.ReLU(inplace=True)\n        self.conv2 = conv3x3(planes, planes)\n        self.bn2 = norm_layer(planes)\n        self.downsample = downsample\n        self.stride = stride\n\n    def forward(self, x: Tensor) -> Tensor:\n        identity = x\n\n        out = self.conv1(x)\n        out = self.bn1(out)\n        out = self.relu(out)\n\n        out = self.conv2(out)\n        out = self.bn2(out)\n\n        if self.downsample is not None:\n            identity = self.downsample(x)\n\n        out += identity\n        out = self.relu(out)\n\n        return out\n\n\nclass Bottleneck(nn.Module):\n    # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)\n    # while original implementation places the stride at the first 1x1 convolution(self.conv1)\n    # according to \"Deep residual learning for image recognition\"https://arxiv.org/abs/1512.03385.\n    # This variant is also known as ResNet V1.5 and improves accuracy according to\n    # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.\n\n    expansion: int = 4\n\n    def __init__(\n        self,\n        inplanes: int,\n        planes: int,\n        stride: int = 1,\n        downsample: Optional[nn.Module] = None,\n        groups: int = 1,\n        base_width: int = 64,\n        dilation: int = 1,\n        norm_layer: Optional[Callable[..., nn.Module]] = None\n    ) -> None:\n        super(Bottleneck, self).__init__()\n        if norm_layer is None:\n            norm_layer = nn.BatchNorm2d\n        width = int(planes * (base_width / 64.)) * groups\n        # Both self.conv2 and self.downsample layers downsample the input when stride != 1\n        self.conv1 = conv1x1(inplanes, width)\n        self.bn1 = norm_layer(width)\n        self.conv2 = conv3x3(width, width, stride, groups, dilation)\n        self.bn2 = norm_layer(width)\n        self.conv3 = conv1x1(width, planes * self.expansion)\n        self.bn3 = norm_layer(planes * self.expansion)\n        self.relu = nn.ReLU(inplace=True)\n        self.downsample = downsample\n        self.stride = stride\n\n    def forward(self, x: Tensor) -> Tensor:\n        identity = x\n\n        out = self.conv1(x)\n        out = self.bn1(out)\n        out = self.relu(out)\n\n        out = self.conv2(out)\n        out = self.bn2(out)\n        out = self.relu(out)\n\n        out = self.conv3(out)\n        out = self.bn3(out)\n\n        if self.downsample is not None:\n            identity = self.downsample(x)\n\n        out += identity\n        out = self.relu(out)\n\n        return out\n\n\nclass ResNet(nn.Module):\n\n    def __init__(\n        self,\n        block: Type[Union[BasicBlock, Bottleneck]],\n        layers: List[int],\n        num_classes: int = 14,\n        zero_init_residual: bool = False,\n        groups: int = 1,\n        width_per_group: int = 64,\n        replace_stride_with_dilation: Optional[List[bool]] = None,\n        norm_layer: Optional[Callable[..., nn.Module]] = None\n    ) -> None:\n        super(ResNet, self).__init__()\n        if norm_layer is None:\n            norm_layer = nn.BatchNorm2d\n        self._norm_layer = norm_layer\n\n        self.inplanes = 64\n        self.dilation = 1\n        if replace_stride_with_dilation is None:\n            # each element in the tuple indicates if we should replace\n            # the 2x2 stride with a dilated convolution instead\n            replace_stride_with_dilation = [False, False, False]\n        if len(replace_stride_with_dilation) != 3:\n            raise ValueError(\"replace_stride_with_dilation should be None \"\n                             \"or a 3-element tuple, got {}\".format(replace_stride_with_dilation))\n        self.groups = groups\n        self.base_width = width_per_group\n        self.conv1 = nn.Conv2d(1, self.inplanes, kernel_size=7, stride=2, padding=3,\n                               bias=False)\n        self.bn1 = norm_layer(self.inplanes)\n        self.relu = nn.ReLU(inplace=True)\n        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n        self.layer1 = self._make_layer(block, 64, layers[0])\n        self.layer2 = self._make_layer(block, 128, layers[1], stride=2,\n                                       dilate=replace_stride_with_dilation[0])\n        self.layer3 = self._make_layer(block, 256, layers[2], stride=2,\n                                       dilate=replace_stride_with_dilation[1])\n        self.layer4 = self._make_layer(block, 512, layers[3], stride=2,\n                                       dilate=replace_stride_with_dilation[2])\n        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n        self.fc = nn.Linear(512 * block.expansion, num_classes)\n\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d):\n                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n                nn.init.constant_(m.weight, 1)\n                nn.init.constant_(m.bias, 0)\n\n        # Zero-initialize the last BN in each residual branch,\n        # so that the residual branch starts with zeros, and each residual block behaves like an identity.\n        # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677\n        if zero_init_residual:\n            for m in self.modules():\n                if isinstance(m, Bottleneck):\n                    nn.init.constant_(m.bn3.weight, 0)  # type: ignore[arg-type]\n                elif isinstance(m, BasicBlock):\n                    nn.init.constant_(m.bn2.weight, 0)  # type: ignore[arg-type]\n\n    def _make_layer(self, block: Type[Union[BasicBlock, Bottleneck]], planes: int, blocks: int,\n                    stride: int = 1, dilate: bool = False) -> nn.Sequential:\n        norm_layer = self._norm_layer\n        downsample = None\n        previous_dilation = self.dilation\n        if dilate:\n            self.dilation *= stride\n            stride = 1\n        if stride != 1 or self.inplanes != planes * block.expansion:\n            downsample = nn.Sequential(\n                conv1x1(self.inplanes, planes * block.expansion, stride),\n                norm_layer(planes * block.expansion),\n            )\n\n        layers = []\n        layers.append(block(self.inplanes, planes, stride, downsample, self.groups,\n                            self.base_width, previous_dilation, norm_layer))\n        self.inplanes = planes * block.expansion\n        for _ in range(1, blocks):\n            layers.append(block(self.inplanes, planes, groups=self.groups,\n                                base_width=self.base_width, dilation=self.dilation,\n                                norm_layer=norm_layer))\n\n        return nn.Sequential(*layers)\n\n    def _forward_impl(self, x: Tensor) -> Tensor:\n        # See note [TorchScript super()]\n        x = self.conv1(x)\n        x = self.bn1(x)\n        x = self.relu(x)\n        x = self.maxpool(x)\n\n        x = self.layer1(x)\n        x = self.layer2(x)\n        x = self.layer3(x)\n        x = self.layer4(x)\n\n        x = self.avgpool(x)\n        x = torch.flatten(x, 1)\n        x = self.fc(x)\n\n        return x\n\n    def forward(self, x: Tensor) -> Tensor:\n        return self._forward_impl(x)\n\n\ndef _resnet(\n    arch: str,\n    block: Type[Union[BasicBlock, Bottleneck]],\n    layers: List[int],\n    pretrained: bool,\n    progress: bool,\n    **kwargs: Any\n) -> ResNet:\n    model = ResNet(block, layers, **kwargs)\n    if pretrained:\n        state_dict = load_state_dict_from_url(model_urls[arch],\n                                              progress=progress)\n        model.load_state_dict(state_dict)\n    return model\n\n\ndef resnet18(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n    r\"\"\"ResNet-18 model from\n    `\"Deep Residual Learning for Image Recognition\" <https://arxiv.org/pdf/1512.03385.pdf>`_\n    Args:\n        pretrained (bool): If True, returns a model pre-trained on ImageNet\n        progress (bool): If True, displays a progress bar of the download to stderr\n    \"\"\"\n    return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,\n                   **kwargs)\n\n\ndef resnet34(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n    r\"\"\"ResNet-34 model from\n    `\"Deep Residual Learning for Image Recognition\" <https://arxiv.org/pdf/1512.03385.pdf>`_\n    Args:\n        pretrained (bool): If True, returns a model pre-trained on ImageNet\n        progress (bool): If True, displays a progress bar of the download to stderr\n    \"\"\"\n    return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,\n                   **kwargs)\n\n\ndef resnet50(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n    r\"\"\"ResNet-50 model from\n    `\"Deep Residual Learning for Image Recognition\" <https://arxiv.org/pdf/1512.03385.pdf>`_\n    Args:\n        pretrained (bool): If True, returns a model pre-trained on ImageNet\n        progress (bool): If True, displays a progress bar of the download to stderr\n    \"\"\"\n    return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,\n                   **kwargs)\n\n\ndef resnet101(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n    r\"\"\"ResNet-101 model from\n    `\"Deep Residual Learning for Image Recognition\" <https://arxiv.org/pdf/1512.03385.pdf>`_\n    Args:\n        pretrained (bool): If True, returns a model pre-trained on ImageNet\n        progress (bool): If True, displays a progress bar of the download to stderr\n    \"\"\"\n    return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress,\n                   **kwargs)\n\n\ndef resnet152(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n    r\"\"\"ResNet-152 model from\n    `\"Deep Residual Learning for Image Recognition\" <https://arxiv.org/pdf/1512.03385.pdf>`_\n    Args:\n        pretrained (bool): If True, returns a model pre-trained on ImageNet\n        progress (bool): If True, displays a progress bar of the download to stderr\n    \"\"\"\n    return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress,\n                   **kwargs)\n\n\ndef resnext50_32x4d(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n    r\"\"\"ResNeXt-50 32x4d model from\n    `\"Aggregated Residual Transformation for Deep Neural Networks\" <https://arxiv.org/pdf/1611.05431.pdf>`_\n    Args:\n        pretrained (bool): If True, returns a model pre-trained on ImageNet\n        progress (bool): If True, displays a progress bar of the download to stderr\n    \"\"\"\n    kwargs['groups'] = 32\n    kwargs['width_per_group'] = 4\n    return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3],\n                   pretrained, progress, **kwargs)\n\n\ndef resnext101_32x8d(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n    r\"\"\"ResNeXt-101 32x8d model from\n    `\"Aggregated Residual Transformation for Deep Neural Networks\" <https://arxiv.org/pdf/1611.05431.pdf>`_\n    Args:\n        pretrained (bool): If True, returns a model pre-trained on ImageNet\n        progress (bool): If True, displays a progress bar of the download to stderr\n    \"\"\"\n    kwargs['groups'] = 32\n    kwargs['width_per_group'] = 8\n    return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3],\n                   pretrained, progress, **kwargs)\n\n\ndef wide_resnet50_2(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n    r\"\"\"Wide ResNet-50-2 model from\n    `\"Wide Residual Networks\" <https://arxiv.org/pdf/1605.07146.pdf>`_\n    The model is the same as ResNet except for the bottleneck number of channels\n    which is twice larger in every block. The number of channels in outer 1x1\n    convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048\n    channels, and in Wide ResNet-50-2 has 2048-1024-2048.\n    Args:\n        pretrained (bool): If True, returns a model pre-trained on ImageNet\n        progress (bool): If True, displays a progress bar of the download to stderr\n    \"\"\"\n    kwargs['width_per_group'] = 64 * 2\n    return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3],\n                   pretrained, progress, **kwargs)\n\n\ndef wide_resnet101_2(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n    r\"\"\"Wide ResNet-101-2 model from\n    `\"Wide Residual Networks\" <https://arxiv.org/pdf/1605.07146.pdf>`_\n    The model is the same as ResNet except for the bottleneck number of channels\n    which is twice larger in every block. The number of channels in outer 1x1\n    convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048\n    channels, and in Wide ResNet-50-2 has 2048-1024-2048.\n    Args:\n        pretrained (bool): If True, returns a model pre-trained on ImageNet\n        progress (bool): If True, displays a progress bar of the download to stderr\n    \"\"\"\n    kwargs['width_per_group'] = 64 * 2\n    return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3],\n                   pretrained, progress, **kwargs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = resnet50()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = model.cuda()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in model.parameters():\n    i.requires_grad = False\n#model.fc = nn.Sequential(nn.Linear(2048, 14),nn.ReLU(),nn.Dropout(0.2),nn.Linear(512, 10), nn.LogSoftmax(dim=1))\ncriterion = nn.MSELoss()\noptimizer = optim.Adam(model.parameters(), lr=0.003)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from torch.autograd import Variable\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 1\nsteps = 0\nrunning_loss = 0\nprint_every = 10\ntrain_losses, test_losses = [], []\ntrain_acc = 0\nfor epoch in range(epochs):\n    model.train()\n    for b,(image_train, y_train) in enumerate(trainloader):\n        print(b)\n        steps += 1\n        optimizer.zero_grad()\n        image_train, y_train = image_train.cuda(), y_train.cuda()\n        image_train = Variable(image_train,requires_grad=True)\n        logps = model.forward(image_train)\n        loss = criterion(logps, y_train)\n        loss.backward()\n        optimizer.step()\n        running_loss += loss.item()\n        ps = torch.exp(logps)\n        #print('ps',ps)\n        ps = torch.sigmoid(ps)\n        #print('sps',ps)\n        top_p, top_class = ps.topk(14, dim=1)\n        equals = top_class == y_train.view(top_class.shape)\n        acc = torch.mean(equals.type(torch.FloatTensor))\n        train_acc += acc.item()\n        \n    with torch.no_grad():\n        model.eval()\n        for image_valid, y_valid in testloader:\n            image_valid, y_valid = image_train.cuda(), y_train.cuda()\n            image_valid = Variable(image_valid,requires_grad=True)\n            logps = model.forward(image_valid)\n            batch_loss += criterion(logps, y_valid).item()    \n            ps = torch.exp(logps)\n            ps = torch.sigmoid(ps)\n            #print('ps',ps)\n            top_p, top_class = ps.topk(14, dim=1)\n            #print('top_p',top_p)\n            #print('top_class',top_class)\n            equals = top_class == y_valid.view(*top_class.shape)\n            accuracy += torch.mean(equals.type(torch.FloatTensor)).item()\n    train_losses.append(running_loss/len(train_loader))\n    test_losses.append(test_loss/len(valid_loader))                    \n    print(f\"Epoch {epoch+1}/{epochs}.. \"\n          f\"Train loss: {running_loss/print_every:.3f}.. \"\n          f\"Test loss: {test_loss/len(valid_loader):.3f}.. \"\n          f\"Test accuracy: {accuracy/len(valid_loader):.3f}\")\n    if epoch%20 == 0:\n        torch.save(model, './')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"The state dict keys: \\n\\n\", model.state_dict().keys())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"modelpath = {'model': resnet50(),\n              'state_dict': model.state_dict(),\n              'optimizer' : optimizer.state_dict()}\n\ntorch.save(modelpath, './')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"        data, target = data.to(device), target.to(device)\n        image_valid, y_valid = image_train.cuda(), y_train.cuda()\n        output = model(data)\n        loss = criterion(output, target)\n        # update running validation loss \n        valid_loss += loss.item() #*data.size(0)\n        # convert output probabilities to predicted class\n        _, pred = torch.max(output, 1)\n        # compare predictions to true label\n        correct = np.squeeze(pred.eq(target.data.view_as(pred)))\n        # calculate test accuracy for each object class\n        for i in range(16):\n          label = target.data[i]\n          class_correct[label] += correct[i].item()\n          class_total[label] += 1\n        \n        \n    # print training/validation statistics \n    # calculate average loss over an epoch\n    train_loss = train_loss/len(train_loader.dataset)\n    valid_loss = valid_loss/len(test_loader.dataset)\n    \n    #clculate train loss and running loss\n    train_loss_data.append(train_loss)\n    valid_loss_data.append(valid_loss)\n    \n    print('Epoch: {}/{} \\tTraining Loss: {:.6f} \\tValidation Loss: {:.6f}'.format(\n        epoch+1,\n        n_epochs,\n        train_loss,\n        valid_loss\n        ))\n    print('\\t\\tTest Accuracy: %4d%% (%2d/%2d)' % (\n    100. * np.sum(class_correct) / np.sum(class_total),\n    np.sum(class_correct), np.sum(class_total)))\n    if valid_loss <= valid_loss_min:\n        print('\\t\\tValidation loss decreased ({:.6f} --> {:.6f}).  Saving model ...'.format(\n        valid_loss_min,\n        valid_loss))\n        torch.save(model.state_dict(), 'model.pt')\n        valid_loss_min = valid_loss","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learning_rate = 1e-3\nbatch_size = 5\nnum_epochs = 30\ninput_size = 11\nfor epoch in range(1,num_epochs):\n    losses = []\n    for batch_idx,(data, targets) in enumerate(trainoader,testloader):\n        scores = model(data)\n        loss = criterion(scores, targets)\n        losses.append(loss.item())\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n    print(f\"Cost at epoch {epoch} is {sum(losses) / len(losses)}\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(train_dataset,test_dataset)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_epochs = 10\nfor epoch in range(num_epochs):\n    losses = []\n    for x, y in enumerate(trainloader):\n        scores = model(x)\n        loss = criterion(scores, y)\n        losses.append(loss.item())\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n    print(f\"Cost at epoch {epoch} is {sum(losses)/len(losses)}\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"f=train_file[0]\nStudyInstanceUID = f.split('/')[-3]\nSeriesInstanceUID = f.split('/')[-2]\nSOPInstanceUID = f.split('/')[-1].split('.')[0]\ncsv_data = pd.read_csv('../input/rsna-str-pulmonary-embolism-detection/train.csv')\ndat = csv_data[csv_data['StudyInstanceUID']==StudyInstanceUID][csv_data['SeriesInstanceUID']==SeriesInstanceUID][csv_data['SOPInstanceUID']==SOPInstanceUID]\ny = dat.drop(columns=['StudyInstanceUID','SeriesInstanceUID','SOPInstanceUID']).values\nprint(y[0])\nprint(len(y[0]))\nprint(dat.columns)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class_list=['pe_present_on_image', 'negative_exam_for_pe', 'qa_motion',\n       'qa_contrast', 'flow_artifact', 'rv_lv_ratio_gte_1', 'rv_lv_ratio_lt_1',\n       'leftsided_pe', 'chronic_pe', 'true_filling_defect_not_pe',\n       'rightsided_pe', 'acute_and_chronic_pe', 'central_pe', 'indeterminate']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!wget https://github.com/pytorch/vision/blob/master/torchvision/models","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = torch.hub.load('pytorch/vision:v0.6.0', 'resnet50', pretrained=True)","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}