[
  {
    "path": ".gitignore",
    "content": "#cmake related files\nCMakeCache.txt\nCMakeFiles\nCMakeScripts\nMakefile\ncmake_install.cmake\ninstall_manifest.txt\nCTestTestfile.cmake\n#ignore all bin dirs\nbin/\n.DS_Store\n*.vtp\n*.pathlinesinfo\n*.pyc\n*.pyo\n*~\n*.bak\n*.swp\n*.o\n*.nii.gz\n*.mha\n*.raw\n*.mhd\n*.a\n*.orig # git merge conflict file\n# model file\n*.pth\n*.p\n\n### following copied from https://gist.github.com/octocat/9257657\n# Compiled source #\n###################\n*.com\n*.class\n*.dll\n*.exe\n*.o\n*.so\n\n# Packages #\n############\n# it's better to unpack these files and commit the raw source\n# git has its own built in compression methods\n*.7z\n*.dmg\n*.gz\n*.iso\n*.jar\n*.rar\n*.tar\n*.zip\n\n# Logs and databases #\n######################\n*.log\n*.sql\n*.sqlite\n\n# OS generated files #\n######################\n.DS_Store\n.DS_Store?\n._*\n.Spotlight-V100\n.Trashes\nehthumbs.db\nThumbs.db\n\n# Ignore data and experiments dirs, but keep folder organizations#\n######################\nexperiments\n"
  },
  {
    "path": "LICENSE",
    "content": "“Commons Clause” License Condition v1.0\n\nThe Software is provided to you by the Licensor under the\nLicense, as defined below, subject to the following condition.\n\nWithout limiting other conditions in the License, the grant\nof rights under the License will not include, and the License\ndoes not grant to you, the right to Sell the Software.\n\nFor purposes of the foregoing, “Sell” means practicing any or\nall of the rights granted to you under the License to provide\nto third parties, for a fee or other consideration (including\nwithout limitation fees for hosting or consulting/ support\nservices related to the Software), a product or service whose\nvalue derives, entirely or substantially, from the functionality\nof the Software. Any license notice or attribution required by\nthe License must also include this Commons Clause License\nCondition notice.\n\nSoftware: COVNet\n\nLicense: Apache 2.0\n\nLicensor: CuraCloud Corporation\n\n\n---------------------------------------------------------------------\n\n\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\n"
  },
  {
    "path": "README.md",
    "content": "# COVID-19 Detection Neural Network (COVNet)\nThis is a PyTorch implementation of the paper \"[Artificial Intelligence Distinguishes COVID-19 from Community Acquired Pneumonia on Chest CT](https://pubs.rsna.org/doi/10.1148/radiol.2020200905)\". It supports training, validation and testing for COVNet.\n\n<img src=\"assets/overview.png\" width=\"600\">\n\n### Updates & Notices\n- 2020-03-30: Thanks for the interest in our work. Unfortunately, we do not own the data, and we have to get permission from our collaborators before we share the data and model. We will update later.\n\n## Citation\nIf you find this code is useful for your research, please consider citing:\n```\n@article{li2020artificial,\n  title={Artificial Intelligence Distinguishes COVID-19 from Community Acquired Pneumonia on Chest CT},\n  author={Li, Lin and Qin, Lixin and Xu, Zeguo and Yin, Youbing and Wang, Xin and Kong, Bin and Bai, Junjie and Lu, Yi and Fang, Zhenghan and Song, Qi and Cao, Kunlin and others},\n  journal={Radiology},\n  year={2020}\n}\n```\n\n## Setup\n### Prerequisites\n- Anaconda 3.7\n- PyTorch 1.4\n- SimpleITK\n- batchgenerators\n- tensorboardX\n\n### Prepare data\nPreprocess the data according to the [Appendix E1 section](https://pubs.rsna.org/doi/suppl/10.1148/radiol.2020200905/suppl_file/ry_200905_supp_in%20press.pdf) of the paper and organize them as the following. A example of train.csv and val.csv are also provided.\n```\ndata\n├── caseid1\n|   ├── masked_ct.nii\n|   └── mask.nii.gz\n├── caseid2\n|   ├── masked_ct.nii\n|   └── mask.nii.gz\n├── caseid3\n|   ├── masked_ct.nii\n|   └── mask.nii.gz\n├── caseid4\n|   ├── masked_ct.nii\n|   └── mask.nii.gz\n├── train.csv\n└── val.csv\n```\n\n## COVNet\n<img src=\"assets/demo.png\" width=\"600\">\n\n### Training\nTraining a COVNet with default arguments. Model checkpoints and tensorboard logs are written out to a unique directory created by default within `experiments/models` and `experiments/logs` respectively after starting training.\n```\npython main.py\n```\n\n### Validation and Testing\nYou can run validation and testing on the checkpointed best model by:\n```\npython test.py\n```\n"
  },
  {
    "path": "config.py",
    "content": "import argparse\n\n\ndef parse_arguments():\n    \"\"\"Argument Parser for the commandline argments\n    :returns: command line arguments\n\n    \"\"\"\n    ##########################################################################\n    #                            Training setting                            #\n    ##########################################################################\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--n_classes', help=\"Number of classes\", type=int,\n                        default=3)\n    parser.add_argument('--lr', type=float, default=1e-5)\n    parser.add_argument('--epochs', type=int, default=50)\n    parser.add_argument('--lr_scheduler', type=str,\n                        default='plateau', choices=['plateau', 'step'])\n    parser.add_argument('--gamma', type=float,\n                        help='LR Multiplicative factor if lr_scheduler is step',\n                        default=0.1)\n    parser.add_argument('--patience', type=int, default=9)\n    parser.add_argument('--log-every', type=int, default=100)\n    parser.add_argument('--save-model', type=bool, default=True)\n    args = parser.parse_args()\n\n    return args\n"
  },
  {
    "path": "data/train.csv",
    "content": "case,label\ncaseid1,0\ncaseid2,1\ncaseid3,2\n"
  },
  {
    "path": "data/val.csv",
    "content": "case,label\ncaseid4,0\n"
  },
  {
    "path": "dataset.py",
    "content": "import os\nimport pandas as pd\nimport numpy as np\n\nimport torch\nimport torch.utils.data as data\nimport SimpleITK as sitk\nfrom batchgenerators.transforms import noise_transforms\nfrom batchgenerators.transforms import spatial_transforms\n\n\nclass NCovDataset(data.Dataset):\n    def __init__(self, root_dir, stage='train'):\n        super().__init__()\n        self.root_dir = root_dir\n        self.stage = stage\n        assert stage in ['train', 'val', 'test']\n\n        if stage == 'train':\n            split_file = 'train.csv'\n        elif stage == 'val':\n            split_file = 'val.csv'\n        elif stage == 'test':\n            # We just assume validation set is the same as test set\n            split_file = 'val.csv'\n\n        df = pd.read_csv(os.path.join(root_dir, split_file),\n                              converters={'case': str, 'label': int})\n        df = df.set_index('case')\n        self.case_ids = list(df.index)\n        self.labels = df['label'].values.tolist()\n\n    def __len__(self):\n        return len(self.case_ids)\n\n    def __getitem__(self, index):\n        fn = os.path.join(self.root_dir, self.case_ids[index], 'masked_ct.nii')\n        image = sitk.ReadImage(fn)\n        array = sitk.GetArrayFromImage(image)\n\n        mask_fn = os.path.join(self.root_dir, self.case_ids[index],\n                               'mask.nii.gz')\n        mask_image = sitk.ReadImage(mask_fn)\n        mask = sitk.GetArrayFromImage(mask_image)\n\n        array, mask = array[None, ...], mask[None, ...]\n        if self.stage == 'train':\n            # Default randomly mirroring the second and third axes\n            array, mask = spatial_transforms.augment_mirroring(\n                array, sample_seg=mask, axes=(1, 2))\n        array, mask = array[0], mask[0]\n\n        ######################################################\n        #  Preprocessing for both train and validation data  #\n        ######################################################\n        min_value, max_value = -1250, 250\n        np.clip(array, min_value, max_value, out=array)\n        array = (array - min_value) / (max_value - min_value)\n\n        # data should be a numpy array with shape [x, y, z] or [c, x, y, z]\n        # seg should be a numpy array with shape [x, y, z]\n        full_channel = np.stack([array, array, array])\n\n        if self.stage == 'train':\n            full_channel, mask = self.do_augmentation(full_channel, mask)\n        else:\n            mask = mask[None, ...]\n\n        # remove the noise in the non-lung regions\n        mask = mask[0]\n        full_channel[0][mask == 0] = 0\n        full_channel[1][mask == 0] = 0\n        full_channel[2][mask == 0] = 0\n        label = self.labels[index]\n        full_channel = torch.FloatTensor(full_channel).permute((1, 0, 2, 3))\n\n        return full_channel, label, self.case_ids[index]\n\n    def do_augmentation(self, array, mask):\n        \"\"\"Augmentation for the training data.\n\n        :array: A numpy array of size [c, x, y, z]\n        :returns: augmented image and the corresponding mask\n\n        \"\"\"\n        # normalize image to range [0, 1], then apply this transform\n        patch_size = np.asarray(array.shape)[1:]\n        augmented = noise_transforms.augment_gaussian_noise(\n            array, noise_variance=(0, .015))\n\n        # need to become [bs, c, x, y, z] before augment_spatial\n        augmented = augmented[None, ...]\n        mask = mask[None, None, ...]\n        r_range = (0, (3 / 360.) * 2 * np.pi)\n        cval = 0.\n\n        augmented, mask = spatial_transforms.augment_spatial(\n            augmented, seg=mask, patch_size=patch_size,\n            do_elastic_deform=True, alpha=(0., 100.), sigma=(8., 13.),\n            do_rotation=True, angle_x=r_range, angle_y=r_range, angle_z=r_range,\n            do_scale=True, scale=(.9, 1.1),\n            border_mode_data='constant', border_cval_data=cval,\n            order_data=3,\n            p_el_per_sample=0.5,\n            p_scale_per_sample=.5,\n            p_rot_per_sample=.5,\n            random_crop=False\n        )\n        mask = mask[0]\n        return augmented[0], mask\n\n    def make_weights_for_balanced_classes(self):\n        \"\"\"Making sampling weights for the data samples\n        :returns: sampling weigghts for dealing with class imbalance problem\n\n        \"\"\"\n        n_samples = len(self.labels)\n        unique, cnts = np.unique(self.labels, return_counts=True)\n        cnt_dict = dict(zip(unique, cnts))\n\n        weights = []\n        for label in self.labels:\n            weights.append(n_samples / float(cnt_dict[label]))\n        return weights\n"
  },
  {
    "path": "main.py",
    "content": "import os\nimport numpy as np\nimport time\n\nfrom tensorboardX import SummaryWriter\nimport torch\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport dataset\nimport model\nimport config\nimport utils\n\n\ndef get_lr(optimizer):\n    for param_group in optimizer.param_groups:\n        return param_group['lr']\n\n\ndef train_model(model, train_loader, epoch, num_epochs, optimizer, writer,\n                current_lr, log_every=100):\n    n_classes = model.n_classes\n    metric = torch.nn.CrossEntropyLoss()\n\n    y_probs = np.zeros((0, n_classes), np.float)\n    losses, y_trues = [], []\n    model.train()\n\n    for m in model.modules():\n        if isinstance(m, nn.BatchNorm2d):\n            m.train()\n            m.weight.requires_grad = False\n            m.bias.requires_grad = False\n\n    for i, (image, label, case_id) in enumerate(train_loader):\n        optimizer.zero_grad()\n        if torch.cuda.is_available():\n            image = image.cuda()\n            label = label.cuda()\n\n        prediction = model.forward(image.float())\n        loss = metric(prediction, label.long())\n        loss.backward()\n        optimizer.step()\n\n        loss_value = loss.item()\n        losses.append(loss_value)\n        y_prob = F.softmax(prediction, dim=1)\n        y_probs = np.concatenate([y_probs, y_prob.detach().cpu().numpy()])\n        y_trues.append(label.item())\n\n        metric_collects = utils.calc_multi_cls_measures(y_probs, y_trues)\n        n_iter = epoch * len(train_loader) + i\n        writer.add_scalar('Train/Loss', loss_value, n_iter)\n\n        if (i % log_every == 0) & (i > 0):\n            utils.print_progress(epoch + 1, num_epochs, i, len(train_loader),\n                                 np.mean(losses), current_lr, metric_collects)\n\n    train_loss_epoch = np.round(np.mean(losses), 4)\n    return train_loss_epoch, metric_collects\n\n\ndef evaluate_model(model, val_loader, epoch, num_epochs, writer, current_lr,\n                   log_every=20):\n    n_classes = model.n_classes\n    metric = torch.nn.CrossEntropyLoss()\n\n    model.eval()\n    for m in model.modules():\n        if isinstance(m, nn.BatchNorm2d):\n            m.train()\n            m.weight.requires_grad = False\n            m.bias.requires_grad = False\n\n    y_probs = np.zeros((0, n_classes), np.float)\n    losses, y_trues = [], []\n\n    for i, (image, label, case_id) in enumerate(val_loader):\n\n        if torch.cuda.is_available():\n            image = image.cuda()\n            label = label.cuda()\n\n        prediction = model.forward(image.float())\n        loss = metric(prediction, label.long())\n\n        loss_value = loss.item()\n        losses.append(loss_value)\n        y_prob = F.softmax(prediction, dim=1)\n        y_probs = np.concatenate([y_probs, y_prob.detach().cpu().numpy()])\n        y_trues.append(label.item())\n\n        metric_collects = utils.calc_multi_cls_measures(y_probs, y_trues)\n\n        n_iter = epoch * len(val_loader) + i\n        writer.add_scalar('Val/Loss', loss_value, n_iter)\n\n        if (i % log_every == 0) & (i > 0):\n            prefix = '*Val|'\n            utils.print_progress(epoch + 1, num_epochs, i, len(val_loader),\n                                 np.mean(losses), current_lr, metric_collects,\n                                 prefix=prefix)\n\n    val_loss_epoch = np.round(np.mean(losses), 4)\n    return val_loss_epoch, metric_collects\n\n\ndef main(args):\n    \"\"\"Main function for the training pipeline\n\n    :args: commandlien arguments\n    :returns: None\n\n    \"\"\"\n    ##########################################################################\n    #                             Basic settings                             #\n    ##########################################################################\n    exp_dir = 'experiments'\n    log_dir = os.path.join(exp_dir, 'logs')\n    model_dir = os.path.join(exp_dir, 'models')\n    os.makedirs(model_dir, exist_ok=True)\n\n    ##########################################################################\n    #  Define all the necessary variables for model training and evaluation  #\n    ##########################################################################\n    writer = SummaryWriter(log_dir)\n    train_dataset = dataset.NCovDataset('data/', stage='train')\n    weights = train_dataset.make_weights_for_balanced_classes()\n    weights = torch.DoubleTensor(weights)\n    sampler = torch.utils.data.sampler.WeightedRandomSampler(\n        weights, len(train_dataset.case_ids))\n\n    train_loader = torch.utils.data.DataLoader(\n        train_dataset, batch_size=1, num_workers=20,\n        drop_last=False, sampler=sampler)\n\n    val_dataset = dataset.NCovDataset('data/', stage='val')\n    val_loader = torch.utils.data.DataLoader(\n        val_dataset, batch_size=1, shuffle=False, num_workers=11,\n        drop_last=False)\n\n    cov_net = model.COVNet(n_classes=args.n_classes)\n    if torch.cuda.is_available():\n        cov_net = cov_net.cuda()\n    optimizer = optim.Adam(cov_net.parameters(), lr=args.lr, weight_decay=0.1)\n\n    if args.lr_scheduler == \"plateau\":\n        scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(\n            optimizer, patience=3, factor=.3, threshold=1e-4, verbose=True)\n    elif args.lr_scheduler == \"step\":\n        scheduler = torch.optim.lr_scheduler.StepLR(\n            optimizer, step_size=3, gamma=args.gamma)\n\n    best_val_loss = float('inf')\n    best_val_accu = float(0)\n\n    iteration_change_loss = 0\n    t_start_training = time.time()\n    ##########################################################################\n    #                           Main training loop                           #\n    ##########################################################################\n    for epoch in range(args.epochs):\n        current_lr = get_lr(optimizer)\n        t_start = time.time()\n\n        ############################################################\n        #  The actual training and validation step for each epoch  #\n        ############################################################\n        train_loss, train_metric = train_model(\n            cov_net, train_loader, epoch, args.epochs, optimizer, writer,\n            current_lr, args.log_every)\n\n        with torch.no_grad():\n            val_loss, val_metric = evaluate_model(\n                cov_net, val_loader, epoch, args.epochs, writer, current_lr)\n\n        ##############################\n        #  Adjust the learning rate  #\n        ##############################\n        if args.lr_scheduler == 'plateau':\n            scheduler.step(val_loss)\n        elif args.lr_scheduler == 'step':\n            scheduler.step()\n\n        t_end = time.time()\n        delta = t_end - t_start\n\n        utils.print_epoch_progress(train_loss, val_loss, delta, train_metric,\n                                   val_metric)\n        iteration_change_loss += 1\n        print('-' * 30)\n\n        train_acc, val_acc = train_metric['accuracy'], val_metric['accuracy']\n        file_name = ('train_acc_{}_val_acc_{}_epoch_{}.pth'.\n                     format(train_acc, val_acc, epoch))\n        torch.save(cov_net, os.path.join(model_dir, file_name))\n\n        if val_acc > best_val_accu:\n            best_val_accu = val_acc\n            if bool(args.save_model):\n                torch.save(cov_net, os.path.join(model_dir, 'best.pth'))\n\n        if val_loss < best_val_loss:\n            best_val_loss = val_loss\n            iteration_change_loss = 0\n\n        if iteration_change_loss == args.patience:\n            print(('Early stopping after {0} iterations without the decrease ' +\n                  'of the val loss').format(iteration_change_loss))\n            break\n    t_end_training = time.time()\n    print('training took {}s'.\n          format(t_end_training - t_start_training))\n\n\nif __name__ == \"__main__\":\n    args = config.parse_arguments()\n    main(args)\n"
  },
  {
    "path": "model.py",
    "content": "import torch\nimport torch.nn as nn\nfrom torchvision import models\n\n\nclass COVNet(nn.Module):\n    def __init__(self, n_classes):\n        super().__init__()\n        model = models.resnet50(pretrained=True)\n        layer_list = list(model.children())[:-2]\n        self.pretrained_model = nn.Sequential(*layer_list)\n\n        self.pooling_layer = nn.AdaptiveAvgPool2d(1)\n        self.classifer = nn.Linear(2048, n_classes)\n        self.n_classes = n_classes\n\n    def forward(self, x):\n        x = torch.squeeze(x, dim=0)\n        features = self.pretrained_model(x)\n        pooled_features = self.pooling_layer(features)\n        pooled_features = pooled_features.view(pooled_features.size(0), -1)\n        flattened_features = torch.max(pooled_features, 0, keepdim=True)[0]\n        output = self.classifer(flattened_features)\n        return output\n"
  },
  {
    "path": "test.py",
    "content": "import os\nfrom tqdm import tqdm\nimport numpy as np\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch\n\nimport model\nimport config\nimport dataset\nimport utils\n\n\ndef evaluate_model(model, val_loader):\n    metric = torch.nn.CrossEntropyLoss()\n    model.eval()\n\n    for m in model.modules():\n        if isinstance(m, nn.BatchNorm2d):\n            m.train()\n            m.weight.requires_grad = False\n            m.bias.requires_grad = False\n\n    y_probs = np.zeros((0, 3), np.float)\n    losses, y_trues = [], []\n\n    for i, (image, label, case_id) in enumerate(tqdm(val_loader)):\n        if torch.cuda.is_available():\n            image = image.cuda()\n            label = label.cuda()\n\n        prediction = model.forward(image.float())\n        loss = metric(prediction, label.long())\n\n        loss_value = loss.item()\n        losses.append(loss_value)\n        y_prob = F.softmax(prediction, dim=1).detach().cpu().numpy()\n\n        y_probs = np.concatenate([y_probs, y_prob])\n        y_trues.append(label.item())\n    metric_collects = utils.calc_multi_cls_measures(y_probs, y_trues)\n    val_loss_epoch = np.mean(losses)\n    return val_loss_epoch, metric_collects\n\n\ndef main(args):\n    \"\"\"Main function for the testing pipeline\n\n    :args: commandline arguments\n    :returns: None\n\n    \"\"\"\n    ##########################################################################\n    #                             Basic settings                             #\n    ##########################################################################\n    exp_dir = 'experiments'\n    model_dir = os.path.join(exp_dir, 'models')\n    model_file = os.path.join(model_dir, 'best.pth')\n    val_dataset = dataset.NCovDataset('data/', stage='val')\n    val_loader = torch.utils.data.DataLoader(\n        val_dataset, batch_size=1, shuffle=False, num_workers=11,\n        drop_last=False)\n\n    cov_net = model.COVNet(n_classes=args.n_classes)\n    if torch.cuda.is_available():\n        cov_net.cuda()\n\n    state = torch.load(model_file)\n    cov_net.load_state_dict(state.state_dict())\n\n    with torch.no_grad():\n        val_loss, metric_collects = evaluate_model(cov_net, val_loader)\n    prefix = '******Evaluate******'\n    utils.print_progress(mean_loss=val_loss, metric_collects=metric_collects,\n                         prefix=prefix)\n\n\nif __name__ == \"__main__\":\n    args = config.parse_arguments()\n    main(args)\n"
  },
  {
    "path": "utils.py",
    "content": "import numpy as np\nimport pandas as pd\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\n\n\ndef calc_multi_cls_measures(probs, label):\n    \"\"\"Calculate multi-class classification measures (Accuracy, precision,\n    Recall, AUC.\n\n    :probs: NxC numpy array storing probabilities for each case\n    :label: ground truth label\n    :returns: a dictionary of accuracy, precision and recall\n\n    \"\"\"\n    n_classes = probs.shape[1]\n    preds = np.argmax(probs, axis=1)\n    accuracy = accuracy_score(label, preds)\n    precisions = precision_score(label, preds, average=None,\n                                 labels=range(n_classes), zero_division=0.)\n    recalls = recall_score(label, preds, average=None, labels=range(n_classes),\n                           zero_division=0.)\n\n    metric_collects = {'accuracy': accuracy, 'precisions': precisions,\n                       'recalls': recalls}\n    return metric_collects\n\n\ndef print_progress(epoch=None, n_epoch=None, n_iter=None, iters_one_batch=None,\n                   mean_loss=None, cur_lr=None, metric_collects=None,\n                   prefix=None):\n    \"\"\"Print the training progress.\n\n    :epoch: epoch number\n    :n_epoch: total number of epochs\n    :n_iter: current iteration number\n    :mean_loss: mean loss of current batch\n    :iters_one_batch: number of iterations per batch\n    :cur_lr: current learning rate\n    :metric_collects: dictionary returned by function calc_multi_cls_measures\n    :returns: None\n\n    \"\"\"\n    accuracy = metric_collects['accuracy']\n    precisions = metric_collects['precisions']\n    recalls = metric_collects['recalls']\n\n    n_classes = len(precisions)\n\n    log_str = ''\n    if epoch is not None:\n        log_str += 'Ep: {0}/{1}|'.format(epoch, n_epoch)\n\n    if n_iter is not None:\n        log_str += 'It: {0}/{1}|'.format(n_iter, iters_one_batch)\n\n    if mean_loss is not None:\n        log_str += 'Loss: {0:.4f}|'.format(mean_loss)\n\n    log_str += 'Acc: {:.4f}|'.format(accuracy)\n    templ = 'Pr: ' + ', '.join(['{:.4f}'] * (n_classes-1)) + '|'\n    log_str += templ.format(*(precisions[1:].tolist()))\n    templ = 'Re: ' + ', '.join(['{:.4f}'] * (n_classes-1)) + '|'\n    log_str += templ.format(*(recalls[1:].tolist()))\n\n    if cur_lr is not None:\n        log_str += 'lr: {0}'.format(cur_lr)\n    log_str = log_str if prefix is None else prefix + log_str\n    print(log_str)\n\n\ndef print_epoch_progress(train_loss, val_loss, time_duration, train_metric,\n                         val_metric):\n    \"\"\"Print all the information after each epoch.\n\n    :train_loss: average training loss\n    :val_loss: average validation loss\n    :time_duration: time duration for current epoch\n    :train_metric_collects: a performance dictionary for training\n    :val_metric_collects: a performance dictionary for validation\n    :returns: None\n\n    \"\"\"\n    train_acc, val_acc = train_metric['accuracy'], val_metric['accuracy']\n    train_prec, val_prec = train_metric['precisions'], val_metric['precisions']\n    train_recalls, val_recalls = train_metric['recalls'], val_metric['recalls']\n    log_str = 'Train/Val| Loss: {:.4f}/{:.4f}|'.format(train_loss, val_loss)\n    log_str += 'Acc: {:.4f}/{:.4f}|'.format(train_acc, val_acc)\n\n    n_classes = len(train_prec)\n\n    templ = 'Pr: ' + ', '.join(['{:.4f}'] * (n_classes-1)) + '/'\n    log_str += templ.format(*(train_prec[1:].tolist()))\n    templ = ', '.join(['{:.4f}'] * (n_classes-1)) + '|'\n    log_str += templ.format(*(val_prec[1:].tolist()))\n\n    templ = 'Re: ' + ', '.join(['{:.4f}'] * (n_classes - 1)) + '/'\n    log_str += templ.format(*(train_recalls[1:].tolist()))\n    templ = ', '.join(['{:.4f}'] * (n_classes - 1)) + '|'\n    log_str += templ.format(*(val_recalls[1:].tolist()))\n    log_str += 'T(s) {:.2f}'.format(time_duration)\n    print(log_str)\n"
  }
]