[
  {
    "path": ".gitignore",
    "content": "*.pyc\ncheckpoints/\nlogs/\ndata/"
  },
  {
    "path": "LICENSE.md",
    "content": "Educational Community License, Version 2.0 (ECL-2.0)\n\nVersion 2.0, April 2007\n\nhttp://www.osedu.org/licenses/ \n\nThe Educational Community License version 2.0 (\"ECL\") consists of the Apache 2.0 license, modified to change the scope of the patent grant in section 3 to be specific to the needs of the education communities using this license. The original Apache 2.0 license can be found at: http://www.apache.org/licenses /LICENSE-2.0 \n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n\"License\" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.\n\n\"Licensor\" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.\n\n\"Legal Entity\" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, \"control\" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.\n\n\"You\" (or \"Your\") shall mean an individual or Legal Entity exercising permissions granted by this License.\n\n\"Source\" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.\n\n\"Object\" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.\n\n\"Work\" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).\n\n\"Derivative Works\" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.\n\n\"Contribution\" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, \"submitted\" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as \"Not a Contribution.\"\n\n\"Contributor\" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.\n\n2. Grant of Copyright License. \n\nSubject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. \n\nSubject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. Any patent license granted hereby with respect to contributions by an individual employed by an institution or organization is limited to patent claims where the individual that is the author of the Work is also the inventor of the patent claims licensed, and where the organization or institution has the right to grant such license under applicable grant and research funding agreements. No other express or implied licenses are granted.\n\n4. Redistribution. \n\nYou may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:\n\nYou must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a \"NOTICE\" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.\n\n5. Submission of Contributions. \n\nUnless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.\n\n6. Trademarks. \n\nThis License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. \n\nUnless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. \n\nIn no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. \n\nWhile redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Educational Community License to your work \n\nTo apply the Educational Community License to your work, attach\nthe following boilerplate notice, with the fields enclosed by\nbrackets \"[]\" replaced with your own identifying information.\n(Don't include the brackets!) The text should be enclosed in the\nappropriate comment syntax for the file format. We also recommend\nthat a file or class name and description of purpose be included on\nthe same \"printed page\" as the copyright notice for easier\nidentification within third-party archives.\n\nCopyright [yyyy] [name of copyright owner] Licensed under the\nEducational Community License, Version 2.0 (the \"License\"); you may\nnot use this file except in compliance with the License. You may\nobtain a copy of the License at\n\nhttp://www.osedu.org/licenses /ECL-2.0 \n\nUnless required by applicable law or agreed to in writing,\nsoftware distributed under the License is distributed on an \"AS IS\"\nBASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\nor implied. See the License for the specific language governing\npermissions and limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# Cutout\n\nThis repository contains the code for the paper [Improved Regularization of Convolutional Neural Networks with Cutout](https://arxiv.org/abs/1708.04552). \n\n## Introduction\n\nCutout is a simple regularization method for convolutional neural networks which consists of masking out random sections of input images during training. This technique simulates occluded examples and encourages the model to take more minor features into consideration when making decisions, rather than relying on the presence of a few major features.  \n  \n![Cutout applied to CIFAR-10](https://github.com/uoguelph-mlrg/Cutout/blob/master/images/cutout_on_cifar10.jpg \"Cutout applied to CIFAR-10\")\n\nBibtex:  \n```\n@article{devries2017cutout,  \n  title={Improved Regularization of Convolutional Neural Networks with Cutout},  \n  author={DeVries, Terrance and Taylor, Graham W},  \n  journal={arXiv preprint arXiv:1708.04552},  \n  year={2017}  \n}\n```\n\n## Results and Usage   \n### Dependencies  \n[PyTorch v0.4.0](http://pytorch.org/)  \n[tqdm](https://pypi.python.org/pypi/tqdm)\n\n### ResNet18  \nTest error (%, flip/translation augmentation, mean/std normalization, mean of 5 runs) \n\n| **Network** | **CIFAR-10** | **CIFAR-100** |\n| ----------- | ------------ | ------------- |\n| ResNet18    | 4.72         | 22.46         |\n| ResNet18 + cutout | 3.99   | 21.96         |  \n\nTo train ResNet18 on CIFAR10 with data augmentation and cutout:    \n`python train.py --dataset cifar10 --model resnet18 --data_augmentation --cutout --length 16`\n\nTo train ResNet18 on CIFAR100 with data augmentation and cutout:  \n`python train.py --dataset cifar100 --model resnet18 --data_augmentation --cutout --length 8`\n\n### WideResNet\nWideResNet model implementation from https://github.com/xternalz/WideResNet-pytorch  \n\nTest error (%, flip/translation augmentation, mean/std normalization, mean of 5 runs)  \n\n| **Network** | **CIFAR-10** | **CIFAR-100** | **SVHN** |\n| ----------- | ------------ | ------------- | -------- |\n| WideResNet  | 3.87         | 18.8          | 1.60     |\n| WideResNet + cutout | 3.08 | 18.41         | **1.30** |\n\nTo train WideResNet 28-10 on CIFAR10 with data augmentation and cutout:    \n`python train.py --dataset cifar10 --model wideresnet --data_augmentation --cutout --length 16`\n\nTo train WideResNet 28-10 on CIFAR100 with data augmentation and cutout:  \n`python train.py --dataset cifar100 --model wideresnet --data_augmentation --cutout --length 8`\n\nTo train WideResNet 16-8 on SVHN with cutout:  \n`python train.py --dataset svhn --model wideresnet --learning_rate 0.01 --epochs 160 --cutout --length 20`\n\n### Shake-shake Regularization Network\nShake-shake regularization model implementation from https://github.com/xgastaldi/shake-shake\n\nTest error (%, flip/translation augmentation, mean/std normalization, mean of 3 runs)  \n\n| **Network** | **CIFAR-10** | **CIFAR-100** |\n| ----------- | ------------ | ------------- |\n| Shake-shake | 2.86         | 15.58         |\n| Shake-shake + cutout | **2.56** | **15.20** |\n\nSee README in [shake-shake](https://github.com/uoguelph-mlrg/Cutout/tree/master/shake-shake) folder for usage instructions.\n"
  },
  {
    "path": "model/__init__.py",
    "content": ""
  },
  {
    "path": "model/resnet.py",
    "content": "'''ResNet18/34/50/101/152 in Pytorch.'''\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torch.autograd import Variable\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)\n\n\nclass BasicBlock(nn.Module):\n    expansion = 1\n\n    def __init__(self, in_planes, planes, stride=1):\n        super(BasicBlock, self).__init__()\n        self.conv1 = conv3x3(in_planes, planes, stride)\n        self.bn1 = nn.BatchNorm2d(planes)\n        self.conv2 = conv3x3(planes, planes)\n        self.bn2 = nn.BatchNorm2d(planes)\n\n        self.shortcut = nn.Sequential()\n        if stride != 1 or in_planes != self.expansion*planes:\n            self.shortcut = nn.Sequential(\n                nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False),\n                nn.BatchNorm2d(self.expansion*planes)\n            )\n\n    def forward(self, x):\n        out = F.relu(self.bn1(self.conv1(x)))\n        out = self.bn2(self.conv2(out))\n        out += self.shortcut(x)\n        out = F.relu(out)\n        return out\n\n\nclass Bottleneck(nn.Module):\n    expansion = 4\n\n    def __init__(self, in_planes, planes, stride=1):\n        super(Bottleneck, self).__init__()\n        self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)\n        self.bn1 = nn.BatchNorm2d(planes)\n        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n        self.bn2 = nn.BatchNorm2d(planes)\n        self.conv3 = nn.Conv2d(planes, self.expansion*planes, kernel_size=1, bias=False)\n        self.bn3 = nn.BatchNorm2d(self.expansion*planes)\n\n        self.shortcut = nn.Sequential()\n        if stride != 1 or in_planes != self.expansion*planes:\n            self.shortcut = nn.Sequential(\n                nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False),\n                nn.BatchNorm2d(self.expansion*planes)\n            )\n\n    def forward(self, x):\n        out = F.relu(self.bn1(self.conv1(x)))\n        out = F.relu(self.bn2(self.conv2(out)))\n        out = self.bn3(self.conv3(out))\n        out += self.shortcut(x)\n        out = F.relu(out)\n        return out\n\n\nclass ResNet(nn.Module):\n    def __init__(self, block, num_blocks, num_classes=10):\n        super(ResNet, self).__init__()\n        self.in_planes = 64\n\n        self.conv1 = conv3x3(3,64)\n        self.bn1 = nn.BatchNorm2d(64)\n        self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)\n        self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)\n        self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)\n        self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)\n        self.linear = nn.Linear(512*block.expansion, num_classes)\n\n    def _make_layer(self, block, planes, num_blocks, stride):\n        strides = [stride] + [1]*(num_blocks-1)\n        layers = []\n        for stride in strides:\n            layers.append(block(self.in_planes, planes, stride))\n            self.in_planes = planes * block.expansion\n        return nn.Sequential(*layers)\n\n    def forward(self, x):\n        out = F.relu(self.bn1(self.conv1(x)))\n        out = self.layer1(out)\n        out = self.layer2(out)\n        out = self.layer3(out)\n        out = self.layer4(out)\n        out = F.avg_pool2d(out, 4)\n        out = out.view(out.size(0), -1)\n        out = self.linear(out)\n        return out\n\n\ndef ResNet18(num_classes=10):\n    return ResNet(BasicBlock, [2,2,2,2], num_classes)\n\ndef ResNet34(num_classes=10):\n    return ResNet(BasicBlock, [3,4,6,3], num_classes)\n\ndef ResNet50(num_classes=10):\n    return ResNet(Bottleneck, [3,4,6,3], num_classes)\n\ndef ResNet101(num_classes=10):\n    return ResNet(Bottleneck, [3,4,23,3], num_classes)\n\ndef ResNet152(num_classes=10):\n    return ResNet(Bottleneck, [3,8,36,3], num_classes)\n\ndef test_resnet():\n    net = ResNet50()\n    y = net(Variable(torch.randn(1,3,32,32)))\n    print(y.size())\n\n# test_resnet()"
  },
  {
    "path": "model/wide_resnet.py",
    "content": "# From https://github.com/xternalz/WideResNet-pytorch\n\nimport math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass BasicBlock(nn.Module):\n    def __init__(self, in_planes, out_planes, stride, dropRate=0.0):\n        super(BasicBlock, self).__init__()\n        self.bn1 = nn.BatchNorm2d(in_planes)\n        self.relu1 = nn.ReLU(inplace=True)\n        self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n                               padding=1, bias=False)\n        self.bn2 = nn.BatchNorm2d(out_planes)\n        self.relu2 = nn.ReLU(inplace=True)\n        self.conv2 = nn.Conv2d(out_planes, out_planes, kernel_size=3, stride=1,\n                               padding=1, bias=False)\n        self.droprate = dropRate\n        self.equalInOut = (in_planes == out_planes)\n        self.convShortcut = (not self.equalInOut) and nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride,\n                               padding=0, bias=False) or None\n    def forward(self, x):\n        if not self.equalInOut:\n            x = self.relu1(self.bn1(x))\n        else:\n            out = self.relu1(self.bn1(x))\n        out = self.relu2(self.bn2(self.conv1(out if self.equalInOut else x)))\n        if self.droprate > 0:\n            out = F.dropout(out, p=self.droprate, training=self.training)\n        out = self.conv2(out)\n        return torch.add(x if self.equalInOut else self.convShortcut(x), out)\n\nclass NetworkBlock(nn.Module):\n    def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0):\n        super(NetworkBlock, self).__init__()\n        self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, dropRate)\n    def _make_layer(self, block, in_planes, out_planes, nb_layers, stride, dropRate):\n        layers = []\n        for i in range(nb_layers):\n            layers.append(block(i == 0 and in_planes or out_planes, out_planes, i == 0 and stride or 1, dropRate))\n        return nn.Sequential(*layers)\n    def forward(self, x):\n        return self.layer(x)\n\nclass WideResNet(nn.Module):\n    def __init__(self, depth, num_classes, widen_factor=1, dropRate=0.0):\n        super(WideResNet, self).__init__()\n        nChannels = [16, 16*widen_factor, 32*widen_factor, 64*widen_factor]\n        assert((depth - 4) % 6 == 0)\n        n = (depth - 4) / 6\n        block = BasicBlock\n        # 1st conv before any network block\n        self.conv1 = nn.Conv2d(3, nChannels[0], kernel_size=3, stride=1,\n                               padding=1, bias=False)\n        # 1st block\n        self.block1 = NetworkBlock(n, nChannels[0], nChannels[1], block, 1, dropRate)\n        # 2nd block\n        self.block2 = NetworkBlock(n, nChannels[1], nChannels[2], block, 2, dropRate)\n        # 3rd block\n        self.block3 = NetworkBlock(n, nChannels[2], nChannels[3], block, 2, dropRate)\n        # global average pooling and classifier\n        self.bn1 = nn.BatchNorm2d(nChannels[3])\n        self.relu = nn.ReLU(inplace=True)\n        self.fc = nn.Linear(nChannels[3], num_classes)\n        self.nChannels = nChannels[3]\n\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d):\n                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n                m.weight.data.normal_(0, math.sqrt(2. / n))\n            elif isinstance(m, nn.BatchNorm2d):\n                m.weight.data.fill_(1)\n                m.bias.data.zero_()\n            elif isinstance(m, nn.Linear):\n                m.bias.data.zero_()\n    def forward(self, x):\n        out = self.conv1(x)\n        out = self.block1(out)\n        out = self.block2(out)\n        out = self.block3(out)\n        out = self.relu(self.bn1(out))\n\n        out = F.avg_pool2d(out, 8)\n        out = out.view(-1, self.nChannels)\n        out = self.fc(out)\n        return out\n"
  },
  {
    "path": "shake-shake/README.md",
    "content": "# Cutout in Shake-Shake Regularization Networks\n\nIn order to add cutout to Xavier Gastaldi's shake-shake regularization code we simply add a cutout function to transforms.lua (lines 16 to 29) and then append the cutout function to the CIFAR-10 and CIFAR-100 pre-processing pipelines (lines 49 and 60 in cifar10.lua and cifar100.lua respectively). \n\n## Usage  \n1. Follow Usage instruction 1 from https://github.com/xgastaldi/shake-shake to install fb.resnet.torch and related libraries.\n2. Once installed, navigate to your local fb.resnet.torch/datasets folder.\n3. Copy the files from this folder (shake-shake) and paste them into the datasets folder. This should overwrite cifar10.lua, cifar100.lua, and transforms.lua.\n4. Continue following remaining instructions from https://github.com/xgastaldi/shake-shake. CIFAR-10 should now train using cutout with a length of 16 and CIFAR-100 will train using cutout with a length of 8.\n"
  },
  {
    "path": "shake-shake/cifar10.lua",
    "content": "--\n--  Copyright (c) 2016, Facebook, Inc.\n--  All rights reserved.\n--\n--  This source code is licensed under the BSD-style license found in the\n--  LICENSE file in the root directory of this source tree. An additional grant\n--  of patent rights can be found in the PATENTS file in the same directory.\n--\n--  CIFAR-10 dataset loader\n--\n\nlocal t = require 'datasets/transforms'\n\nlocal M = {}\nlocal CifarDataset = torch.class('resnet.CifarDataset', M)\n\nfunction CifarDataset:__init(imageInfo, opt, split)\n   assert(imageInfo[split], split)\n   self.imageInfo = imageInfo[split]\n   self.split = split\nend\n\nfunction CifarDataset:get(i)\n   local image = self.imageInfo.data[i]:float()\n   local label = self.imageInfo.labels[i]\n\n   return {\n      input = image,\n      target = label,\n   }\nend\n\nfunction CifarDataset:size()\n   return self.imageInfo.data:size(1)\nend\n\n-- Computed from entire CIFAR-10 training set\nlocal meanstd = {\n   mean = {125.3, 123.0, 113.9},\n   std  = {63.0,  62.1,  66.7},\n}\n\nfunction CifarDataset:preprocess()\n   if self.split == 'train' then\n      return t.Compose{\n         t.ColorNormalize(meanstd),\n         t.HorizontalFlip(0.5),\n         t.RandomCrop(32, 4),\n         t.CutOut(8),\n      }\n   elseif self.split == 'val' then\n      return t.ColorNormalize(meanstd)\n   else\n      error('invalid split: ' .. self.split)\n   end\nend\n\nreturn M.CifarDataset\n"
  },
  {
    "path": "shake-shake/cifar100.lua",
    "content": "--\n--  Copyright (c) 2016, Facebook, Inc.\n--  All rights reserved.\n--\n--  This source code is licensed under the BSD-style license found in the\n--  LICENSE file in the root directory of this source tree. An additional grant\n--  of patent rights can be found in the PATENTS file in the same directory.\n--\n\n------------\n-- This file is downloading and transforming CIFAR-100.\n-- It is based on cifar10.lua\n-- Ludovic Trottier\n------------\n\nlocal t = require 'datasets/transforms'\n\nlocal M = {}\nlocal CifarDataset = torch.class('resnet.CifarDataset', M)\n\nfunction CifarDataset:__init(imageInfo, opt, split)\n   assert(imageInfo[split], split)\n   self.imageInfo = imageInfo[split]\n   self.split = split\nend\n\nfunction CifarDataset:get(i)\n   local image = self.imageInfo.data[i]:float()\n   local label = self.imageInfo.labels[i]\n\n   return {\n      input = image,\n      target = label,\n   }\nend\n\nfunction CifarDataset:size()\n   return self.imageInfo.data:size(1)\nend\n\n\n-- Computed from entire CIFAR-100 training set with this code:\n--      dataset = torch.load('cifar100.t7')\n--      tt = dataset.train.data:double();\n--      tt = tt:transpose(2,4);\n--      tt = tt:reshape(50000*32*32, 3);\n--      tt:mean(1)\n--      tt:std(1)\nlocal meanstd = {\n   mean = {129.3, 124.1, 112.4},\n   std  = {68.2,  65.4,  70.4},\n}\n\nfunction CifarDataset:preprocess()\n   if self.split == 'train' then\n      return t.Compose{\n         t.ColorNormalize(meanstd),\n         t.HorizontalFlip(0.5),\n         t.RandomCrop(32, 4),\n         t.CutOut(4),\n      }\n   elseif self.split == 'val' then\n      return t.ColorNormalize(meanstd)\n   else\n      error('invalid split: ' .. self.split)\n   end\nend\n\nreturn M.CifarDataset\n"
  },
  {
    "path": "shake-shake/transforms.lua",
    "content": "--\n--  Copyright (c) 2016, Facebook, Inc.\n--  All rights reserved.\n--\n--  This source code is licensed under the BSD-style license found in the\n--  LICENSE file in the root directory of this source tree. An additional grant\n--  of patent rights can be found in the PATENTS file in the same directory.\n--\n--  Image transforms for data augmentation and input normalization\n--\n\nrequire 'image'\n\nlocal M = {}\n\nfunction M.CutOut(half_length)\n\treturn function(input)\n\t\tlocal w, h = input:size(3), input:size(2)\n\t\tlocal x, y = torch.random(1, w), torch.random(1, h)\n\n\t\tlocal y1 = math.min(math.max(y - half_length, 1), h)\n\t\tlocal y2 = math.min(math.max(y + half_length, 1), h)\n\t\tlocal x1 = math.min(math.max(x - half_length, 1), w)\n\t\tlocal x2 = math.min(math.max(x + half_length, 1), w)\n\n\t\tinput[{ {}, {y1, y2}, {x1, x2} }] = 0.\n\t\treturn input\n\tend\nend\n\nfunction M.Compose(transforms)\n   return function(input)\n      for _, transform in ipairs(transforms) do\n         input = transform(input)\n      end\n      return input\n   end\nend\n\nfunction M.ColorNormalize(meanstd)\n   return function(img)\n      img = img:clone()\n      for i=1,3 do\n         img[i]:add(-meanstd.mean[i])\n         img[i]:div(meanstd.std[i])\n      end\n      return img\n   end\nend\n\n-- Scales the smaller edge to size\nfunction M.Scale(size, interpolation)\n   interpolation = interpolation or 'bicubic'\n   return function(input)\n      local w, h = input:size(3), input:size(2)\n      if (w <= h and w == size) or (h <= w and h == size) then\n         return input\n      end\n      if w < h then\n         return image.scale(input, size, h/w * size, interpolation)\n      else\n         return image.scale(input, w/h * size, size, interpolation)\n      end\n   end\nend\n\n-- Crop to centered rectangle\nfunction M.CenterCrop(size)\n   return function(input)\n      local w1 = math.ceil((input:size(3) - size)/2)\n      local h1 = math.ceil((input:size(2) - size)/2)\n      return image.crop(input, w1, h1, w1 + size, h1 + size) -- center patch\n   end\nend\n\n-- Random crop form larger image with optional zero padding\nfunction M.RandomCrop(size, padding)\n   padding = padding or 0\n\n   return function(input)\n      if padding > 0 then\n         local temp = input.new(3, input:size(2) + 2*padding, input:size(3) + 2*padding)\n         temp:zero()\n            :narrow(2, padding+1, input:size(2))\n            :narrow(3, padding+1, input:size(3))\n            :copy(input)\n         input = temp\n      end\n\n      local w, h = input:size(3), input:size(2)\n      if w == size and h == size then\n         return input\n      end\n\n      local x1, y1 = torch.random(0, w - size), torch.random(0, h - size)\n      local out = image.crop(input, x1, y1, x1 + size, y1 + size)\n      assert(out:size(2) == size and out:size(3) == size, 'wrong crop size')\n      return out\n   end\nend\n\n-- Four corner patches and center crop from image and its horizontal reflection\nfunction M.TenCrop(size)\n   local centerCrop = M.CenterCrop(size)\n\n   return function(input)\n      local w, h = input:size(3), input:size(2)\n\n      local output = {}\n      for _, img in ipairs{input, image.hflip(input)} do\n         table.insert(output, centerCrop(img))\n         table.insert(output, image.crop(img, 0, 0, size, size))\n         table.insert(output, image.crop(img, w-size, 0, w, size))\n         table.insert(output, image.crop(img, 0, h-size, size, h))\n         table.insert(output, image.crop(img, w-size, h-size, w, h))\n      end\n\n      -- View as mini-batch\n      for i, img in ipairs(output) do\n         output[i] = img:view(1, img:size(1), img:size(2), img:size(3))\n      end\n\n      return input.cat(output, 1)\n   end\nend\n\n-- Resized with shorter side randomly sampled from [minSize, maxSize] (ResNet-style)\nfunction M.RandomScale(minSize, maxSize)\n   return function(input)\n      local w, h = input:size(3), input:size(2)\n\n      local targetSz = torch.random(minSize, maxSize)\n      local targetW, targetH = targetSz, targetSz\n      if w < h then\n         targetH = torch.round(h / w * targetW)\n      else\n         targetW = torch.round(w / h * targetH)\n      end\n\n      return image.scale(input, targetW, targetH, 'bicubic')\n   end\nend\n\n-- Random crop with size 8%-100% and aspect ratio 3/4 - 4/3 (Inception-style)\nfunction M.RandomSizedCrop(size)\n   local scale = M.Scale(size)\n   local crop = M.CenterCrop(size)\n\n   return function(input)\n      local attempt = 0\n      repeat\n         local area = input:size(2) * input:size(3)\n         local targetArea = torch.uniform(0.08, 1.0) * area\n\n         local aspectRatio = torch.uniform(3/4, 4/3)\n         local w = torch.round(math.sqrt(targetArea * aspectRatio))\n         local h = torch.round(math.sqrt(targetArea / aspectRatio))\n\n         if torch.uniform() < 0.5 then\n            w, h = h, w\n         end\n\n         if h <= input:size(2) and w <= input:size(3) then\n            local y1 = torch.random(0, input:size(2) - h)\n            local x1 = torch.random(0, input:size(3) - w)\n\n            local out = image.crop(input, x1, y1, x1 + w, y1 + h)\n            assert(out:size(2) == h and out:size(3) == w, 'wrong crop size')\n\n            return image.scale(out, size, size, 'bicubic')\n         end\n         attempt = attempt + 1\n      until attempt >= 10\n\n      -- fallback\n      return crop(scale(input))\n   end\nend\n\nfunction M.HorizontalFlip(prob)\n   return function(input)\n      if torch.uniform() < prob then\n         input = image.hflip(input)\n      end\n      return input\n   end\nend\n\nfunction M.Rotation(deg)\n   return function(input)\n      if deg ~= 0 then\n         input = image.rotate(input, (torch.uniform() - 0.5) * deg * math.pi / 180, 'bilinear')\n      end\n      return input\n   end\nend\n\n-- Lighting noise (AlexNet-style PCA-based noise)\nfunction M.Lighting(alphastd, eigval, eigvec)\n   return function(input)\n      if alphastd == 0 then\n         return input\n      end\n\n      local alpha = torch.Tensor(3):normal(0, alphastd)\n      local rgb = eigvec:clone()\n         :cmul(alpha:view(1, 3):expand(3, 3))\n         :cmul(eigval:view(1, 3):expand(3, 3))\n         :sum(2)\n         :squeeze()\n\n      input = input:clone()\n      for i=1,3 do\n         input[i]:add(rgb[i])\n      end\n      return input\n   end\nend\n\nlocal function blend(img1, img2, alpha)\n   return img1:mul(alpha):add(1 - alpha, img2)\nend\n\nlocal function grayscale(dst, img)\n   dst:resizeAs(img)\n   dst[1]:zero()\n   dst[1]:add(0.299, img[1]):add(0.587, img[2]):add(0.114, img[3])\n   dst[2]:copy(dst[1])\n   dst[3]:copy(dst[1])\n   return dst\nend\n\nfunction M.Saturation(var)\n   local gs\n\n   return function(input)\n      gs = gs or input.new()\n      grayscale(gs, input)\n\n      local alpha = 1.0 + torch.uniform(-var, var)\n      blend(input, gs, alpha)\n      return input\n   end\nend\n\nfunction M.Brightness(var)\n   local gs\n\n   return function(input)\n      gs = gs or input.new()\n      gs:resizeAs(input):zero()\n\n      local alpha = 1.0 + torch.uniform(-var, var)\n      blend(input, gs, alpha)\n      return input\n   end\nend\n\nfunction M.Contrast(var)\n   local gs\n\n   return function(input)\n      gs = gs or input.new()\n      grayscale(gs, input)\n      gs:fill(gs[1]:mean())\n\n      local alpha = 1.0 + torch.uniform(-var, var)\n      blend(input, gs, alpha)\n      return input\n   end\nend\n\nfunction M.RandomOrder(ts)\n   return function(input)\n      local img = input.img or input\n      local order = torch.randperm(#ts)\n      for i=1,#ts do\n         img = ts[order[i]](img)\n      end\n      return img\n   end\nend\n\nfunction M.ColorJitter(opt)\n   local brightness = opt.brightness or 0\n   local contrast = opt.contrast or 0\n   local saturation = opt.saturation or 0\n\n   local ts = {}\n   if brightness ~= 0 then\n      table.insert(ts, M.Brightness(brightness))\n   end\n   if contrast ~= 0 then\n      table.insert(ts, M.Contrast(contrast))\n   end\n   if saturation ~= 0 then\n      table.insert(ts, M.Saturation(saturation))\n   end\n\n   if #ts == 0 then\n      return function(input) return input end\n   end\n\n   return M.RandomOrder(ts)\nend\n\nreturn M\n"
  },
  {
    "path": "train.py",
    "content": "# run train.py --dataset cifar10 --model resnet18 --data_augmentation --cutout --length 16\n# run train.py --dataset cifar100 --model resnet18 --data_augmentation --cutout --length 8\n# run train.py --dataset svhn --model wideresnet --learning_rate 0.01 --epochs 160 --cutout --length 20\n\nimport pdb\nimport argparse\nimport numpy as np\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.backends.cudnn as cudnn\nfrom torch.optim.lr_scheduler import MultiStepLR\n\nfrom torchvision.utils import make_grid\nfrom torchvision import datasets, transforms\n\nfrom util.misc import CSVLogger\nfrom util.cutout import Cutout\n\nfrom model.resnet import ResNet18\nfrom model.wide_resnet import WideResNet\n\nmodel_options = ['resnet18', 'wideresnet']\ndataset_options = ['cifar10', 'cifar100', 'svhn']\n\nparser = argparse.ArgumentParser(description='CNN')\nparser.add_argument('--dataset', '-d', default='cifar10',\n                    choices=dataset_options)\nparser.add_argument('--model', '-a', default='resnet18',\n                    choices=model_options)\nparser.add_argument('--batch_size', type=int, default=128,\n                    help='input batch size for training (default: 128)')\nparser.add_argument('--epochs', type=int, default=200,\n                    help='number of epochs to train (default: 20)')\nparser.add_argument('--learning_rate', type=float, default=0.1,\n                    help='learning rate')\nparser.add_argument('--data_augmentation', action='store_true', default=False,\n                    help='augment data by flipping and cropping')\nparser.add_argument('--cutout', action='store_true', default=False,\n                    help='apply cutout')\nparser.add_argument('--n_holes', type=int, default=1,\n                    help='number of holes to cut out from image')\nparser.add_argument('--length', type=int, default=16,\n                    help='length of the holes')\nparser.add_argument('--no-cuda', action='store_true', default=False,\n                    help='enables CUDA training')\nparser.add_argument('--seed', type=int, default=0,\n                    help='random seed (default: 1)')\n\nargs = parser.parse_args()\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\ncudnn.benchmark = True  # Should make training should go faster for large models\n\ntorch.manual_seed(args.seed)\nif args.cuda:\n    torch.cuda.manual_seed(args.seed)\n\ntest_id = args.dataset + '_' + args.model\n\nprint(args)\n\n# Image Preprocessing\nif args.dataset == 'svhn':\n    normalize = transforms.Normalize(mean=[x / 255.0 for x in[109.9, 109.7, 113.8]],\n                                     std=[x / 255.0 for x in [50.1, 50.6, 50.8]])\nelse:\n    normalize = transforms.Normalize(mean=[x / 255.0 for x in [125.3, 123.0, 113.9]],\n                                     std=[x / 255.0 for x in [63.0, 62.1, 66.7]])\n\ntrain_transform = transforms.Compose([])\nif args.data_augmentation:\n    train_transform.transforms.append(transforms.RandomCrop(32, padding=4))\n    train_transform.transforms.append(transforms.RandomHorizontalFlip())\ntrain_transform.transforms.append(transforms.ToTensor())\ntrain_transform.transforms.append(normalize)\nif args.cutout:\n    train_transform.transforms.append(Cutout(n_holes=args.n_holes, length=args.length))\n\n\ntest_transform = transforms.Compose([\n    transforms.ToTensor(),\n    normalize])\n\nif args.dataset == 'cifar10':\n    num_classes = 10\n    train_dataset = datasets.CIFAR10(root='data/',\n                                     train=True,\n                                     transform=train_transform,\n                                     download=True)\n\n    test_dataset = datasets.CIFAR10(root='data/',\n                                    train=False,\n                                    transform=test_transform,\n                                    download=True)\nelif args.dataset == 'cifar100':\n    num_classes = 100\n    train_dataset = datasets.CIFAR100(root='data/',\n                                      train=True,\n                                      transform=train_transform,\n                                      download=True)\n\n    test_dataset = datasets.CIFAR100(root='data/',\n                                     train=False,\n                                     transform=test_transform,\n                                     download=True)\nelif args.dataset == 'svhn':\n    num_classes = 10\n    train_dataset = datasets.SVHN(root='data/',\n                                  split='train',\n                                  transform=train_transform,\n                                  download=True)\n\n    extra_dataset = datasets.SVHN(root='data/',\n                                  split='extra',\n                                  transform=train_transform,\n                                  download=True)\n\n    # Combine both training splits (https://arxiv.org/pdf/1605.07146.pdf)\n    data = np.concatenate([train_dataset.data, extra_dataset.data], axis=0)\n    labels = np.concatenate([train_dataset.labels, extra_dataset.labels], axis=0)\n    train_dataset.data = data\n    train_dataset.labels = labels\n\n    test_dataset = datasets.SVHN(root='data/',\n                                 split='test',\n                                 transform=test_transform,\n                                 download=True)\n\n# Data Loader (Input Pipeline)\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n                                           batch_size=args.batch_size,\n                                           shuffle=True,\n                                           pin_memory=True,\n                                           num_workers=2)\n\ntest_loader = torch.utils.data.DataLoader(dataset=test_dataset,\n                                          batch_size=args.batch_size,\n                                          shuffle=False,\n                                          pin_memory=True,\n                                          num_workers=2)\n\nif args.model == 'resnet18':\n    cnn = ResNet18(num_classes=num_classes)\nelif args.model == 'wideresnet':\n    if args.dataset == 'svhn':\n        cnn = WideResNet(depth=16, num_classes=num_classes, widen_factor=8,\n                         dropRate=0.4)\n    else:\n        cnn = WideResNet(depth=28, num_classes=num_classes, widen_factor=10,\n                         dropRate=0.3)\n\ncnn = cnn.cuda()\ncriterion = nn.CrossEntropyLoss().cuda()\ncnn_optimizer = torch.optim.SGD(cnn.parameters(), lr=args.learning_rate,\n                                momentum=0.9, nesterov=True, weight_decay=5e-4)\n\nif args.dataset == 'svhn':\n    scheduler = MultiStepLR(cnn_optimizer, milestones=[80, 120], gamma=0.1)\nelse:\n    scheduler = MultiStepLR(cnn_optimizer, milestones=[60, 120, 160], gamma=0.2)\n\nfilename = 'logs/' + test_id + '.csv'\ncsv_logger = CSVLogger(args=args, fieldnames=['epoch', 'train_acc', 'test_acc'], filename=filename)\n\n\ndef test(loader):\n    cnn.eval()    # Change model to 'eval' mode (BN uses moving mean/var).\n    correct = 0.\n    total = 0.\n    for images, labels in loader:\n        images = images.cuda()\n        labels = labels.cuda()\n\n        with torch.no_grad():\n            pred = cnn(images)\n\n        pred = torch.max(pred.data, 1)[1]\n        total += labels.size(0)\n        correct += (pred == labels).sum().item()\n\n    val_acc = correct / total\n    cnn.train()\n    return val_acc\n\n\nfor epoch in range(args.epochs):\n\n    xentropy_loss_avg = 0.\n    correct = 0.\n    total = 0.\n\n    progress_bar = tqdm(train_loader)\n    for i, (images, labels) in enumerate(progress_bar):\n        progress_bar.set_description('Epoch ' + str(epoch))\n\n        images = images.cuda()\n        labels = labels.cuda()\n\n        cnn.zero_grad()\n        pred = cnn(images)\n\n        xentropy_loss = criterion(pred, labels)\n        xentropy_loss.backward()\n        cnn_optimizer.step()\n\n        xentropy_loss_avg += xentropy_loss.item()\n\n        # Calculate running average of accuracy\n        pred = torch.max(pred.data, 1)[1]\n        total += labels.size(0)\n        correct += (pred == labels.data).sum().item()\n        accuracy = correct / total\n\n        progress_bar.set_postfix(\n            xentropy='%.3f' % (xentropy_loss_avg / (i + 1)),\n            acc='%.3f' % accuracy)\n\n    test_acc = test(test_loader)\n    tqdm.write('test_acc: %.3f' % (test_acc))\n\n    scheduler.step(epoch)  # Use this line for PyTorch <1.4\n    # scheduler.step()     # Use this line for PyTorch >=1.4\n\n    row = {'epoch': str(epoch), 'train_acc': str(accuracy), 'test_acc': str(test_acc)}\n    csv_logger.writerow(row)\n\ntorch.save(cnn.state_dict(), 'checkpoints/' + test_id + '.pt')\ncsv_logger.close()\n"
  },
  {
    "path": "util/__init__.py",
    "content": ""
  },
  {
    "path": "util/cutout.py",
    "content": "import torch\nimport numpy as np\n\n\nclass Cutout(object):\n    \"\"\"Randomly mask out one or more patches from an image.\n\n    Args:\n        n_holes (int): Number of patches to cut out of each image.\n        length (int): The length (in pixels) of each square patch.\n    \"\"\"\n    def __init__(self, n_holes, length):\n        self.n_holes = n_holes\n        self.length = length\n\n    def __call__(self, img):\n        \"\"\"\n        Args:\n            img (Tensor): Tensor image of size (C, H, W).\n        Returns:\n            Tensor: Image with n_holes of dimension length x length cut out of it.\n        \"\"\"\n        h = img.size(1)\n        w = img.size(2)\n\n        mask = np.ones((h, w), np.float32)\n\n        for n in range(self.n_holes):\n            y = np.random.randint(h)\n            x = np.random.randint(w)\n\n            y1 = np.clip(y - self.length // 2, 0, h)\n            y2 = np.clip(y + self.length // 2, 0, h)\n            x1 = np.clip(x - self.length // 2, 0, w)\n            x2 = np.clip(x + self.length // 2, 0, w)\n\n            mask[y1: y2, x1: x2] = 0.\n\n        mask = torch.from_numpy(mask)\n        mask = mask.expand_as(img)\n        img = img * mask\n\n        return img\n"
  },
  {
    "path": "util/misc.py",
    "content": "import csv\n\n\nclass CSVLogger():\n    def __init__(self, args, fieldnames, filename='log.csv'):\n\n        self.filename = filename\n        self.csv_file = open(filename, 'w')\n\n        # Write model configuration at top of csv\n        writer = csv.writer(self.csv_file)\n        for arg in vars(args):\n            writer.writerow([arg, getattr(args, arg)])\n        writer.writerow([''])\n\n        self.writer = csv.DictWriter(self.csv_file, fieldnames=fieldnames)\n        self.writer.writeheader()\n\n        self.csv_file.flush()\n\n    def writerow(self, row):\n        self.writer.writerow(row)\n        self.csv_file.flush()\n\n    def close(self):\n        self.csv_file.close()\n"
  }
]