{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "061599cf",
   "metadata": {},
   "source": [
    "A contracting path: capture context.\n",
    "\n",
    "A symmetric expanding path: enables precise localization."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb69fa32",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\" Parts of the U-Net model \"\"\"\n",
    "\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "\n",
    "\n",
    "class DoubleConv(nn.Module):\n",
    "    \"\"\"(convolution => [BN] => ReLU) * 2\"\"\"\n",
    "\n",
    "    def __init__(self, in_channels, out_channels, mid_channels=None):\n",
    "        super().__init__()\n",
    "        if not mid_channels:\n",
    "            mid_channels = out_channels\n",
    "        self.double_conv = nn.Sequential(\n",
    "            nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1),\n",
    "            nn.BatchNorm2d(mid_channels),\n",
    "            nn.ReLU(inplace=True),\n",
    "            nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1),\n",
    "            nn.BatchNorm2d(out_channels),\n",
    "            nn.ReLU(inplace=True)\n",
    "        )\n",
    "\n",
    "    def forward(self, x):\n",
    "        return self.double_conv(x)\n",
    "\n",
    "\n",
    "class Down(nn.Module):\n",
    "    \"\"\"Downscaling with maxpool then double conv\"\"\"\n",
    "\n",
    "    def __init__(self, in_channels, out_channels):\n",
    "        super().__init__()\n",
    "        self.maxpool_conv = nn.Sequential(\n",
    "            nn.MaxPool2d(2),\n",
    "            DoubleConv(in_channels, out_channels)\n",
    "        )\n",
    "\n",
    "    def forward(self, x):\n",
    "        return self.maxpool_conv(x)\n",
    "\n",
    "\n",
    "class Up(nn.Module):\n",
    "    \"\"\"Upscaling then double conv\"\"\"\n",
    "\n",
    "    def __init__(self, in_channels, out_channels, bilinear=True):\n",
    "        super().__init__()\n",
    "\n",
    "        # if bilinear, use the normal convolutions to reduce the number of channels\n",
    "        if bilinear:\n",
    "            self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n",
    "            self.conv = DoubleConv(in_channels, out_channels, in_channels // 2)\n",
    "        else:\n",
    "            self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)\n",
    "            self.conv = DoubleConv(in_channels, out_channels)\n",
    "\n",
    "    def forward(self, x1, x2):\n",
    "        x1 = self.up(x1)\n",
    "        # input is CHW\n",
    "        diffY = x2.size()[2] - x1.size()[2]\n",
    "        diffX = x2.size()[3] - x1.size()[3]\n",
    "\n",
    "        x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,\n",
    "                        diffY // 2, diffY - diffY // 2])\n",
    "        # if you have padding issues, see\n",
    "        # https://github.com/HaiyongJiang/U-Net-Pytorch-Unstructured-Buggy/commit/0e854509c2cea854e247a9c615f175f76fbb2e3a\n",
    "        # https://github.com/xiaopeng-liao/Pytorch-UNet/commit/8ebac70e633bac59fc22bb5195e513d5832fb3bd\n",
    "        x = torch.cat([x2, x1], dim=1)\n",
    "        return self.conv(x)\n",
    "\n",
    "\n",
    "class OutConv(nn.Module):\n",
    "    def __init__(self, in_channels, out_channels):\n",
    "        super(OutConv, self).__init__()\n",
    "        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)\n",
    "\n",
    "    def forward(self, x):\n",
    "        return self.conv(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0fcec5b9",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\" Full assembly of the parts to form the complete network \"\"\"\n",
    "\n",
    "from .unet_parts import *\n",
    "\n",
    "\n",
    "class UNet(nn.Module):\n",
    "    def __init__(self, n_channels, n_classes, bilinear=True):\n",
    "        super(UNet, self).__init__()\n",
    "        self.n_channels = n_channels\n",
    "        self.n_classes = n_classes\n",
    "        self.bilinear = bilinear\n",
    "\n",
    "        self.inc = DoubleConv(n_channels, 64)\n",
    "        self.down1 = Down(64, 128)\n",
    "        self.down2 = Down(128, 256)\n",
    "        self.down3 = Down(256, 512)\n",
    "        factor = 2 if bilinear else 1\n",
    "        self.down4 = Down(512, 1024 // factor)\n",
    "        self.up1 = Up(1024, 512 // factor, bilinear)\n",
    "        self.up2 = Up(512, 256 // factor, bilinear)\n",
    "        self.up3 = Up(256, 128 // factor, bilinear)\n",
    "        self.up4 = Up(128, 64, bilinear)\n",
    "        self.outc = OutConv(64, n_classes)\n",
    "\n",
    "    def forward(self, x):\n",
    "        x1 = self.inc(x)\n",
    "        x2 = self.down1(x1)\n",
    "        x3 = self.down2(x2)\n",
    "        x4 = self.down3(x3)\n",
    "        x5 = self.down4(x4)\n",
    "        x = self.up1(x5, x4)\n",
    "        x = self.up2(x, x3)\n",
    "        x = self.up3(x, x2)\n",
    "        x = self.up4(x, x1)\n",
    "        logits = self.outc(x)\n",
    "        return logits\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}

e98735b7c48d59c644cfcc66423fa9ab06dd2b8c
<mask token>

{'cells': [{'cell_type': 'markdown', 'id': '061599cf', 'metadata': {},
    'source': ["""A contracting path: capture context.
""", '\n',
    'A symmetric expanding path: enables precise localization.']}, {
    'cell_type': 'code', 'execution_count': null, 'id': 'fb69fa32',
    'metadata': {}, 'outputs': [], 'source': [
    """""\" Parts of the U-Net model ""\"
""", '\n', 'import torch\n',
    'import torch.nn as nn\n', 'import torch.nn.functional as F\n', '\n',
    '\n', """class DoubleConv(nn.Module):
""",
    '    """(convolution => [BN] => ReLU) * 2"""\n', '\n',
    """    def __init__(self, in_channels, out_channels, mid_channels=None):
"""
    , '        super().__init__()\n', '        if not mid_channels:\n',
    """            mid_channels = out_channels
""",
    '        self.double_conv = nn.Sequential(\n',
    """            nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1),
"""
    , '            nn.BatchNorm2d(mid_channels),\n',
    '            nn.ReLU(inplace=True),\n',
    """            nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1),
"""
    , '            nn.BatchNorm2d(out_channels),\n',
    '            nn.ReLU(inplace=True)\n', '        )\n', '\n',
    """    def forward(self, x):
""",
    '        return self.double_conv(x)\n', '\n', '\n',
    'class Down(nn.Module):\n',
    """    ""\"Downscaling with maxpool then double conv""\"
""", '\n',
    '    def __init__(self, in_channels, out_channels):\n',
    '        super().__init__()\n',
    """        self.maxpool_conv = nn.Sequential(
""",
    '            nn.MaxPool2d(2),\n',
    '            DoubleConv(in_channels, out_channels)\n', '        )\n',
    '\n', """    def forward(self, x):
""",
    '        return self.maxpool_conv(x)\n', '\n', '\n',
    'class Up(nn.Module):\n', """    ""\"Upscaling then double conv""\"
""",
    '\n',
    '    def __init__(self, in_channels, out_channels, bilinear=True):\n',
    """        super().__init__()
""", '\n',
    '        # if bilinear, use the normal convolutions to reduce the number of channels\n'
    , """        if bilinear:
""",
    "            self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n"
    ,
    """            self.conv = DoubleConv(in_channels, out_channels, in_channels // 2)
"""
    , '        else:\n',
    """            self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)
"""
    , '            self.conv = DoubleConv(in_channels, out_channels)\n',
    '\n', """    def forward(self, x1, x2):
""",
    '        x1 = self.up(x1)\n', '        # input is CHW\n',
    """        diffY = x2.size()[2] - x1.size()[2]
""",
    '        diffX = x2.size()[3] - x1.size()[3]\n', '\n',
    """        x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
""",
    '                        diffY // 2, diffY - diffY // 2])\n',
    """        # if you have padding issues, see
""",
    """        # https://github.com/HaiyongJiang/U-Net-Pytorch-Unstructured-Buggy/commit/0e854509c2cea854e247a9c615f175f76fbb2e3a
"""
    ,
    """        # https://github.com/xiaopeng-liao/Pytorch-UNet/commit/8ebac70e633bac59fc22bb5195e513d5832fb3bd
"""
    , '        x = torch.cat([x2, x1], dim=1)\n',
    '        return self.conv(x)\n', '\n', '\n',
    """class OutConv(nn.Module):
""",
    '    def __init__(self, in_channels, out_channels):\n',
    """        super(OutConv, self).__init__()
""",
    '        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)\n'
    , '\n', """    def forward(self, x):
""", '        return self.conv(x)'
    ]}, {'cell_type': 'code', 'execution_count': null, 'id': '0fcec5b9',
    'metadata': {}, 'outputs': [], 'source': [
    """""\" Full assembly of the parts to form the complete network ""\"
""",
    '\n', 'from .unet_parts import *\n', '\n', '\n',
    'class UNet(nn.Module):\n',
    """    def __init__(self, n_channels, n_classes, bilinear=True):
""",
    '        super(UNet, self).__init__()\n',
    '        self.n_channels = n_channels\n',
    """        self.n_classes = n_classes
""",
    '        self.bilinear = bilinear\n', '\n',
    '        self.inc = DoubleConv(n_channels, 64)\n',
    """        self.down1 = Down(64, 128)
""",
    '        self.down2 = Down(128, 256)\n',
    '        self.down3 = Down(256, 512)\n',
    """        factor = 2 if bilinear else 1
""",
    '        self.down4 = Down(512, 1024 // factor)\n',
    """        self.up1 = Up(1024, 512 // factor, bilinear)
""",
    '        self.up2 = Up(512, 256 // factor, bilinear)\n',
    """        self.up3 = Up(256, 128 // factor, bilinear)
""",
    '        self.up4 = Up(128, 64, bilinear)\n',
    '        self.outc = OutConv(64, n_classes)\n', '\n',
    """    def forward(self, x):
""", '        x1 = self.inc(x)\n',
    '        x2 = self.down1(x1)\n', '        x3 = self.down2(x2)\n',
    """        x4 = self.down3(x3)
""", '        x5 = self.down4(x4)\n',
    '        x = self.up1(x5, x4)\n', """        x = self.up2(x, x3)
""",
    '        x = self.up3(x, x2)\n', '        x = self.up4(x, x1)\n',
    """        logits = self.outc(x)
""", '        return logits\n']}],
    'metadata': {'kernelspec': {'display_name': 'Python 3', 'language':
    'python', 'name': 'python3'}, 'language_info': {'codemirror_mode': {
    'name': 'ipython', 'version': 3}, 'file_extension': '.py', 'mimetype':
    'text/x-python', 'name': 'python', 'nbconvert_exporter': 'python',
    'pygments_lexer': 'ipython3', 'version': '3.6.9'}}, 'nbformat': 4,
    'nbformat_minor': 5}

{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "061599cf",
   "metadata": {},
   "source": [
    "A contracting path: capture context.\n",
    "\n",
    "A symmetric expanding path: enables precise localization."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb69fa32",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\" Parts of the U-Net model \"\"\"\n",
    "\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "\n",
    "\n",
    "class DoubleConv(nn.Module):\n",
    "    \"\"\"(convolution => [BN] => ReLU) * 2\"\"\"\n",
    "\n",
    "    def __init__(self, in_channels, out_channels, mid_channels=None):\n",
    "        super().__init__()\n",
    "        if not mid_channels:\n",
    "            mid_channels = out_channels\n",
    "        self.double_conv = nn.Sequential(\n",
    "            nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1),\n",
    "            nn.BatchNorm2d(mid_channels),\n",
    "            nn.ReLU(inplace=True),\n",
    "            nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1),\n",
    "            nn.BatchNorm2d(out_channels),\n",
    "            nn.ReLU(inplace=True)\n",
    "        )\n",
    "\n",
    "    def forward(self, x):\n",
    "        return self.double_conv(x)\n",
    "\n",
    "\n",
    "class Down(nn.Module):\n",
    "    \"\"\"Downscaling with maxpool then double conv\"\"\"\n",
    "\n",
    "    def __init__(self, in_channels, out_channels):\n",
    "        super().__init__()\n",
    "        self.maxpool_conv = nn.Sequential(\n",
    "            nn.MaxPool2d(2),\n",
    "            DoubleConv(in_channels, out_channels)\n",
    "        )\n",
    "\n",
    "    def forward(self, x):\n",
    "        return self.maxpool_conv(x)\n",
    "\n",
    "\n",
    "class Up(nn.Module):\n",
    "    \"\"\"Upscaling then double conv\"\"\"\n",
    "\n",
    "    def __init__(self, in_channels, out_channels, bilinear=True):\n",
    "        super().__init__()\n",
    "\n",
    "        # if bilinear, use the normal convolutions to reduce the number of channels\n",
    "        if bilinear:\n",
    "            self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n",
    "            self.conv = DoubleConv(in_channels, out_channels, in_channels // 2)\n",
    "        else:\n",
    "            self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)\n",
    "            self.conv = DoubleConv(in_channels, out_channels)\n",
    "\n",
    "    def forward(self, x1, x2):\n",
    "        x1 = self.up(x1)\n",
    "        # input is CHW\n",
    "        diffY = x2.size()[2] - x1.size()[2]\n",
    "        diffX = x2.size()[3] - x1.size()[3]\n",
    "\n",
    "        x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,\n",
    "                        diffY // 2, diffY - diffY // 2])\n",
    "        # if you have padding issues, see\n",
    "        # https://github.com/HaiyongJiang/U-Net-Pytorch-Unstructured-Buggy/commit/0e854509c2cea854e247a9c615f175f76fbb2e3a\n",
    "        # https://github.com/xiaopeng-liao/Pytorch-UNet/commit/8ebac70e633bac59fc22bb5195e513d5832fb3bd\n",
    "        x = torch.cat([x2, x1], dim=1)\n",
    "        return self.conv(x)\n",
    "\n",
    "\n",
    "class OutConv(nn.Module):\n",
    "    def __init__(self, in_channels, out_channels):\n",
    "        super(OutConv, self).__init__()\n",
    "        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)\n",
    "\n",
    "    def forward(self, x):\n",
    "        return self.conv(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0fcec5b9",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\" Full assembly of the parts to form the complete network \"\"\"\n",
    "\n",
    "from .unet_parts import *\n",
    "\n",
    "\n",
    "class UNet(nn.Module):\n",
    "    def __init__(self, n_channels, n_classes, bilinear=True):\n",
    "        super(UNet, self).__init__()\n",
    "        self.n_channels = n_channels\n",
    "        self.n_classes = n_classes\n",
    "        self.bilinear = bilinear\n",
    "\n",
    "        self.inc = DoubleConv(n_channels, 64)\n",
    "        self.down1 = Down(64, 128)\n",
    "        self.down2 = Down(128, 256)\n",
    "        self.down3 = Down(256, 512)\n",
    "        factor = 2 if bilinear else 1\n",
    "        self.down4 = Down(512, 1024 // factor)\n",
    "        self.up1 = Up(1024, 512 // factor, bilinear)\n",
    "        self.up2 = Up(512, 256 // factor, bilinear)\n",
    "        self.up3 = Up(256, 128 // factor, bilinear)\n",
    "        self.up4 = Up(128, 64, bilinear)\n",
    "        self.outc = OutConv(64, n_classes)\n",
    "\n",
    "    def forward(self, x):\n",
    "        x1 = self.inc(x)\n",
    "        x2 = self.down1(x1)\n",
    "        x3 = self.down2(x2)\n",
    "        x4 = self.down3(x3)\n",
    "        x5 = self.down4(x4)\n",
    "        x = self.up1(x5, x4)\n",
    "        x = self.up2(x, x3)\n",
    "        x = self.up3(x, x2)\n",
    "        x = self.up4(x, x1)\n",
    "        logits = self.outc(x)\n",
    "        return logits\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
