04 - FCNs-for-segmentation.ipynb 57.2 KB
Newer Older
Ben Glocker's avatar
Ben Glocker committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tutorial 4: Fully Convolutional Nets for Image Segmentation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Running on Colab"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! wget https://www.doc.ic.ac.uk/~bglocker/teaching/notebooks/supervised-data.zip\n",
    "! unzip supervised-data.zip\n",
    "\n",
    "! wget https://www.doc.ic.ac.uk/~bglocker/teaching/notebooks/brain2d-data.zip\n",
    "! unzip brain2d-data.zip\n",
    "\n",
    "# data directories\n",
    "data_dir = 'data/mnist/'\n",
    "data_brain_dir = 'data/brain2d/'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Running on DoC lab machines"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# data directories\n",
    "data_dir = '/vol/lab/course/416/data/mnist/'\n",
    "data_brain_dir = '/vol/lab/course/416/data/brain2d/'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Aims of this tutorial**:\n",
    "- Introduce Fully Convolutional Networks.\n",
    "- Showcase that fully connected/dense layers can be equally turned to convolutional.\n",
    "- Show how Fully Convolutional Networks can be used for segmentation.\n",
    "\n",
    "The tutorial contains material that you will need for the **Coursework**.\n",
    "Along the way you will implement a CNN using the nn.module of Pytorch for extra simplicity.  \n",
    "You will also get to see how ML can help segmenting brain tumours!  \n",
    "\n",
    "**Prerequisites**:\n",
    "- Familiar with python and numpy and Pytorch\n",
    "- Familiar with logistic regression and MNIST\n",
    "- Familiar with SGD, Cross entropy\n",
    "\n",
    "\n",
    "**Notes**:\n",
    "- Docs for Pytorch's nn.Module you will use:  \n",
    "https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html\n",
    "- Some helper functions are included below for loading and plotting data. They will be used out of the box below."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Preliminaries: Loading and pre-processing MNIST (from Tutorial 3)\n",
    "We will use MNIST as in previous tutorial. Below, we prepare the data for a CNN, *exactly* as in Tutorial 3.  \n",
    "Make sure to refresh your memory about **shape of the data** involved.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import torchvision.datasets as dset\n",
    "\n",
    "\n",
    "def get_mnist(data_dir, train):\n",
    "    # data_dir: path to local directory where data is, or should be stored.\n",
    "    # train: if True, return training data. If False, return test data.\n",
    "    # download: if data not in data_dir, download it.\n",
    "    data_set = dset.MNIST(root=data_dir, train=train, transform=None, download=True)\n",
    "    # Students should only deal with numpy arrays, so that it's easy to follow.\n",
    "    if train:\n",
    "        data_x = np.asarray(data_set.train_data, dtype='uint8')\n",
    "        data_y = np.asarray(data_set.train_labels, dtype='int16') # int64 by default\n",
    "    else:\n",
    "        data_x = np.asarray(data_set.test_data, dtype='uint8')\n",
    "        data_y = np.asarray(data_set.test_labels, dtype='int16') # int64 by default\n",
    "    return data_x, data_y\n",
    "\n",
    "\n",
    "def make_lbls_onehot(lbls, num_classes):\n",
    "    # lbls: np.array of shape [N]\n",
    "    lbls_onehot = np.zeros(shape=(lbls.shape[0], num_classes ) )\n",
    "    lbls_onehot[ np.arange(lbls_onehot.shape[0]), lbls ] = 1\n",
    "    return lbls_onehot\n",
    "\n",
    "\n",
    "# If datasets are not at specified location, they will be downloaded.\n",
    "train_imgs, train_lbls = get_mnist(data_dir=data_dir, train=True)\n",
    "test_imgs, test_lbls = get_mnist(data_dir=data_dir, train=False)\n",
    "\n",
    "print(\"[train_imgs] Type: \", type(train_imgs), \"|| Shape:\", train_imgs.shape, \"|| Data type: \", train_imgs.dtype )\n",
    "print(\"[train_lbls] Type: \", type(train_lbls), \"|| Shape:\", train_lbls.shape, \"|| Data type: \", train_lbls.dtype )\n",
    "print('Class labels in train = ', np.unique(train_lbls))\n",
    "\n",
    "print(\"[test_imgs] Type: \", type(test_imgs), \"|| Shape:\", test_imgs.shape, \" || Data type: \", test_imgs.dtype )\n",
    "print(\"[test_lbls] Type: \", type(test_lbls), \"|| Shape:\", test_lbls.shape, \" || Data type: \", test_lbls.dtype )\n",
    "print('Class labels in test = ', np.unique(test_lbls))\n",
    "\n",
    "S_tr_samples = train_imgs.shape[0] # S hereafter. Number of training samples in database.\n",
    "H_height = train_imgs.shape[1] # H hereafter\n",
    "W_width = train_imgs.shape[2] # W hereafter\n",
    "C_classes = len(np.unique(train_lbls)) # C hereafter"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Change representation of labels to one-hot vectors of length C=10. (Lec.5, sl.16)\n",
    "train_lbls_onehot = np.zeros(shape=(train_lbls.shape[0], C_classes ) )\n",
    "train_lbls_onehot[ np.arange(train_lbls_onehot.shape[0]), train_lbls ] = 1\n",
    "test_lbls_onehot = np.zeros(shape=(test_lbls.shape[0], C_classes ) )\n",
    "test_lbls_onehot[ np.arange(test_lbls_onehot.shape[0]), test_lbls ] = 1\n",
    "print(\"BEFORE: [train_lbls]        Type: \", type(train_lbls), \"|| Shape:\", train_lbls.shape, \" || Data type: \", train_lbls.dtype )\n",
    "print(\"AFTER : [train_lbls_onehot] Type: \", type(train_lbls_onehot), \"|| Shape:\", train_lbls_onehot.shape, \" || Data type: \", train_lbls_onehot.dtype )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# (Same as in Tut. 3)  \n",
    "# Normalize intensities (from 0-255) to have 0-mean and 1-stdev. (Lec.5, sl.68)  \n",
    "def normalize_int_whole_database(data):\n",
    "    # data: shape [num_samples, H, W, C]\n",
    "    mu = np.mean(data, axis=(0,1,2), keepdims=True) # Mean int of channel C, over samples and pixels.\n",
    "    std = np.std(data, axis=(0,1,2), keepdims=True) # Returned shape: [1, 1, 1, C]\n",
    "    norm_data = (data - mu) / std\n",
    "    return norm_data\n",
    "\n",
    "train_imgs = normalize_int_whole_database(train_imgs)\n",
    "test_imgs = normalize_int_whole_database(test_imgs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Cross entropy for Classifier (from Tutorial 3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For better understanding, we use our own implementation. Of course, PyTorch has the cross entropy loss already implemented: https://pytorch.org/docs/stable/nn.html#crossentropyloss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def cross_entropy(y_pred, y_real, eps=1e-7):\n",
    "    # y_pred: Tensor of shape [N, D_out]. Predicted class-posterior probabilities from forward.\n",
    "    # y_real: Same shape as y_pred. One-hot representation of real labels.\n",
    "    x_entr_per_sample = - torch.sum( y_real*torch.log(y_pred+eps), dim=1) # Sum over classes, axis=1\n",
    "    loss = torch.mean(x_entr_per_sample, dim=0) # Expectation of loss: Mean over samples (axis=0).\n",
    "    return loss"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Stochastic Gradient Descent (from Tutorial 3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "PyTorch has also very useful functionality for handling datasets and sampling of training data. However, to fully understand what's going, again, we make use of our own implementation here. More details about how PyTorch can help with handling data can be found here: https://pytorch.org/docs/stable/data.html"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Helpers\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "\n",
    "def plot_train_progress(loss_l, acc_train_l, acc_test_l, iters_per_point, total_iters=None):\n",
    "\n",
    "    fig, axes = plt.subplots(1, 2, sharex=False, sharey=False)\n",
    "    assert len(loss_l) == len(acc_train_l) == len(acc_test_l)\n",
    "    x_points = range(0, len(loss_l)*iters_per_point, iters_per_point)\n",
    "    \n",
    "    axes[0].plot(x_points, loss_l, color=\"black\", label=\"Training loss\", linewidth=5)\n",
    "    axes[0].set_title(\"Training loss\", fontsize=10, y=1.022)\n",
    "    axes[0].yaxis.grid(True, zorder=0)\n",
    "    axes[0].set_xlabel('Iteration', fontsize=10)\n",
    "    if total_iters is not None:\n",
    "        axes[0].set_xlim([0,total_iters])\n",
    "    axes[0].set_ylim([0,None])\n",
    "    axes[0].legend(loc='upper right')\n",
    "    \n",
    "    axes[1].set_title(\"Accuracy\", fontsize=10, y=1.022)\n",
    "    axes[1].plot(x_points, acc_train_l, color=\"blue\", label=\"Train\", linewidth=5)\n",
    "    axes[1].plot(x_points, acc_test_l, color=\"red\", label=\"Test\", linewidth=5)\n",
    "    axes[1].yaxis.grid(True, zorder=0)\n",
    "    axes[1].set_xlabel('Iteration', fontsize=10)\n",
    "    if total_iters is not None:\n",
    "        axes[1].set_xlim([0,total_iters])\n",
    "    axes[1].set_ylim([0,100])\n",
    "    axes[1].legend(loc='lower right')\n",
    "    \n",
    "    plt.show()\n",
    "    \n",
    "\n",
    "def plot_image(image, interpol=\"nearest\", cmap=\"gray\", vminmax=[None,None], figsize=None):\n",
    "    # image: np.array of one of the following shapes:\n",
    "    #       grayscale image:    (height, width)\n",
    "    #       grayscale image:    (height, width, 1)\n",
    "    #       rgb image:          (height, width, 3)\n",
    "    print(\"Plotting image of shape: \", image.shape)\n",
    "    plt.figure(figsize=figsize) # (figsize=(n_imgs_per_row*0.5, n_rows*0.5)) # size (width, height), in inches.\n",
    "    if len(image.shape) == 2:\n",
    "        fig = plt.imshow(image, cmap=cmap, interpolation=interpol, vmin=vminmax[0], vmax=vminmax[1]) # imshow: (w,h) or (w,h,3)\n",
    "        plt.colorbar(fig)\n",
    "    elif len(image.shape) == 3 and image.shape[2] == 1:\n",
    "        fig = plt.imshow(image[:,:,0], cmap=cmap, interpolation=interpol, vmin=v_minmax[0], vmax=vminmax[1]) # imshow: (w,h) or (w,h,3)\n",
    "        plt.colorbar(fig)\n",
    "    elif len(image.shape) == 3 and image.shape[2] == 3 :\n",
    "        _ = plt.imshow(image, interpolation=interpol)\n",
    "    else:\n",
    "        raise Error(\"Wrong shape of given image for plotting.\")\n",
    "\n",
    "\n",
    "def display_image_dynamically(image, interpol=\"nearest\", cmap=\"gray\", vminmax=[None,None], figsize=None):\n",
    "    # image: np.array of one of the following shapes:\n",
    "    #       grayscale image:    (height, width)\n",
    "    #       grayscale image:    (height, width, 1)\n",
    "    \n",
    "    print(\"Plotting image of shape: \", image.shape)\n",
    "    plt.figure(figsize=figsize) # (figsize=(n_imgs_per_row*0.5, n_rows*0.5)) # size (width, height), in inches.\n",
    "    if len(image.shape) == 2:\n",
    "        fig = plt.imshow(image, cmap=cmap, interpolation=interpol, vmin=vminmax[0], vmax=vminmax[1]) # imshow: (w,h) or (w,h,3)\n",
    "        plt.colorbar(fig)\n",
    "    elif len(image.shape) == 3 and image.shape[2] == 1:\n",
    "        fig = plt.imshow(image[:,:,0], cmap=cmap, interpolation=interpol, vmin=v_minmax[0], vmax=vminmax[1]) # imshow: (w,h) or (w,h,3)\n",
    "        plt.colorbar(fig)\n",
    "    elif len(image.shape) == 3 and image.shape[2] == 3 :\n",
    "        _ = plt.imshow(image, interpolation=interpol)\n",
    "    else:\n",
    "        raise Error(\"Wrong shape of given image for plotting.\")\n",
    "        \n",
    "    #display.clear_output(wait=True)\n",
    "    display.display(plt.gcf())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_accuracy(lbls_pred, lbls_real):\n",
    "    # lbls_pred, lbls_read: np.arrays of labels (after argmax), not probabilities/onehot.\n",
    "    acc = np.mean(lbls_pred == lbls_real) * 100.\n",
    "    return acc\n",
    "\n",
    "def get_random_batch(train_imgs, train_lbls, N_batch_size, rng):\n",
    "    # train_imgs: Images for training. Numpy array of shape [S, H, W]\n",
    "    # train_lbls: Labels of the training images.\n",
    "    # N_batch_size: integer. Size that the batch should have.\n",
    "    indices = rng.randint(low=0, high=train_imgs.shape[0], size=N_batch_size, dtype='int32')\n",
    "    train_imgs_batch = train_imgs[indices]\n",
    "    train_lbls_batch = train_lbls[indices]\n",
    "    return [train_imgs_batch, train_lbls_batch]\n",
    "\n",
    "def gradient_descent(net, loss_func, grad_descent_optimizer, rng,\n",
    "                     train_imgs, train_lbls, test_imgs, test_lbls,\n",
    "                     N_batch_size, total_iters, iters_per_test=-1,\n",
    "                     is_tumor_segm=False ):\n",
    "    # net: Instance of a model.\n",
    "    # loss_func: Function that computes the loss. See functions: cross_entropy.\n",
    "    # grad_descent_optimizer: From torch.optim (see Task 2)\n",
    "    # rng: numpy random number generator\n",
    "    # train_imgs: The training images. Numpy array, shape [S_tr, H, W]\n",
    "    # test_imgs: Save as above, for testing images. [S_te, H, W]\n",
    "    # train_lbls: One hot representation of labels corresponding to train_imgs. Numpy array, shape [S_tr, C]\n",
    "    # test_lbls: As above, but for testing data. [S_te, C]\n",
    "    # N_batch_size: Size N of the batch that should be processed per SGD iteration by a model.\n",
    "    # learning_rate: self explanatory.\n",
    "    # total_iters: how many iterations in total to perform.\n",
    "    # iters_per_test: Integer. Every that many iterations the model predicts the test data and accuracy is reported.\n",
    "    values_to_plot = {'loss':[], 'acc_train': [], 'acc_test': []}\n",
    "    \n",
    "    for t in range(total_iters):\n",
    "        \n",
    "        x, y_real = get_random_batch(train_imgs, train_lbls, N_batch_size, rng)\n",
    "        \n",
    "        y_pred = net.forward( torch.tensor(x, dtype=torch.float) )\n",
    "        \n",
    "        loss = loss_func(y_pred, torch.tensor(y_real, dtype=torch.float)) # Cross Entropy\n",
    "\n",
    "        loss.backward() # Computes grads with auto-differentiation. Stores them in each params.grads\n",
    "        \n",
    "        # Update weights with gradient descent. One of optimizers given by torch.optim\n",
    "        grad_descent_optimizer.step()\n",
    "        grad_descent_optimizer.zero_grad()  # zero the parameter gradients.\n",
    "        \n",
    "        # ==== Report training loss and accuracy ======\n",
    "        lbls_pred = np.argmax(y_pred.detach().numpy(), axis=1) # Get labels from the probabilities.\n",
    "        lbls_real = np.argmax(y_real, axis=1) # Get labels from one-hot\n",
    "        acc_train = compute_accuracy(lbls_pred, lbls_real)\n",
    "        print(\"[iter:\", t, \"]: Training Loss: {0:.2f}\".format(loss.item()), \"\\t Accuracy: {0:.2f}\".format(acc_train))\n",
    "        \n",
    "        # =============== Every few iterations, predict the testing-database ================#\n",
    "        if t==total_iters-1 or t%iters_per_test == 0:\n",
    "            y_pred_test = net.forward(torch.tensor(test_imgs, dtype=torch.float))\n",
    "            y_pred_test_numpy = y_pred_test.detach().numpy()\n",
    "            # ==== Report test accuracy ======\n",
    "            lbls_pred_test = np.argmax(y_pred_test_numpy, axis=1)\n",
    "            lbls_real_test = np.argmax(test_lbls, axis=1)\n",
    "            acc_test = compute_accuracy(lbls_pred_test, lbls_real_test)\n",
    "            print(\"\\t\\t\\t\\t\\t\\t\\t\\t Testing Accuracy: {0:.2f}\".format(acc_test))\n",
    "            \n",
    "            # Keep list of metrics to plot progress.\n",
    "            values_to_plot['loss'].append(loss.item())\n",
    "            values_to_plot['acc_train'].append(acc_train)\n",
    "            values_to_plot['acc_test'].append(acc_test)\n",
    "            \n",
    "            if is_tumor_segm:\n",
    "                display_image_dynamically(y_pred_test_numpy[0,1,:,:])\n",
    "                #scipy.misc.imsave('./pred_prob.png', y_pred_test_numpy[0,1,:,:])\n",
    "                #scipy.misc.imsave('./pred_segm.png', lbls_pred_test[0,:,:])\n",
    "                \n",
    "                \n",
    "    # In the end of the process, plot loss accuracy on training and testing data.\n",
    "    plot_train_progress(values_to_plot['loss'], values_to_plot['acc_train'], values_to_plot['acc_test'], iters_per_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Task 1: Build LeNet\n",
    "\n",
    "In tutorial 3 we had built a tiny CNN, with just 1 convolution and 1 fully connected layer.  \n",
    "Here, we will build the legendary LeNet.  \n",
    "\n",
    "**Replicate** the code given to you in the lecture **CNNs for Image Segmentation** to build the architecture below:\n",
    "\n",
    "We will build this by using the **nn** and **nn.Module** of PyTorch.\n",
    "\n",
    "- **nn**: Helps developing nets easier by providing building blocks such as *layers*. For example, a **nn.Conv2d** layer internally initializes a weight kernel for its convolution operator, encapsulates a bias term, can apply padding to its input, etc. If we would do this using the basic operators given by *torch.nn.functional* (what we did in the last turorial), we have more transparency, but we got to do everything ourselves. Choose wisely.  \n",
    "- **nn.Module**: A further abstraction module. This module should be used as a **parent class** for classes that represent whole networks. Then, Pytorch automatically keeps track of the net's parameters within **self.parameters**. All you need is to define the **forward** pass. This makes things clean as you will see...  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "\n",
    "# Docs of nn.Conv2d and nn.Linear and max_pool2d:\n",
    "# https://pytorch.org/docs/stable/_modules/torch/nn/modules/conv.html#Conv2d\n",
    "# https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html#Linear\n",
    "# https://pytorch.org/docs/stable/nn.html#torch.nn.functional.max_pool2d\n",
    "\n",
    "class LeNet(nn.Module):\n",
    "    def __init__(self, num_classes):\n",
    "        super(LeNet, self).__init__()\n",
    "        ######################### TODO: Build LeNet ########################\n",
    "        # Make the above architecture of LeNet.\n",
    "        # bias=True makes the layer create a bias internally. Nice and clean.\n",
    "        # Conv2d gets args: (num input channs, num out channs, kernel_size ...)\n",
    "        # Linear gets args: (num input neurons, num out neurons, ...)\n",
    "        self.conv1 = nn.Conv2d(1, ???, kernel_size=???, bias=True, padding=0) # Params are initialized internally.\n",
    "        self.conv2 = nn.Conv2d(???, ???, kernel_size=???, bias=True, padding=0)\n",
    "        self.fc1 = nn.Linear(??? * ??? * ???, ???, bias=True) # nn.Linear is a fully connected layer.\n",
    "        self.fc2 = nn.Linear(???, ???, bias=True)\n",
    "        self.fc3 = nn.Linear(???, num_classes, bias=True)\n",
    "        # All parameters of a nn.Module are afterwards accessible by self.parameters()\n",
    "        # Each layer's weights and biases are accessible by eg by self.conv1.weight & self.conv1.bias\n",
    "    \n",
    "    def forward(self, x):\n",
    "        # x: Input tensor (batch of images) of shape [N, Channels, H, W]\n",
    "        # returns: tensor of shape [N, classes]. The class posterior probabilities.\n",
    "        # Make the forward pass.\n",
    "        x = F.max_pool2d(F.relu(self.conv1(x)), kernel_size=2, stride=2, padding=0, ceil_mode=False)\n",
    "        x = F.???(F.relu(self.???(x)), kernel_size=2, stride=2, padding=0, ceil_mode=False)\n",
    "        x = x.reshape(x.shape[0], -1)\n",
    "        x = F.relu(self.???(x))\n",
    "        x = F.???(self.???(x))\n",
    "        x = self.???(x)\n",
    "        y_pred = F.softmax(x, dim=1) # y_pred.shape = [N, 10]\n",
    "        ####################################################################\n",
    "        return y_pred\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Task 2: Train LeNet classifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# (From Tutorial 3)\n",
    "# Pytorch needs input to conv/pool to be of shape [N, Channels, H, W].\n",
    "# For grayscale images, there is only 1 image channel. We add this *channels dimension*:\n",
    "train_imgs_cnn = train_imgs.reshape([train_imgs.shape[0], 1, train_imgs.shape[1], train_imgs.shape[2]])\n",
    "test_imgs_cnn = test_imgs.reshape([test_imgs.shape[0], 1, test_imgs.shape[1], test_imgs.shape[2]])\n",
    "\n",
    "################ TODO: Pad images to fit to LeNet correctly ###################\n",
    "# MNIST is 28x28 images. LeNet **by construction** requires images of shape 32x32 !\n",
    "# with 2 voxels before and after H & W dimensions, to make them 32x32!\n",
    "train_imgs_cnn = np.pad(train_imgs_cnn, ((0,0), (0,0), (2,???), (???,2)), mode='edge')\n",
    "test_imgs_cnn = np.pad(test_imgs_cnn, ((0,0), (0,0), (???,???), (???,???)), mode='edge')\n",
    "print(\"train_imgs_cnn.shape should be (60000, 1, 32, 32). It is: \", train_imgs_cnn.shape)\n",
    "###############################################################################\n",
    "\n",
    "# Create the network.\n",
    "lenet = LeNet(num_classes=C_classes)\n",
    "\n",
    "############## NOTE: Pytorch's optimizers (nothing to do here) #################\n",
    "# Last time we wrote our own function for optimizing weights: w'=w-lr*grads.\n",
    "# There are more complex ones (RMSProp, Adam, etc)\n",
    "# Pytorch provides out-of-the-box optimizers that do this, so we dont need to write them.\n",
    "# Create one, then call optimizer.step() & optimizer.zero_grad(). See SGD function above.\n",
    "import torch.optim as optim\n",
    "grad_descent_optimizer = optim.SGD(lenet.parameters(), lr=0.03, momentum=0.0)\n",
    "################################################################################\n",
    "\n",
    "# Start training\n",
    "SEED = 42\n",
    "rng = np.random.RandomState(seed=SEED) # Random number generator\n",
    "gradient_descent(lenet,\n",
    "                 cross_entropy,\n",
    "                 grad_descent_optimizer,\n",
    "                 rng,\n",
    "                 train_imgs_cnn,\n",
    "                 train_lbls_onehot,\n",
    "                 test_imgs_cnn,\n",
    "                 test_lbls_onehot,\n",
    "                 N_batch_size=80,\n",
    "                 total_iters=400,\n",
    "                 iters_per_test=20,\n",
    "                 is_tumor_segm=False)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If done correctly, accuracy should surpass 90% both on training and testing samples.  \n",
    "You should see a pretty plot at the bottom of the output when process finishes."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Task 3: Build Fully Convolutional LeNet\n",
    "\n",
    "Fully convolutional networks are networks that do not have dense/fully-connected layers. Any network with dense layers has an **exactly equivalent** fully-convolutional architecture. A dense layer can be turned to a convolution with mathematically exact same behaviour. See lecture slides...\n",
    "\n",
    "Explanation (check together with the slides):\n",
    "- Assume **input X** to a dense layer is a matrix of shape **(num_in_channs, height, width)**, which is the output from a previous conv layer that has (num_inp_channs) **feature maps**, each of **dimensions** \\[height, width\\].  \n",
    "- A dense layer with (num-out) neurons has **weight matrix W** of shape: \\[num-out, num-in-channs * height * width\\].  \n",
    "- **Each of the output neurons** in a dense layer has (num_inp_channs * height_of_inp * width_of_inp) weights connecting it to the above input.  \n",
    "- Out of these, there are (height*width) weights connecting each output neuron to each input feature map. Each of these weights is different.\n",
    "- Thus the above (height*width) weights can be seen as a kernel of shape \\[height, width\\].\n",
    "- The weights connecting each output neuron to all input feature maps can be seen as a convolutional kernel of shape \\[1, num_in_channs, height, width\\].\n",
    "- The whole weight matrix W can be reorganized as a convolution kernel \\[out_channs, num_in_channs, height, width\\]\n",
    "- The whole **dense layer with num-out-neurons** can be reorganized as a **convolutional layer with num-out feature-maps**, where **ach output feature-map gives only 1 activation** (is of height=1 and width=1). \n",
    "- The operation applied by a dense layer, **dot_product(X,W)**, can be now cast as a **convolution(X,W_reorganized)**, with the two being **mathematically equivallent**.  \n",
    "\n",
    "(Note: Won't be needed here, but in some implementations of conv/cross-correlation, you would need to flip the kernel. Check difference between conv and cross-correlation.)\n",
    "\n",
    "Below, we are going to build a Fully Convolutional LeNet, that corresponds exactly to the previous LeNet..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class FCLeNet(nn.Module):\n",
    "    def __init__(self, num_classes):\n",
    "        super(FCLeNet, self).__init__()\n",
    "        ################ TODO: Build a Fully Convolutional LeNet ####################\n",
    "        # Adjust LeNet's code, and replace all nn.Linear layers with appropriate nn.Conv2d\n",
    "        # Conv2d gets args: (num input channs, num out channs, kernel_size ...)\n",
    "        self.conv1 = nn.Conv2d(1, ???, kernel_size=5, bias=True, padding=0)\n",
    "        self.conv2 = nn.Conv2d(???, ???, kernel_size=5, bias=True, padding=0)\n",
    "        self.conv3 = nn.Conv2d(???, 120, kernel_size=???, bias=True, padding=0)\n",
    "        self.conv4 = nn.Conv2d(???, 84, kernel_size=1, bias=True, padding=0)\n",
    "        self.conv5 = nn.Conv2d(???, num_classes, kernel_size=???, bias=True, padding=0)\n",
    "        \n",
    "    def forward(self, x):\n",
    "        # x: Input tensor (batch of images) of shape [N, Channels, H, W]\n",
    "        # returns: tensor of shape [N, classes] if input is of shape 32x32...\n",
    "        # ... or Tensor of shape [N, classes, H_out, W_out if input >= 36x36.\n",
    "        # Make the forward pass.\n",
    "        x = F.???(F.relu(self.conv1(x)), kernel_size=2, stride=2, padding=0, ceil_mode=False)\n",
    "        x = F.???(F.relu(self.???(x)), kernel_size=2, stride=2, padding=0, ceil_mode=False)\n",
    "        x = F.relu(self.???(x))\n",
    "        x = F.???(self.???(x))\n",
    "        x = self.???(x)\n",
    "        \n",
    "        y_pred = F.softmax(x, dim=1) # y_pred.shape = [N, 10, 1, 1]\n",
    "        #############################################################################\n",
    "        \n",
    "        # The output of LeNet was [N, 10] for input x of size 32x32.\n",
    "        # y_pred here will be [N,10,1,1] if input x of size 32x32, ...\n",
    "        # ... Or of shape [N, 10, H_out, W_out] if input larger than 32x32 is given.\n",
    "        # If shape is [N,10,1,1], drop unary dimensions to have same behaviour as LeNet.\n",
    "        if y_pred.shape[2] == 1 and y_pred.shape[3] == 1:\n",
    "            y_pred = y_pred.reshape([y_pred.shape[0], y_pred.shape[1]])\n",
    "            \n",
    "        return y_pred"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We above hopefully created a Fully Convolutional LeNet that we claimed can be mathematically equivalent to a LeNet with dense layers. Is it? Lets check...\n",
    "\n",
    "Below, we will **transfer parameters** of the **pre-trained** LeNet (from Task 2) to FCLeNet, after we **reorganize them in convolutional kernels** of appropriate shape.\n",
    "\n",
    "Then, we will apply both LeNet and FCLeNet, to check if we get the same result..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def transfer_weights_from_LeNet_to_FCLeNet(lenet, fclenet):\n",
    "    # Docs on conv and linear layers, to see their .weight and .bias attributes:\n",
    "    # https://pytorch.org/docs/stable/_modules/torch/nn/modules/conv.html#Conv2d\n",
    "    # https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html#Linear\n",
    "\n",
    "    \n",
    "    ############# TODO: Complete the below #######################################\n",
    "    # Match which layer of lenet should be transfered to which of FCLeNet.\n",
    "    # Reshape the weights of dense layers of LeNet to the shape needed by the convs.\n",
    "    \n",
    "    # Shape of weights : conv [out channels, in channels, kh, kw] linear: [out ch, in ch]\n",
    "    # Shape of biases: conv & linear have same shape: [out channels]\n",
    "    # NOTE: Shape of conv.weight is switched in comparison to how declared in nn.Conv2d(...) above.\n",
    "    # ... Here, [out_chans, in_chans, H, W]. Above at nn.Conv2d(in_chans, out_chans, H, W)\n",
    "    fclenet.conv1.weight.data = lenet.conv1.weight.data.clone()\n",
    "    fclenet.conv1.bias.data = lenet.conv1.bias.data.clone()\n",
    "    fclenet.conv2.weight.data = lenet.???.weight.data.clone()\n",
    "    fclenet.conv2.bias.data = lenet.???.bias.data.clone()\n",
    "    fclenet.conv3.weight.data = lenet.???.weight.data.clone().reshape([120,16,5,5])\n",
    "    fclenet.conv3.bias.data = lenet.???.bias.data.clone()\n",
    "    fclenet.conv4.weight.data = lenet.???.weight.data.clone().reshape([84,120,1,1])\n",
    "    fclenet.conv4.bias.data = lenet.???.bias.data.clone()\n",
    "    fclenet.conv5.weight.data = lenet.???.weight.data.clone().reshape([-1,84,1,1])\n",
    "    fclenet.conv5.bias.data = lenet.???.bias.data.clone()\n",
    "    ##################################################################################\n",
    "    \n",
    "# Initialize an FCLeNet, and then transfer the weights from pre-trained LeNet to FCLeNet.\n",
    "fclenet = FCLeNet(num_classes=C_classes)\n",
    "transfer_weights_from_LeNet_to_FCLeNet(lenet, fclenet)\n",
    "\n",
    "# Test with LeNet\n",
    "y_pred_lenet = lenet.forward(torch.tensor(test_imgs_cnn, dtype=torch.float))\n",
    "lbls_pred_lenet = np.argmax(y_pred_lenet.detach().numpy(), axis=1)\n",
    "acc_lenet = compute_accuracy(lbls_pred_lenet, test_lbls)\n",
    "# Test with FCLeNet\n",
    "y_pred_fclenet = fclenet.forward(torch.tensor(test_imgs_cnn, dtype=torch.float))\n",
    "lbls_pred_fclenet = np.argmax(y_pred_fclenet.detach().numpy(), axis=1)\n",
    "acc_fclenet = compute_accuracy(lbls_pred_fclenet, test_lbls)\n",
    "\n",
    "print(\"Accuracy of LeNet {0:.2f}\".format(acc_lenet), \" and FCLeNet {0:.2f}\".format(acc_fclenet))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If done correctly, you should get **exactly** the same result from LeNet and FCLeNet.  \n",
    "It should also be the same as the final test-accuracy when training LeNet above."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Task 4: Beyond classification with Fully Conv. Nets\n",
    "\n",
    "If we convert a fully connected layer to a conv layer appropriately, we get the same output. What's useful about it then?\n",
    "\n",
    "*As all operations are convolutional, the network can receive input larger than its receptive field.*  \n",
    "\n",
    "LeNet had to receive 32x32 size of input by construction, and would return 1 output.\n",
    "We say that it has a **receptive field** of size 32x32 by construction. *Size of receptive field* is how many pixels the net processes for its output neurons to give one output activation (prediction). The size of the receptive field is defined by the size of the kernels, their strides, and the numbers of layers.\n",
    "\n",
    "FCLeNet has exactly the same size of receptive field with LeNet, since as we saw the two architectures are equivalent. It processes 32x32 pixels via convs and pools, and gives one output. But...  \n",
    "\n",
    "... As whole FCLeNet is made of kernels convolving an output (pooling is the same), nothing stops it from receiving a larger input. If given an input larger than 32x32, kernels at each layer will be applied as normally, they will simply output more activations at the output feature maps. All feature maps will expand, *including the output feature maps*, that used to be 1x1 for 32x32 input, which will give more than one prediction.\n",
    "\n",
    "Lets see this in practice..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Choose an index of an image to test on...\n",
    "index_of_img = 4\n",
    "image_for_cnn = test_imgs_cnn[ index_of_img : index_of_img+1, :, :, : ] # [1, 1, 32, 32]\n",
    "real_lbl = test_lbls[index_of_img]\n",
    "plot_image(image_for_cnn[0,0,:,:], cmap=\"gray\")\n",
    "\n",
    "######### TODO: Run inference on the ORIGINAL 32x32 image. ###################\n",
    "# Do a forward pass with fclenet\n",
    "pred_probs = fclenet.???( torch.tensor(image_for_cnn, dtype=torch.float) ) # Outp shape: [1, 10]\n",
    "pred_probs = pred_probs.detach().numpy() # make tensor numpy\n",
    "pred_lbls = np.argmax(pred_probs, axis=???) # Shape: [1]\n",
    "#############################################################################\n",
    "print(\"For input of shape:\", image_for_cnn.shape, \" FCLeNet gave output of shape \", pred_probs.shape)\n",
    "print(\"Predicted class posterior probabilities:\", pred_probs)\n",
    "print(\"Predicted class (argmax) is:\", pred_lbls)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Now make a larger image to apply FCLeNet on...\n",
    "# Pad the 32x32 image in the H and W dimension enough to become 64 x 64\n",
    "image_for_cnn_padded = np.pad(image_for_cnn, ((0,0),(0,0),(5,27),(27,5)), mode='edge')\n",
    "print(\"image_for_cnn_padded.shape :\", image_for_cnn_padded.shape)\n",
    "plot_image(image_for_cnn_padded[0,0,:,:])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "######### TODO: Run inference with FCLeNet on the padded 64 x 64 image.  ###############\n",
    "pred_probs_padded = fclenet.???( torch.tensor(image_for_cnn_padded, dtype=torch.float) ) # shape: [1, 10, H_out, W_out]\n",
    "pred_probs_padded = pred_probs_padded.detach().numpy() # make tensor numpy\n",
    "pred_lbls_padded = np.argmax(pred_probs_padded, axis=1) # Shape: [1, H_out, W_out]\n",
    "########################################################################################\n",
    "print(\"For input of shape:\", image_for_cnn_padded.shape, \" FCLeNet gave output of shape:\", pred_probs_padded.shape)\n",
    "print(\"Plotting output of Channel #\", real_lbl, \"(real class) of the last conv layer (classification layer):\")\n",
    "plot_image(pred_probs_padded[0,real_lbl,:,:], cmap=\"bwr\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For a 64 x 64 input, FCLeNet.forward() should output a \\[1,10,9,9\\] matrix. For each of the 10 classes, it outputs a *probability map* of size \\[9,9\\] (the feature map output by the last conv). Above you should see plotted the probability map for the *real* class of the digit in the input.\n",
    "\n",
    "**Q: Why 9x9 pixels in the output? (It has to do with the strides of the pooling layers and the size of input.)**  \n",
    "**A: In the lecture slides...**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Task 5: Upsample the output to the original resolution\n",
    "\n",
    "Comparing the output with the padded 64x64 image, it looks as if the network **localizes** the digit in the image. But the output is in low resolution. Why? Because of the x4 downsampling done inside the network by the 2 pooling layers (each downsamples x2).\n",
    "\n",
    "Lets **upsample** it back to original resolution with **interpolation**. We will do this following the method discussed in the lecture slides.\n",
    "- **Repeat elements x4** in the spatial dimensions (H,W).  \n",
    "- Then **convolve with a uniform kernel** in the spatial dimensions (H,W)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy import signal\n",
    "\n",
    "############# TODO: Repeat elements x4 along the two spatial dimensions #####################\n",
    "pred_probs_padded_ups = np.repeat(pred_probs_padded, repeats=4, axis=???) # [N,Class,H,W]\n",
    "pred_probs_padded_ups = np.repeat(pred_probs_padded_ups, repeats=???, axis=3)\n",
    "print(\"Plotting image after repetition....................\")\n",
    "plot_image(pred_probs_padded_ups[0,real_lbl,:,:], cmap=\"bwr\")\n",
    "print(\"Upsampled image after repetition has shape:\", pred_probs_padded_ups.shape) # (1, 10, 33, 33)\n",
    "############################################################################################\n",
    "# Convolve with uniform kernel:\n",
    "kernel = np.ones([1,1,4,4])/16.\n",
    "pred_probs_padded_ups = signal.convolve(pred_probs_padded_ups, kernel, mode='valid')\n",
    "print(\"Plotting image after convolution...................\")\n",
    "plot_image(pred_probs_padded_ups[0,4], cmap=\"bwr\")\n",
    "\n",
    "print(\"Upsampled image after convolution has shape:\", pred_probs_padded_ups.shape) # (1, 10, 33, 33)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If done right, you will notice it looks like a very good localisation of the digit.\n",
    "\n",
    "Notice the shape of the upsampled image. It should be 33x33.  \n",
    "- The initial 9x9 voxels were repeated x4, up to 36x36.  \n",
    "- The convolution with mode='valid' requires that the kernel is fully contained in the image for a response.  \n",
    "- Thus, convolving a 36x36 image with a 4x4 kernel gives 33x33 responses.  \n",
    "- The whole process can be seen as if we interpolated 3 voxels in between each of the original 9x9 voxels.\n",
    "\n",
    "*Each 'valid' convolution with kernel of size k reduces the shape of the input by k-1.*  \n",
    "**Why do we care?** Because this is what happens within the neural network as well with every conv/pool.  \n",
    "\n",
    "**Eventhough we upsampled, the output is not same size as the original input, 64x64. Why?**  \n",
    "Exactly because of the above behaviour of the **'valid' convolutions within the net (and pools with ceiling=True)**.  \n",
    "With every conv or pool with kernel of size k, the feature maps get reduced in size by (k-1). **Except** if we use **padding=True** in the net, though this may cause problems for segmentation (cf. lecture slides).  \n",
    "Padding was quite irrelevant for classification nets, but becomes important for segmentation.\n",
    "\n",
    "**Q: The output (33x33) is 31 pixels smaller in each spatial dimension in comparison to the input (64x64). Can you come up with an equation that computes how much is the output's size, as a function of the input's size and the size of the receptive field of the network?**  \n",
    "**A: ???**\n",
    "\n",
    "Note: Very good material is in Theano's documentation (discontinued, original DL library): http://deeplearning.net/software/theano/tutorial/conv_arithmetic.html\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Task 6: Segmentation of Brain Tumors with FCLeNet\n",
    "\n",
    "Recap of what we have seen:\n",
    "- Fully convolutional nets can be used to **localise** something in an image.\n",
    "- Their **output** is of **lower resolution** due to conv/pool with *strides*.\n",
    "- **Output is smaller** than the input image, shrinking around the borders with every **'valid' conv/pool**.\n",
    "\n",
    "In this last, most important task, we will combine all we have learned:\n",
    "- We will use FCLeNet for **segmentation** of an image.\n",
    "- We will extend FCLeNet for segmentation, to **learn to upsample within the net**.\n",
    "- We will ensure to segment the whole image, by **padding the input** as required.\n",
    "\n",
    "For this, we will use a new database. We will segment brain tumors, from 2D slices of brain MRIs.  \n",
    "\n",
    "**Note: This is related to the task you will get for the coursework, so invest time to understand it.**\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Preliminary: Load data & make one-hot ground truth labels\n",
    "\n",
    "The below will load brain images and segmentation labels for training and testing.  \n",
    "It is exactly the same as the steps we were taking for MNIST, except that we don't normalize intentisities. **They are already loaded normalized**.  \n",
    "\n",
    "The only **important difference** are the ground truth labels for segmentation..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import imageio\n",
    "\n",
    "\n",
    "def get_tumor_data(data_dir, train):\n",
    "    if train:\n",
    "        paths_to_imgs =[data_dir + \"image_0.png\",\n",
    "                        data_dir + \"image_1.png\"]\n",
    "        paths_to_gts = [data_dir + \"seg_0.png\",\n",
    "                        data_dir + \"seg_1.png\"]\n",
    "    else: # test\n",
    "        paths_to_imgs =[data_dir + \"image_2.png\"]\n",
    "        paths_to_gts = [data_dir + \"seg_2.png\"]\n",
    "\n",
    "    assert len(paths_to_imgs) == len(paths_to_gts)\n",
    "    data_x = None\n",
    "    data_y = None\n",
    "    for i in range(len(paths_to_imgs)):\n",
    "        img = imageio.imread(paths_to_imgs[i]) # [H, W]\n",
    "        img = np.reshape(img, newshape=[1]+list(img.shape)) # [1, H, W]\n",
    "        gt  = imageio.imread(paths_to_gts[i]) # [H, W]\n",
    "        gt  = np.reshape(gt, newshape=[1]+list(gt.shape)) # [1, H, W]\n",
    "        if data_x is None:\n",
    "            data_x = img.copy()\n",
    "            data_y = gt.copy()\n",
    "        else:\n",
    "            data_x = np.concatenate((data_x, img), axis=0) # [N, H, W]\n",
    "            data_y = np.concatenate((data_y, gt), axis=0) # [N, H, W]\n",
    "            \n",
    "    data_x = (data_x - np.mean(data_x, axis=(1,2), keepdims=True))/np.std(data_x, axis=(1,2), keepdims=True)\n",
    "    data_y[data_y>0] = 1\n",
    "    return data_x, data_y\n",
    "\n",
    "\n",
    "# Load the data. NOTE: Their intensities are already normalized.\n",
    "train_imgs, train_lbls = get_tumor_data(data_dir=data_brain_dir, train=True)\n",
    "test_imgs, test_lbls = get_tumor_data(data_dir=data_brain_dir, train=False)\n",
    "\n",
    "print(\"[train_imgs] Type: \", type(train_imgs), \"|| Shape:\", train_imgs.shape, \"|| Data type: \", train_imgs.dtype )\n",
    "print(\"[train_lbls] Type: \", type(train_lbls), \"|| Shape:\", train_lbls.shape, \"|| Data type: \", train_lbls.dtype )\n",
    "print('[train] Intensities in images [min,max]:', np.min(train_imgs), np.max(train_imgs))\n",
    "print('[train] Values in class labels:', np.unique(train_lbls))\n",
    "print(\"[test_imgs] Type: \", type(test_imgs), \"|| Shape:\", test_imgs.shape, \"|| Data type: \", test_imgs.dtype )\n",
    "print(\"[test_lbls] Type: \", type(test_lbls), \"|| Shape:\", test_lbls.shape, \"|| Data type: \", test_lbls.dtype )\n",
    "print('[test] Intensities in images [min,max]:', np.min(test_imgs), np.max(test_imgs))\n",
    "print('[test] Values in class labels:', np.unique(test_lbls))\n",
    "\n",
    "C_classes = len(np.unique(train_lbls))\n",
    "\n",
    "# Change representation of labels to one-hot vectors of length C=2.\n",
    "def make_NHW_lbls_onehot(lbls, num_classes):\n",
    "    # lbls: np.array [N, H, W], ints\n",
    "    # returns: np.array [N, H, W, C], 0 or 1\n",
    "    onehot_shape = (lbls.shape[0], num_classes, lbls.shape[1], lbls.shape[2])\n",
    "    lbls_onehot = np.zeros(shape=onehot_shape)\n",
    "    for n in range(lbls.shape[0]):\n",
    "        for x in range(lbls.shape[1]):\n",
    "            for y in range(lbls.shape[2]):\n",
    "                for c in range(num_classes):\n",
    "                    lbls_onehot[n,c,x,y] = 1 if lbls[n,x,y] == c else 0\n",
    "    return lbls_onehot\n",
    "\n",
    "train_lbls_onehot = make_NHW_lbls_onehot(train_lbls, C_classes)\n",
    "test_lbls_onehot = make_NHW_lbls_onehot(test_lbls, C_classes)\n",
    "print(\"[train_lbls]        Type: \", type(train_lbls), \"|| Shape:\", train_lbls.shape, \" || Data type: \", train_lbls.dtype )\n",
    "print(\"[train_lbls_onehot] Type: \", type(train_lbls_onehot), \"|| Shape:\", train_lbls_onehot.shape, \" || Data type: \", train_lbls_onehot.dtype )\n",
    "print(\"[test_lbls]        Type: \", type(test_lbls), \"|| Shape:\", test_lbls.shape, \" || Data type: \", test_lbls.dtype )\n",
    "print(\"[test_lbls_onehot] Type: \", type(test_lbls_onehot), \"|| Shape:\", test_lbls_onehot.shape, \" || Data type: \", test_lbls_onehot.dtype )\n",
    "\n",
    "# Plot the test image...\n",
    "print(\"Plotting the test image and its ground truth segmentation label.\")\n",
    "plot_image(test_imgs[0,:,:])\n",
    "plot_image(test_lbls[0,:,:])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Observe in the output of the above:\n",
    "- We have 2 training images, each of shape 169 x 129. (train_imgs.shape = (2, 169, 129))  \n",
    "- We have 1 testing image, also of shape 169 x 129. (test_imgs.shape = (1, 169, 129))  \n",
    "\n",
    "Each has an associated ground truth **segmentation mask**:\n",
    "- Each segmentation mask is also of shape 169 x 129. **Aligned** with corresponding image.\n",
    "- Each segmentation mask is **binary**. A pixel has value 0 if it is **backround**, 1 if it is **tumor**.\n",
    "- We have 2 segmentation masks for training (train_lbls.shape=(2,169,129))\n",
    "- We have 1 segmentation mask for testing (test_lbls.shape=(2,169,129))\n",
    "- The one-hot segmentation masks are respectively of shape (2, 2, 169, 129) and (1, 2, 169, 129).\n",
    "\n",
    "For example:  \n",
    "train_lbls_onehot\\[0,1,50,60\\]==1 if in the 1st training image, the pixel at position \\[50,60\\] is a tumor.\n",
    "\n",
    "**The segmentation masks can be perceived as if they provide classification labels per pixel.**  \n",
    "Subsequently, we are going to train a **CNN for segmentation**.  \n",
    "It can be perceived as if we train it to do **pixel-wise classification**..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Build FCLeNet with learnt upsampling for segmentation\n",
    "\n",
    "For segmentation, we need fully-convolutional networks, but with output that is at the same resolution as their input. So that they give us a predicted class posterior probability for each pixel.\n",
    "\n",
    "Below, we will extend FCLeNet by performing upsampling x4 within the network.  \n",
    "This is to reverse the 2x downsampling made by the 2 pooling layers.  \n",
    "We will do this similarly to how we upsampled the output of FCLeNet in task 6:  \n",
    "- Repeat by x4 in each spatial dimension the feature maps of the last hidden layer.\n",
    "- Convolve with a kernel of \\[height,width\\]=\\[4,4\\]\n",
    "- We are going to *learn* the kernel for the convolution of the upsampling module, instead for a fixed one.\n",
    "\n",
    "**Note: The above procedure is similar to what transpose-convolution internally implements (often called deconvolution in DL literature).**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Helper function\n",
    "def torch_repeat(in_tens, repeats, axis):\n",
    "    # Repeat FM in the 2 last dimensions, to upsample back to the normal resolution space.\n",
    "    # in_tens: [batch size, num of FMs, H, W]. Input/output of conv layers.\n",
    "    # repeat_per_dim: [repetitions axis H, repetitions axis W]\n",
    "    # returns: Tensor of size: [batch size, num of FMs, H*repeat[0], W*repeat[1] ]\n",
    "    \n",
    "    # NOTE: Exactly the same API and behaviour as numpy.repeat(...)\n",
    "    # Because torch.repeat is similar to numpy.tile(...), not what we want.\n",
    "    # See: https://stackoverflow.com/questions/35227224/torch-repeat-tensor-like-numpy-repeat\n",
    "    tens = in_tens\n",
    "    assert axis>0\n",
    "    # Combine dimension to previous\n",
    "    shape_flat = list(in_tens.shape)\n",
    "    shape_flat[axis-1] = in_tens.shape[axis-1]*in_tens.shape[axis]\n",
    "    shape_flat[axis] = 1\n",
    "    tens_flat = tens.reshape( shape_flat )\n",
    "    # Tile\n",
    "    repeat_per_dim = [1]*len(in_tens.shape)\n",
    "    repeat_per_dim[axis] = repeats\n",
    "    tens_rep_flat = tens_flat.repeat( repeat_per_dim ) # This is what numpy.tile(...) does.\n",
    "    # Reshape to what it should be.\n",
    "    shape_result = list(in_tens.shape)\n",
    "    shape_result[axis] = in_tens.shape[axis]*repeats\n",
    "    tens_rep = tens_rep_flat.reshape( shape_result )\n",
    "    return tens_rep"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class FCLeNet_Seg(nn.Module):\n",
    "    def __init__(self, num_classes):\n",
    "        super(FCLeNet_Seg, self).__init__()\n",
    "        ############## TODO: Complete the implementation ##################################\n",
    "        # Create exactly the same implementation as FCLeNet, but with one added layer:\n",
    "        # conv(5x5)->pool(2x2)->conv(5x5)->pool(2x2)->conv(5x5)->conv(1x1)->upsample->conv(1x1)\n",
    "        self.conv1 = nn.Conv2d(1, ???, kernel_size=5, bias=True, padding=0)\n",
    "        self.conv2 = nn.Conv2d(???, 16, kernel_size=???, bias=True, padding=0)\n",
    "        self.conv3 = nn.Conv2d(???, ???, kernel_size=???, bias=True, padding=0)\n",
    "        self.conv4 = nn.Conv2d(120, ???, kernel_size=1, bias=True, padding=0)\n",
    "        self.conv_ups = nn.Conv2d(84, 84, kernel_size=4, bias=False, padding=0) # Kernel for the upsampling step.\n",
    "        self.conv5 = nn.Conv2d(???, num_classes, kernel_size=???, bias=True, padding=0)\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = F.max_pool2d(F.relu(self.conv1(x)), kernel_size=2, stride=2, padding=0, ceil_mode=False)\n",
    "        x = F.max_pool2d(F.relu(self.conv2(x)), kernel_size=2, stride=2, padding=0, ceil_mode=False)\n",
    "        x = F.relu(self.conv3(x))\n",
    "        x = F.relu(self.conv4(x))\n",
    "        x = torch_repeat(x, repeats=4, axis=???) # Repeat 1 of upsampling step, ala Task 6.\n",
    "        x = torch_repeat(x, repeats=???, axis=3) # Repeat 2 of upsampling step, ala Task 6.\n",
    "        x = self.???(x) \n",
    "        x = self.conv5(x)\n",
    "        # Note: The repeats and conv_ups can be replaced with a single torch.nn.ConvTranspose2d ...\n",
    "        # ... but we prefer looking under the hood.\n",
    "        ###################################################################################\n",
    "        \n",
    "        y_pred = F.softmax(x, dim=1) # y_pred.shape = [N, Classes, H_out, W_out]\n",
    "        return y_pred\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Cross entropy for segmentation\n",
    "\n",
    "We below provide the cross-entropy loss that will be used in the case of segmentation.   \n",
    "It is *almost* the same as the one used for classification (preliminaries of this tutorial and Tutorial 3).  \n",
    "\n",
    "As we previously mentioned, a segmentation network can be seen as if it is trained for pixel-wise classification.  \n",
    "As such, it can be perceived as if **in the loss, each pixel is treated as another sample**.  \n",
    "Thus the final torch.mean(...) is taken over the batch samples (images N) and each of the H_out*W_out pixels.  \n",
    "Compare with classification cross entropy for clarity (beginning of tutorial).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def cross_entropy_segmentation(y_pred, y_real, eps=1e-7):\n",
    "    # Cross entropy for segmentation.\n",
    "    # y_pred: Tensor of shape [N, Classes, H_out, W_out]. Predicted class-posterior probabilities from forward().\n",
    "    # y_real: One-hot representation of segmentation masks. Same shape as y_pred.\n",
    "    \n",
    "    x_entr_per_sample = - torch.sum( y_real * torch.log(y_pred + eps), dim=1) # Sum over classes.\n",
    "    # x_entr_per_sample is now of shape [N, H_out, W_out]\n",
    "    loss = torch.mean(x_entr_per_sample, dim=(0,1,2)) # Mean over batch & over spatial positions.\n",
    "    \n",
    "    return loss"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Train FCLeNet for segmentation\n",
    "\n",
    "Finally, we will train the network.\n",
    "\n",
    "But don't forget. Our network's outputs are 31 pixels less in each spatial dimension (H,W) than the input.  \n",
    "So, to get a segmentation for the whole input, we will first **pad input with 31 pixels along dimensions (H,W)**."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython import display\n",
    "# Pytorch needs input to conv/pool to be of shape [N, Channels, H, W].\n",
    "# For grayscale images, there is only 1 image channel. We add this *channels dimension*:\n",
    "IMAGE_CHANNELS = 1\n",
    "train_imgs_cnn = train_imgs.reshape([train_imgs.shape[0], IMAGE_CHANNELS, train_imgs.shape[1], train_imgs.shape[2]])\n",
    "test_imgs_cnn = test_imgs.reshape([test_imgs.shape[0], IMAGE_CHANNELS, test_imgs.shape[1], test_imgs.shape[2]])\n",
    "\n",
    "######## TODO: Fill the blanks (????) ###########################################################\n",
    "# Pad 31 voxels along each of the spatial dimensions of the input.\n",
    "# ... So that the final output is of same size as original input.\n",
    "# Preferably (roughly) half padding before, half after.\n",
    "train_imgs_cnn = np.pad(train_imgs_cnn, ((0,0), (0,0), (15,???), (???,16)), mode='edge')\n",
    "test_imgs_cnn = np.pad(test_imgs_cnn, ((0,0), (0,0), (???,???), (???,???)), mode='edge')\n",
    "print(\"train_imgs_cnn.shape=\", train_imgs_cnn.shape)\n",
    "print(\"train_lbls.shape=\", train_lbls.shape)\n",
    "##################################################################################################\n",
    "\n",
    "# Create the network\n",
    "fclenet_seg = FCLeNet_Seg(num_classes=C_classes)\n",
    "\n",
    "import torch.optim as optim\n",
    "grad_descent_optimizer = optim.SGD(fclenet_seg.parameters(), lr=0.05, momentum=0.0)\n",
    "\n",
    "# Start training\n",
    "rng = np.random.RandomState(seed=SEED)\n",
    "gradient_descent(fclenet_seg,\n",
    "                 cross_entropy_segmentation,\n",
    "                 grad_descent_optimizer,\n",
    "                 rng,\n",
    "                 train_imgs_cnn,\n",
    "                 train_lbls_onehot,\n",
    "                 test_imgs_cnn,\n",
    "                 test_lbls_onehot,\n",
    "                 N_batch_size=2, \n",
    "                 total_iters=300,\n",
    "                 iters_per_test=10,\n",
    "                 is_tumor_segm=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If the whole task was performed correctly, you should see the network learning.  \n",
    "The probability map for the tumor class will be plotted every few iterations, for the test image.  \n",
    "If the task was performed correctly, you will see the tumor bright-up after ~200 iterations."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## This notebook:\n",
    "Copyright 2020, Imperial College London  \n",
    "Author: Konstantinos Kamnitsas (konstantinos.kamnitsas12@imperial.ac.uk)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}