├── model
├── __init__.py
├── MaxDropout.py
├── wide_resnet.py
└── resnet.py
├── util
├── __init__.py
├── misc.py
└── cutout.py
├── .gitignore
├── images
├── droped.png
├── maxdroped.png
└── original.png
├── README.md
├── train.py
└── LICENSE.md
/model/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/util/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | checkpoints/
3 | logs/
4 | data/
--------------------------------------------------------------------------------
/images/droped.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cfsantos/MaxDropout-torch/HEAD/images/droped.png
--------------------------------------------------------------------------------
/images/maxdroped.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cfsantos/MaxDropout-torch/HEAD/images/maxdroped.png
--------------------------------------------------------------------------------
/images/original.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cfsantos/MaxDropout-torch/HEAD/images/original.png
--------------------------------------------------------------------------------
/util/misc.py:
--------------------------------------------------------------------------------
1 | import csv
2 |
3 |
4 | class CSVLogger():
5 | def __init__(self, args, fieldnames, filename='log.csv'):
6 |
7 | self.filename = filename
8 | self.csv_file = open(filename, 'w')
9 |
10 | # Write model configuration at top of csv
11 | writer = csv.writer(self.csv_file)
12 | for arg in vars(args):
13 | writer.writerow([arg, getattr(args, arg)])
14 | writer.writerow([''])
15 |
16 | self.writer = csv.DictWriter(self.csv_file, fieldnames=fieldnames)
17 | self.writer.writeheader()
18 |
19 | self.csv_file.flush()
20 |
21 | def writerow(self, row):
22 | self.writer.writerow(row)
23 | self.csv_file.flush()
24 |
25 | def close(self):
26 | self.csv_file.close()
27 |
--------------------------------------------------------------------------------
/util/cutout.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import numpy as np
3 |
4 |
5 | class Cutout(object):
6 | """Randomly mask out one or more patches from an image.
7 |
8 | Args:
9 | n_holes (int): Number of patches to cut out of each image.
10 | length (int): The length (in pixels) of each square patch.
11 | """
12 | def __init__(self, n_holes, length):
13 | self.n_holes = n_holes
14 | self.length = length
15 |
16 | def __call__(self, img):
17 | """
18 | Args:
19 | img (Tensor): Tensor image of size (C, H, W).
20 | Returns:
21 | Tensor: Image with n_holes of dimension length x length cut out of it.
22 | """
23 | h = img.size(1)
24 | w = img.size(2)
25 |
26 | mask = np.ones((h, w), np.float32)
27 |
28 | for n in range(self.n_holes):
29 | y = np.random.randint(h)
30 | x = np.random.randint(w)
31 |
32 | y1 = np.clip(y - self.length // 2, 0, h)
33 | y2 = np.clip(y + self.length // 2, 0, h)
34 | x1 = np.clip(x - self.length // 2, 0, w)
35 | x2 = np.clip(x + self.length // 2, 0, w)
36 |
37 | mask[y1: y2, x1: x2] = 0.
38 |
39 | mask = torch.from_numpy(mask)
40 | mask = mask.expand_as(img)
41 | img = img * mask
42 |
43 | return img
44 |
--------------------------------------------------------------------------------
/model/MaxDropout.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch
4 | import torch.nn as nn
5 | import torch.utils.data as data_utils
6 | import numpy as np
7 | import matplotlib.pyplot as plt
8 | import torch.nn.functional as F
9 | from torch import autograd
10 |
11 | class MaxDropout(nn.Module):
12 | def __init__(self, drop=0.3):
13 | # print(p)
14 | super(MaxDropout, self).__init__()
15 | if drop < 0 or drop > 1:
16 | raise ValueError("dropout probability has to be between 0 and 1, "
17 | "but got {}".format(p))
18 | self.drop = 1 - drop
19 |
20 | def forward(self, x):
21 | if not self.training:
22 | return x
23 |
24 | up = x - x.min()
25 | divisor = (x.max() - x.min())
26 | x_copy = torch.div(up,divisor)
27 | if x.is_cuda:
28 | x_copy = x_copy.cuda()
29 |
30 | mask = (x_copy > (self.drop))
31 | x = x.masked_fill(mask > 0.5, 0)
32 | return x
33 |
34 |
35 | class AlphaDropout(nn.Module):
36 | # Custom implementation of alpha dropout. Note that an equivalent
37 | # implementation exists in pytorch as nn.AlphaDropout
38 | def __init__(self, dropout=0.1, lambd=1.0507, alpha=1.67326):
39 | super().__init__()
40 | self.lambd = lambd
41 | self.alpha = alpha
42 | self.aprime = -lambd * alpha
43 |
44 | self.q = 1 - dropout
45 | self.p = dropout
46 |
47 | self.a = (self.q + self.aprime**2 * self.q * self.p)**(-0.5)
48 | self.b = -self.a * (self.p * self.aprime)
49 |
50 | def forward(self, x):
51 | if not self.training:
52 | return x
53 | ones = torch.ones(x.size())
54 | x_copy = (x - x.min()) / (x.max() - x.min()).detach().clone()
55 | if x.is_cuda:
56 | ones = ones.cuda()
57 | x_copy = x_copy.cuda()
58 | mask = (x_copy > (self.q))
59 | x = x.masked_fill(autograd.Variable(mask.bool()), 0)
60 | return x
61 |
62 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # MaxDropout
2 |
3 | This repository contains the code for the paper [MaxDropout: Deep Neural Network RegularizationBased on Maximum Output Values](https://arxiv.org/abs/2007.13723).
4 |
5 | Code based on the [Cutout original repository](https://github.com/uoguelph-mlrg/Cutout)
6 |
7 | ## Introduction
8 |
9 | MaxDropout is a regularization technique based on Dropout. While dropout removes random neurons from a given tensor, MaxDropout relies on the highest values of this tensor, changing the values according to this rule.
10 |
11 | | Original Image | Dropout(50%) | MaxDropout(50%) |
12 | :-------------------------:|:-------------:|:-------------------:|
13 |
|
|
|
14 |
15 |
16 |
17 | Bibtex:
18 | ```
19 | @misc{santos2020maxdropout,
20 | title={MaxDropout: Deep Neural Network Regularization Based on Maximum Output Values},
21 | author={Claudio Filipi Goncalves do Santos and Danilo Colombo and Mateus Roder and João Paulo Papa},
22 | year={2020},
23 | eprint={2007.13723},
24 | archivePrefix={arXiv},
25 | primaryClass={cs.LG}
26 | }
27 | ```
28 |
29 | ## Results and Usage
30 | ### Dependencies
31 | [PyTorch v0.4.0](http://pytorch.org/)
32 | [tqdm](https://pypi.python.org/pypi/tqdm)
33 |
34 | ### ResNet18
35 | Test error (%, flip/translation augmentation, mean/std normalization, mean of 5 runs)
36 |
37 | | **Network** | **CIFAR-10** | **CIFAR-100** |
38 | | ----------- | ------------ | ------------- |
39 | | ResNet18 | 4.72 | 22.46 |
40 | | ResNet18 + cutout | 3.99 | 21.96 |
41 | | ResNet18 + MaxDropout | 4.66 | 21.93 |
42 | | ResNet18 + cutout + MaxDropout | **3.76** | **21.82** |
43 |
44 |
45 | To train ResNet18 on CIFAR10 with data augmentation and MaxDropout:
46 | `python train.py --dataset cifar10 --model resnet18 --data_augmentation `
47 |
48 | To train ResNet18 on CIFAR100 with data augmentation and MaxDropout:
49 | `python train.py --dataset cifar100 --model resnet18 --data_augmentation `
50 |
51 | To train ResNet18 on CIFAR10 with data augmentation, cutout and MaxDropout:
52 | `python train.py --dataset cifar10 --model resnet18 --data_augmentation --cutout --length 16`
53 |
54 | To train ResNet18 on CIFAR100 with data augmentation, cutout and MaxDropout:
55 | `python train.py --dataset cifar100 --model resnet18 --data_augmentation --cutout --length 8`
56 | ### WideResNet
57 | WideResNet model implementation from https://github.com/xternalz/WideResNet-pytorch
58 |
59 | Test error (%, flip/translation augmentation, mean/std normalization, mean of 5 runs)
60 |
61 | | **Network** | **CIFAR-10** | **CIFAR-100** |
62 | | ----------- | ------------ | ------------- |
63 | | WideResNet | 4.00 | 19.25 |
64 | | WideResNet + Dropout | 3.89 | 18.89 |
65 | | WideResNet + MaxDropout | **3.84** | **18.81** |
66 |
67 | To train WideResNet 28-10 on CIFAR10 with data augmentation and MaxDropout:
68 | `python train.py --dataset cifar10 --model wideresnet --data_augmentation `
69 |
70 | To train WideResNet 28-10 on CIFAR100 with data augmentation and MaxDropout:
71 | `python train.py --dataset cifar100 --model wideresnet --data_augmentation `
72 |
73 |
74 |
75 |
--------------------------------------------------------------------------------
/model/wide_resnet.py:
--------------------------------------------------------------------------------
1 | # From https://github.com/xternalz/WideResNet-pytorch
2 |
3 | import math
4 | import torch
5 | import torch.nn as nn
6 | import torch.nn.functional as F
7 |
8 | from model.MaxDropout import MaxDropout
9 |
10 | class BasicBlock(nn.Module):
11 | def __init__(self, in_planes, out_planes, stride, dropRate=0.3):
12 | super(BasicBlock, self).__init__()
13 | self.bn1 = nn.BatchNorm2d(in_planes)
14 | self.relu1 = nn.ReLU(inplace=True)
15 | self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
16 | padding=1, bias=False)
17 | self.bn2 = nn.BatchNorm2d(out_planes)
18 | self.relu2 = nn.ReLU(inplace=True)
19 | self.conv2 = nn.Conv2d(out_planes, out_planes, kernel_size=3, stride=1,
20 | padding=1, bias=False)
21 | self.droprate = dropRate
22 | self.equalInOut = (in_planes == out_planes)
23 | self.convShortcut = (not self.equalInOut) and nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride,
24 | padding=0, bias=False) or None
25 | def forward(self, x):
26 | if not self.equalInOut:
27 | x = self.relu1(self.bn1(x))
28 | else:
29 | out = self.relu1(self.bn1(x))
30 | out = self.relu2(self.bn2(self.conv1(out if self.equalInOut else x)))
31 | if self.droprate > 0:
32 | out = MaxDropout(drop=self.droprate).forward(out)
33 | out = self.conv2(out)
34 | return torch.add(x if self.equalInOut else self.convShortcut(x), out)
35 |
36 | class NetworkBlock(nn.Module):
37 | def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0):
38 | super(NetworkBlock, self).__init__()
39 | self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, dropRate)
40 | def _make_layer(self, block, in_planes, out_planes, nb_layers, stride, dropRate):
41 | layers = []
42 | for i in range(int(nb_layers)):
43 | layers.append(block(i == 0 and in_planes or out_planes, out_planes, i == 0 and stride or 1, dropRate))
44 | return nn.Sequential(*layers)
45 | def forward(self, x):
46 | return self.layer(x)
47 |
48 | class WideResNet(nn.Module):
49 | def __init__(self, depth, num_classes, widen_factor=1, dropRate=0.0):
50 | super(WideResNet, self).__init__()
51 | nChannels = [16, 16*widen_factor, 32*widen_factor, 64*widen_factor]
52 | assert((depth - 4) % 6 == 0)
53 | n = (depth - 4) / 6
54 | block = BasicBlock
55 | # 1st conv before any network block
56 | self.conv1 = nn.Conv2d(3, nChannels[0], kernel_size=3, stride=1,
57 | padding=1, bias=False)
58 | # 1st block
59 | self.block1 = NetworkBlock(n, nChannels[0], nChannels[1], block, 1, dropRate)
60 | # 2nd block
61 | self.block2 = NetworkBlock(n, nChannels[1], nChannels[2], block, 2, dropRate)
62 | # 3rd block
63 | self.block3 = NetworkBlock(n, nChannels[2], nChannels[3], block, 2, dropRate)
64 | # global average pooling and classifier
65 | self.bn1 = nn.BatchNorm2d(nChannels[3])
66 | self.relu = nn.ReLU(inplace=True)
67 | self.fc = nn.Linear(nChannels[3], num_classes)
68 | self.nChannels = nChannels[3]
69 |
70 | for m in self.modules():
71 | if isinstance(m, nn.Conv2d):
72 | n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
73 | m.weight.data.normal_(0, math.sqrt(2. / n))
74 | elif isinstance(m, nn.BatchNorm2d):
75 | m.weight.data.fill_(1)
76 | m.bias.data.zero_()
77 | elif isinstance(m, nn.Linear):
78 | m.bias.data.zero_()
79 | def forward(self, x):
80 | out = self.conv1(x)
81 | out = self.block1(out)
82 | out = self.block2(out)
83 | out = self.block3(out)
84 | out = self.relu(self.bn1(out))
85 |
86 | out = F.avg_pool2d(out, 8)
87 | out = out.view(-1, self.nChannels)
88 | out = self.fc(out)
89 | return out
90 |
--------------------------------------------------------------------------------
/model/resnet.py:
--------------------------------------------------------------------------------
1 | '''ResNet18/34/50/101/152 in Pytorch.'''
2 | import torch
3 | import torch.nn as nn
4 | import torch.nn.functional as F
5 |
6 | from torch.autograd import Variable
7 | from model.MaxDropout import MaxDropout
8 |
9 | def conv3x3(in_planes, out_planes, stride=1):
10 | return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
11 |
12 |
13 | class BasicBlock(nn.Module):
14 | expansion = 1
15 |
16 | def __init__(self, in_planes, planes, stride=1):
17 | super(BasicBlock, self).__init__()
18 | self.conv1 = conv3x3(in_planes, planes, stride)
19 | self.bn1 = nn.BatchNorm2d(planes)
20 | self.conv2 = conv3x3(planes, planes)
21 | self.bn2 = nn.BatchNorm2d(planes)
22 |
23 | self.shortcut = nn.Sequential()
24 | if stride != 1 or in_planes != self.expansion*planes:
25 | self.shortcut = nn.Sequential(
26 | nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False),
27 | nn.BatchNorm2d(self.expansion*planes)
28 | )
29 |
30 | def forward(self, x):
31 | out = F.relu(self.bn1(self.conv1(x)))
32 | out = self.bn2(self.conv2(out))
33 | out += self.shortcut(x)
34 | out = F.relu(out)
35 | return out
36 |
37 |
38 | class Bottleneck(nn.Module):
39 | expansion = 4
40 |
41 | def __init__(self, in_planes, planes, stride=1):
42 | super(Bottleneck, self).__init__()
43 | self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
44 | self.bn1 = nn.BatchNorm2d(planes)
45 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
46 | self.bn2 = nn.BatchNorm2d(planes)
47 | self.conv3 = nn.Conv2d(planes, self.expansion*planes, kernel_size=1, bias=False)
48 | self.bn3 = nn.BatchNorm2d(self.expansion*planes)
49 |
50 | self.shortcut = nn.Sequential()
51 | if stride != 1 or in_planes != self.expansion*planes:
52 | self.shortcut = nn.Sequential(
53 | nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False),
54 | nn.BatchNorm2d(self.expansion*planes)
55 | )
56 |
57 | def forward(self, x):
58 | out = F.relu(self.bn1(self.conv1(x)))
59 | out = F.relu(self.bn2(self.conv2(out)))
60 | out = self.bn3(self.conv3(out))
61 | out += self.shortcut(x)
62 | out = F.relu(out)
63 | return out
64 |
65 |
66 | class ResNet(nn.Module):
67 | def __init__(self, block, num_blocks,drop=0.3, num_classes=10):
68 | super(ResNet, self).__init__()
69 | self.in_planes = 64
70 | self.drop = drop
71 | self.conv1 = conv3x3(3,64)
72 | self.bn1 = nn.BatchNorm2d(64)
73 | self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)
74 | self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)
75 | self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)
76 | self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)
77 | self.linear = nn.Linear(512*block.expansion, num_classes)
78 |
79 | def _make_layer(self, block, planes, num_blocks, stride):
80 | strides = [stride] + [1]*(num_blocks-1)
81 | layers = []
82 | for stride in strides:
83 | layers.append(block(self.in_planes, planes, stride))
84 | self.in_planes = planes * block.expansion
85 | return nn.Sequential(*layers)
86 |
87 | def forward(self, x):
88 | out = F.relu(self.bn1(self.conv1(x)))
89 | out = self.layer1(out)
90 | out = MaxDropout(drop=self.drop).forward(out)
91 |
92 | out = self.layer2(out)
93 | out = MaxDropout(drop=self.drop).forward(out)
94 |
95 | out = self.layer3(out)
96 | out = MaxDropout(drop=self.drop).forward(out)
97 | out = self.layer4(out)
98 | out = MaxDropout(drop=self.drop).forward(out)
99 | out = F.avg_pool2d(out, 4)
100 | out = out.view(out.size(0), -1)
101 | out = self.linear(out)
102 | return out
103 |
104 |
105 | def ResNet18(drop, num_classes=10):
106 | return ResNet(BasicBlock, [2,2,2,2],drop, num_classes)
107 |
108 |
--------------------------------------------------------------------------------
/train.py:
--------------------------------------------------------------------------------
1 | # run train.py --dataset cifar10 --model resnet18 --data_augmentation --cutout --length 16
2 | # run train.py --dataset cifar100 --model resnet18 --data_augmentation --cutout --length 8
3 | # run train.py --dataset svhn --model wideresnet --learning_rate 0.01 --epochs 160 --cutout --length 20
4 | import os
5 | os.environ["CUDA_VISIBLE_DEVICES"]="1"
6 |
7 | import pdb
8 | import argparse
9 | import numpy as np
10 | from tqdm import tqdm
11 |
12 | import torch
13 | import torch.nn as nn
14 | from torch.autograd import Variable
15 | import torch.backends.cudnn as cudnn
16 | from torch.optim.lr_scheduler import MultiStepLR
17 |
18 | from torchvision.utils import make_grid
19 | from torchvision import datasets, transforms
20 |
21 | from util.misc import CSVLogger
22 | from util.cutout import Cutout
23 |
24 | from model.resnet import ResNet18
25 | from model.wide_resnet import WideResNet
26 |
27 | model_options = ['resnet18', 'wideresnet']
28 | dataset_options = ['cifar10', 'cifar100', 'svhn']
29 |
30 | parser = argparse.ArgumentParser(description='CNN')
31 | parser.add_argument('--dataset', '-d', default='cifar10',
32 | choices=dataset_options)
33 | parser.add_argument('--model', '-a', default='resnet18',
34 | choices=model_options)
35 | parser.add_argument('--batch_size', type=int, default=128,
36 | help='input batch size for training (default: 128)')
37 | parser.add_argument('--epochs', type=int, default=200,
38 | help='number of epochs to train (default: 20)')
39 | parser.add_argument('--learning_rate', type=float, default=0.1,
40 | help='learning rate')
41 | parser.add_argument('--data_augmentation', action='store_true', default=False,
42 | help='augment data by flipping and cropping')
43 | parser.add_argument('--cutout', action='store_true', default=False,
44 | help='apply cutout')
45 | parser.add_argument('--n_holes', type=int, default=1,
46 | help='number of holes to cut out from image')
47 | parser.add_argument('--length', type=int, default=16,
48 | help='length of the holes')
49 | parser.add_argument('--no-cuda', action='store_true', default=False,
50 | help='enables CUDA training')
51 | parser.add_argument('--seed', type=int, default=0,
52 | help='random seed (default: 1)')
53 | parser.add_argument('--run', type=int, default=0,
54 | help='running time (default: 0')
55 | parser.add_argument('--drop', type=float, default=0.3,
56 | help='drop rate on maxdropout (default: 0.3')
57 |
58 | args = parser.parse_args()
59 | args.cuda = not args.no_cuda and torch.cuda.is_available()
60 | cudnn.benchmark = True # Should make training should go faster for large models
61 |
62 | torch.manual_seed(args.seed)
63 | if args.cuda:
64 | torch.cuda.manual_seed(args.seed)
65 |
66 | test_id = args.dataset + '_' + args.model +'_dataaug_'+str(args.data_augmentation) +'_'+str(args.run)+'_drop_'+str(args.drop)
67 |
68 | print(args)
69 |
70 | # Image Preprocessing
71 | if args.dataset == 'svhn':
72 | normalize = transforms.Normalize(mean=[x / 255.0 for x in[109.9, 109.7, 113.8]],
73 | std=[x / 255.0 for x in [50.1, 50.6, 50.8]])
74 | else:
75 | normalize = transforms.Normalize(mean=[x / 255.0 for x in [125.3, 123.0, 113.9]],
76 | std=[x / 255.0 for x in [63.0, 62.1, 66.7]])
77 |
78 | train_transform = transforms.Compose([])
79 | if args.data_augmentation:
80 | train_transform.transforms.append(transforms.RandomCrop(32, padding=4))
81 | train_transform.transforms.append(transforms.RandomHorizontalFlip())
82 | train_transform.transforms.append(transforms.ToTensor())
83 | train_transform.transforms.append(normalize)
84 | if args.cutout:
85 | train_transform.transforms.append(Cutout(n_holes=args.n_holes, length=args.length))
86 |
87 |
88 | test_transform = transforms.Compose([
89 | transforms.ToTensor(),
90 | normalize])
91 |
92 | if args.dataset == 'cifar10':
93 | num_classes = 10
94 | train_dataset = datasets.CIFAR10(root='data/',
95 | train=True,
96 | transform=train_transform,
97 | download=True)
98 |
99 | test_dataset = datasets.CIFAR10(root='data/',
100 | train=False,
101 | transform=test_transform,
102 | download=True)
103 | elif args.dataset == 'cifar100':
104 | num_classes = 100
105 | train_dataset = datasets.CIFAR100(root='data/',
106 | train=True,
107 | transform=train_transform,
108 | download=True)
109 |
110 | test_dataset = datasets.CIFAR100(root='data/',
111 | train=False,
112 | transform=test_transform,
113 | download=True)
114 | elif args.dataset == 'svhn':
115 | num_classes = 10
116 | train_dataset = datasets.SVHN(root='data/',
117 | split='train',
118 | transform=train_transform,
119 | download=True)
120 |
121 | extra_dataset = datasets.SVHN(root='data/',
122 | split='extra',
123 | transform=train_transform,
124 | download=True)
125 |
126 | # Combine both training splits (https://arxiv.org/pdf/1605.07146.pdf)
127 | data = np.concatenate([train_dataset.data, extra_dataset.data], axis=0)
128 | labels = np.concatenate([train_dataset.labels, extra_dataset.labels], axis=0)
129 | train_dataset.data = data
130 | train_dataset.labels = labels
131 |
132 | test_dataset = datasets.SVHN(root='data/',
133 | split='test',
134 | transform=test_transform,
135 | download=True)
136 |
137 | # Data Loader (Input Pipeline)
138 | train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
139 | batch_size=args.batch_size,
140 | shuffle=True,
141 | pin_memory=True,
142 | num_workers=2)
143 |
144 | test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
145 | batch_size=args.batch_size,
146 | shuffle=False,
147 | pin_memory=True,
148 | num_workers=2)
149 |
150 | if args.model == 'resnet18':
151 | cnn = ResNet18(num_classes=num_classes, drop=args.drop)
152 | elif args.model == 'wideresnet':
153 | if args.dataset == 'svhn':
154 | cnn = WideResNet(depth=16, num_classes=num_classes, widen_factor=4,
155 | dropRate=args.drop)
156 | else:
157 | cnn = WideResNet(depth=28, num_classes=num_classes, widen_factor=10,
158 | dropRate=args.drop)
159 |
160 | cnn = cnn.cuda()
161 | criterion = nn.CrossEntropyLoss().cuda()
162 | cnn_optimizer = torch.optim.SGD(cnn.parameters(), lr=args.learning_rate,
163 | momentum=0.9, nesterov=True, weight_decay=5e-4)
164 |
165 | if args.dataset == 'svhn':
166 | scheduler = MultiStepLR(cnn_optimizer, milestones=[80, 120], gamma=0.1)
167 | else:
168 | scheduler = MultiStepLR(cnn_optimizer, milestones=[60, 120, 160], gamma=0.2)
169 |
170 | filename = 'logs/' + test_id + '.csv'
171 | csv_logger = CSVLogger(args=args, fieldnames=['epoch', 'train_acc', 'test_acc'], filename=filename)
172 |
173 |
174 | def test(loader):
175 | cnn.eval() # Change model to 'eval' mode (BN uses moving mean/var).
176 | correct = 0.
177 | total = 0.
178 | for images, labels in loader:
179 | images = images.cuda()
180 | labels = labels.cuda()
181 |
182 | with torch.no_grad():
183 | pred = cnn(images)
184 |
185 | pred = torch.max(pred.data, 1)[1]
186 | total += labels.size(0)
187 | correct += (pred == labels).sum().item()
188 |
189 | val_acc = correct / total
190 | cnn.train()
191 | return val_acc
192 |
193 |
194 | for epoch in range(args.epochs):
195 |
196 | xentropy_loss_avg = 0.
197 | correct = 0.
198 | total = 0.
199 |
200 | progress_bar = tqdm(train_loader)
201 | for i, (images, labels) in enumerate(progress_bar):
202 | progress_bar.set_description('Epoch ' + str(epoch))
203 |
204 | images = images.cuda()
205 | labels = labels.cuda()
206 |
207 | #cnn.zero_grad()
208 | cnn_optimizer.zero_grad()
209 | pred = cnn(images)
210 |
211 | xentropy_loss = criterion(pred, labels)
212 | xentropy_loss.backward()
213 | cnn_optimizer.step()
214 |
215 | xentropy_loss_avg += xentropy_loss.item()
216 |
217 | # Calculate running average of accuracy
218 | pred = torch.max(pred.data, 1)[1]
219 | total += labels.size(0)
220 | correct += (pred == labels.data).sum().item()
221 | accuracy = correct / total
222 |
223 | progress_bar.set_postfix(
224 | xentropy='%.3f' % (xentropy_loss_avg / (i + 1)),
225 | acc='%.5f' % accuracy)
226 |
227 | test_acc = test(test_loader)
228 | tqdm.write('test_acc: %.5f' % (test_acc))
229 |
230 | scheduler.step(epoch) # Use this line for PyTorch <1.4
231 | # scheduler.step() # Use this line for PyTorch >=1.4
232 |
233 | row = {'epoch': str(epoch), 'train_acc': str(accuracy), 'test_acc': str(test_acc)}
234 | csv_logger.writerow(row)
235 |
236 | torch.save(cnn.state_dict(), 'checkpoints/' + test_id + '.pt')
237 | csv_logger.close()
238 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | Educational Community License, Version 2.0 (ECL-2.0)
2 |
3 | Version 2.0, April 2007
4 |
5 | http://www.osedu.org/licenses/
6 |
7 | The 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
8 |
9 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
10 |
11 | 1. Definitions.
12 |
13 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
14 |
15 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
16 |
17 | "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.
18 |
19 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
20 |
21 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
22 |
23 | "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.
24 |
25 | "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).
26 |
27 | "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.
28 |
29 | "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."
30 |
31 | "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.
32 |
33 | 2. Grant of Copyright License.
34 |
35 | Subject 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.
36 |
37 | 3. Grant of Patent License.
38 |
39 | Subject 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.
40 |
41 | 4. Redistribution.
42 |
43 | You 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:
44 |
45 | You 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.
46 |
47 | 5. Submission of Contributions.
48 |
49 | Unless 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.
50 |
51 | 6. Trademarks.
52 |
53 | This 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.
54 |
55 | 7. Disclaimer of Warranty.
56 |
57 | Unless 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.
58 |
59 | 8. Limitation of Liability.
60 |
61 | In 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.
62 |
63 | 9. Accepting Warranty or Additional Liability.
64 |
65 | While 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.
66 |
67 | END OF TERMS AND CONDITIONS
68 |
69 | APPENDIX: How to apply the Educational Community License to your work
70 |
71 | To apply the Educational Community License to your work, attach
72 | the following boilerplate notice, with the fields enclosed by
73 | brackets "[]" replaced with your own identifying information.
74 | (Don't include the brackets!) The text should be enclosed in the
75 | appropriate comment syntax for the file format. We also recommend
76 | that a file or class name and description of purpose be included on
77 | the same "printed page" as the copyright notice for easier
78 | identification within third-party archives.
79 |
80 | Copyright [yyyy] [name of copyright owner] Licensed under the
81 | Educational Community License, Version 2.0 (the "License"); you may
82 | not use this file except in compliance with the License. You may
83 | obtain a copy of the License at
84 |
85 | http://www.osedu.org/licenses /ECL-2.0
86 |
87 | Unless required by applicable law or agreed to in writing,
88 | software distributed under the License is distributed on an "AS IS"
89 | BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
90 | or implied. See the License for the specific language governing
91 | permissions and limitations under the License.
92 |
--------------------------------------------------------------------------------