├── .gitignore ├── doc ├── p1.png └── p2.png ├── scripts └── dualpath28-10.sh ├── models ├── __init__.py └── dualpath.py ├── README.md ├── utils.py ├── fashion_mnist.py ├── train_fashion_mnist.py ├── LICENSE └── train_cifar.py /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | \.idea/ 3 | -------------------------------------------------------------------------------- /doc/p1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Queequeg92/DualPathNet/HEAD/doc/p1.png -------------------------------------------------------------------------------- /doc/p2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Queequeg92/DualPathNet/HEAD/doc/p2.png -------------------------------------------------------------------------------- /scripts/dualpath28-10.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | cd .. 4 | 5 | python train_fashion_mnist.py \ 6 | --arch=DualPathNet_28_10 \ 7 | --epochs=180 \ 8 | --start_epoch=0 \ 9 | --batch_size=128 \ 10 | --lr=0.1 \ 11 | --lr_schedule=0 \ 12 | --momentum=0.9 \ 13 | --nesterov \ 14 | --weight_decay=0.0005 \ 15 | --ckpt_path='' 16 | 17 | python train_cifar.py \ 18 | --arch=DualPathNet_28_10 \ 19 | --dataset=cifar10 \ 20 | --epochs=200 \ 21 | --start_epoch=0 \ 22 | --batch_size=128 \ 23 | --lr=0.1 \ 24 | --lr_schedule=0 \ 25 | --momentum=0.9 \ 26 | --nesterov \ 27 | --weight_decay=0.0005 \ 28 | --ckpt_path='' -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Queequeg92. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # ============================================================================== 15 | 16 | from .dualpath import DualPathNet_28_10 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Dual Path Networks on cifar-10 and fashion-mnist datasets. 2 | ============= 3 | ---------- 4 | 5 | We construct a dual path network with WideResNet28-10 as the backbone network. The growth rate of densenet structure in the three convolutional stages are 16, 32 and 64, respectively. For details of the dual path network and wide resnet, please refer to [1] and [2]. We call this model DualPathNet28-10, which has 47.75M parameters (WideResNet28-10 has 37.5M parameters). 6 | The implementation details are as in [2]. **We did not fine-tune the hyperparameters. You might get better results after fine-tuning.** 7 | 8 | 9 | ## Results on cifar-10: 10 | Accuracy: 96.35 vs 96.10(WideResNet28-10) 11 | ![image](/doc/p1.png) 12 | 13 | ## Results on fashion-mnist: 14 | Accuracy: 95.73 15 | ![image](/doc/p2.png) 16 | 17 | ## To-Do: 18 | More dual path networks. 19 | **Welcome to make contributions!** 20 | 21 | ## Pre-requisites: 22 | pytorch http://pytorch.org/ 23 | tensorboard https://www.tensorflow.org/get_started/summaries_and_tensorboard 24 | tensorboard-pytorch https://github.com/lanpa/tensorboard-pytorch 25 | 26 | ## How to Run: 27 | ```shell 28 | # cd to the /scripts folder. 29 | cd /path-to-this-repository/scripts 30 | # run the shells. 31 | sh dualpath28-10.sh 32 | ``` 33 | ## Acknowledgments: 34 | Code in fashion_mnist.py are based on https://github.com/kefth/fashion-mnist/blob/master/fashionmnist.py 35 | All rights belongs to the original author. 36 | ## References: 37 | [1] Chen, Yunpeng, Jianan Li, Huaxin Xiao, Xiaojie Jin, Shuicheng Yan, and 38 | Jiashi Feng. "Dual Path Networks." arXiv preprint arXiv:1707.01629 (2017). 39 | [2] Zagoruyko, Sergey, and Nikos Komodakis. "Wide residual networks." arXiv preprint arXiv:1605.07146 (2016). 40 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Queequeg92. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # ============================================================================== 15 | 16 | import os 17 | import sys 18 | import time 19 | import math 20 | 21 | import torch 22 | import torch.nn as nn 23 | import torch.nn.init as init 24 | from torch.autograd import Variable 25 | import torchvision 26 | import torchvision.transforms as transforms 27 | 28 | 29 | def get_mean_and_std(dataset): 30 | '''Compute the mean and std value of dataset.''' 31 | dataloader = torch.utils.data.DataLoader(dataset, batch_size=100, shuffle=False, num_workers=10) 32 | mean = torch.zeros(3) 33 | std = torch.zeros(3) 34 | print('==> Computing mean and std..') 35 | print(len(dataset)) 36 | for inputs, targets in dataloader: 37 | if torch.cuda.is_available(): 38 | inputs, targets = inputs.cuda(), targets.cuda() 39 | for i in range(3): 40 | mean[i] += inputs[:,i,:,:].mean() 41 | std[i] += inputs[:,i,:,:].std() 42 | mean.div_(len(dataset)) 43 | std.div_(len(dataset)) 44 | return mean, std 45 | 46 | mean_cifar10 = (0.4914, 0.4822, 0.4465) 47 | std_cifar10 = (0.2023, 0.1994, 0.2010) 48 | 49 | mean_cifar100 = (0.5071, 0.4866, 0.4409) 50 | std_cifar100 = (0.2009, 0.1984, 0.2023) 51 | 52 | 53 | class AverageMeter(object): 54 | """Computes and stores the average and current value""" 55 | def __init__(self): 56 | self.reset() 57 | 58 | def reset(self): 59 | self.val = 0 60 | self.avg = 0 61 | self.numerator = 0 62 | self.denominator = 0 63 | 64 | def update(self, val, n=1): 65 | self.val = val 66 | self.numerator += val 67 | self.denominator += n 68 | self.avg = float(self.numerator) / float(self.denominator) 69 | 70 | if __name__ == '__main__': 71 | # Mean and std used to normalize cifar10. 72 | transform_train = transforms.Compose([transforms.ToTensor()]) 73 | trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train) 74 | mean, std = get_mean_and_std(trainset) 75 | print(mean) # output: (0.4914, 0.4822, 0.4465) 76 | print(std) # output: (0.2023, 0.1994, 0.2010) 77 | 78 | # Mean and std used to normalize cifar100. 79 | transform_train = transforms.Compose([transforms.ToTensor()]) 80 | trainset = torchvision.datasets.CIFAR100(root='./data', train=True, download=True, transform=transform_train) 81 | mean, std = get_mean_and_std(trainset) 82 | print(mean) # output: (0.5071, 0.4866, 0.4409) 83 | print(std) # output: (0.2009, 0.1984, 0.2023) 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /models/dualpath.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Queequeg92. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # ============================================================================== 15 | 16 | """Dual Path Networks. 17 | 18 | Related papers: 19 | [1] Chen, Yunpeng, Jianan Li, Huaxin Xiao, Xiaojie Jin, Shuicheng Yan, and 20 | Jiashi Feng. "Dual Path Networks." arXiv preprint arXiv:1707.01629 (2017). 21 | 22 | """ 23 | 24 | import torch 25 | import torch.nn as nn 26 | import torch.nn.functional as F 27 | import torch.nn.init as init 28 | 29 | from torch.autograd import Variable 30 | 31 | import math 32 | 33 | 34 | def conv3x3(in_planes, out_planes, stride=1): 35 | return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) 36 | 37 | 38 | class PreActBlock(nn.Module): 39 | '''Pre-activation version of the BasicBlock.''' 40 | 41 | def __init__(self, in_planes, planes, stride=1): 42 | super(PreActBlock, self).__init__() 43 | self.bn1 = nn.BatchNorm2d(in_planes) 44 | self.conv1 = conv3x3(in_planes, planes, stride) 45 | self.bn2 = nn.BatchNorm2d(planes) 46 | self.conv2 = conv3x3(planes, planes) 47 | 48 | if stride != 1 or in_planes != planes: 49 | self.shortcut = nn.Sequential( 50 | nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride, bias=False) 51 | ) 52 | 53 | def forward(self, x): 54 | out = F.relu(self.bn1(x)) 55 | shortcut = self.shortcut(out) if hasattr(self, 'shortcut') else x 56 | out = self.conv1(out) 57 | out = self.conv2(F.relu(self.bn2(out))) 58 | out += shortcut 59 | return out 60 | 61 | 62 | class ConvBlock(nn.Module): 63 | '''Similar to PreActBlock but without shortcut connection.''' 64 | def __init__(self, in_planes, planes, stride=1): 65 | super(ConvBlock, self).__init__() 66 | self.bn1 = nn.BatchNorm2d(in_planes) 67 | self.conv1 = conv3x3(in_planes, planes, stride) 68 | self.bn2 = nn.BatchNorm2d(planes) 69 | self.conv2 = conv3x3(planes, planes) 70 | 71 | 72 | def forward(self, x): 73 | out = F.relu(self.bn1(x)) 74 | out = self.conv1(out) 75 | out = self.conv2(F.relu(self.bn2(out))) 76 | return out 77 | 78 | 79 | class Transition(nn.Module): 80 | '''Transition layer between stages. 81 | Transition layer starts both the resnet 82 | branch and the densenet branch of a stage. 83 | ''' 84 | def __init__(self, block, in_planes, planes, growth_rate, stride=1): 85 | super(Transition, self).__init__() 86 | self.resnet_block = block(in_planes, planes, stride) 87 | self.conv = conv3x3(in_planes, 2*growth_rate, stride) 88 | 89 | def forward(self, x): 90 | resnet_path = self.resnet_block(x) 91 | densenet_path = self.conv(x) 92 | out = torch.cat([resnet_path, densenet_path], 1) 93 | return out 94 | 95 | 96 | class DualPathBlock(nn.Module): 97 | def __init__(self, block, in_planes, res_planes, growth_rate, stride=1): 98 | super(DualPathBlock, self).__init__() 99 | self.conv_block = block(in_planes, res_planes + growth_rate, stride) 100 | self.res_planes = res_planes 101 | 102 | def forward(self, x): 103 | merge_out = self.conv_block(x) 104 | out = torch.cat([x[:,:self.res_planes] + merge_out[:,:self.res_planes], # resnet branch. 105 | x[:, self.res_planes:], # new features of densenet branch. 106 | merge_out[:, self.res_planes:]], 1) # all previous features of densenet branch. 107 | return out 108 | 109 | 110 | class DualPathNet(nn.Module): 111 | def __init__(self, conv_block, transition_block, num_blocks, filters, growth_rates, num_classes=10): 112 | super(DualPathNet, self).__init__() 113 | self.in_planes = 16 114 | self.conv1 = conv3x3(1, self.in_planes) 115 | 116 | self.stage1_0 = Transition(transition_block, self.in_planes, filters[0], growth_rates[0], stride=1) 117 | self.in_planes = filters[0] + 2 * growth_rates[0] 118 | self.stage1 = self._make_layer(conv_block, self.in_planes, 119 | filters[0], num_blocks[0], 120 | growth_rates[0], stride=1) 121 | 122 | self.stage2_0 = Transition(transition_block, self.in_planes, filters[1], growth_rates[1], stride=2) 123 | self.in_planes = filters[1] + 2 * growth_rates[1] 124 | self.stage2 = self._make_layer(conv_block, self.in_planes, 125 | filters[1], num_blocks[1], 126 | growth_rates[1], stride=1) 127 | 128 | self.stage3_0 = Transition(transition_block, self.in_planes, filters[2], growth_rates[2], stride=2) 129 | self.in_planes = filters[2] + 2 * growth_rates[2] 130 | self.stage3 = self._make_layer(conv_block, self.in_planes, 131 | filters[2], num_blocks[2], 132 | growth_rates[2], stride=1) 133 | 134 | self.bn = nn.BatchNorm2d(self.in_planes) 135 | self.linear = nn.Linear(self.in_planes, num_classes) 136 | 137 | for m in self.modules(): 138 | if isinstance(m, nn.Conv2d): 139 | n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 140 | m.weight.data.normal_(0, math.sqrt(2. / n)) 141 | # m.bias.data.zero_() 142 | elif isinstance(m, nn.BatchNorm2d): 143 | m.weight.data.fill_(1) 144 | m.bias.data.zero_() 145 | elif isinstance(m, nn.Linear): 146 | init.kaiming_normal(m.weight) 147 | m.bias.data.zero_() 148 | 149 | def _make_layer(self, block, in_planes, planes, num_blocks, growth_rate, stride): 150 | strides = [1]*(num_blocks-1) 151 | layers = [] 152 | for stride in strides: 153 | layers.append(DualPathBlock(block, self.in_planes, planes, growth_rate, stride)) 154 | self.in_planes += growth_rate 155 | return nn.Sequential(*layers) 156 | 157 | def forward(self, x): 158 | out = self.conv1(x) 159 | 160 | out = self.stage1_0(out) 161 | out = self.stage1(out) 162 | 163 | out = self.stage2_0(out) 164 | out = self.stage2(out) 165 | 166 | out = self.stage3_0(out) 167 | out = self.stage3(out) 168 | 169 | out = F.relu(self.bn(out)) 170 | out = F.avg_pool2d(out, 7) 171 | out = out.view(out.size(0), -1) 172 | out = self.linear(out) 173 | return out 174 | 175 | 176 | 177 | def DualPathNet_28_10(num_classes=10): 178 | return DualPathNet(ConvBlock, PreActBlock, [4, 4, 4], [160, 320, 640], [16, 32, 64], num_classes) 179 | 180 | -------------------------------------------------------------------------------- /fashion_mnist.py: -------------------------------------------------------------------------------- 1 | """ 2 | """ 3 | 4 | import numpy as np 5 | 6 | import torch 7 | import torch.nn as nn 8 | import torch.nn.functional as F 9 | import torch.optim as optim 10 | 11 | from torchvision import datasets, transforms 12 | from torch.autograd import Variable 13 | from collections import namedtuple 14 | 15 | from matplotlib import pyplot as plt 16 | from PIL import Image 17 | 18 | import os 19 | import os.path 20 | import errno 21 | import codecs 22 | import copy 23 | 24 | from six.moves import urllib 25 | import gzip 26 | 27 | 28 | class MNIST(torch.utils.data.Dataset): 29 | """`MNIST `_ Dataset. 30 | Args: 31 | root (string): Root directory of dataset where ``processed/training.pt`` 32 | and ``processed/test.pt`` exist. 33 | dataset (string): If `train`, create dataset from ``training.pt``, 34 | otherwise from ``test.pt``. 35 | download (bool, optional): If true, downloads the dataset from the internet and 36 | puts it in root directory. If dataset is already downloaded, it is not 37 | downloaded again. 38 | transform (callable, optional): A function/transform that takes in an PIL image 39 | and returns a transformed version. E.g, ``transforms.RandomCrop`` 40 | target_transform (callable, optional): A function/transform that takes in the 41 | target and transforms it. 42 | """ 43 | mnist_base_url = 'http://yann.lecun.com/exdb/mnist/' 44 | fasion_base_url = 'https://cdn.rawgit.com/zalandoresearch/fashion-mnist/ed8e4f3b/data/fashion/' 45 | #base_url = mnist_base_url # change one line to change datasets 46 | base_url = fasion_base_url 47 | urls = [ 48 | base_url+'train-images-idx3-ubyte.gz', 49 | base_url+'train-labels-idx1-ubyte.gz', 50 | base_url+'t10k-images-idx3-ubyte.gz', 51 | base_url+'t10k-labels-idx1-ubyte.gz',] 52 | raw_folder = 'raw' 53 | processed_folder = 'processed' 54 | training_file = 'training.pt' 55 | test_file = 'test.pt' 56 | 57 | def __init__(self, root, dataset='train', transform=None, target_transform=None, download=False, 58 | force_download=False): 59 | self.root = os.path.expanduser(root) 60 | self.transform = transform 61 | self.target_transform = target_transform 62 | self.dataset = dataset # 'train' or 'test' 63 | 64 | self.force_download = force_download # if True, will download dataset everytime no matter what. 65 | 66 | if download: 67 | self.download() 68 | 69 | if not self._check_exists(): 70 | raise RuntimeError('Dataset not found.' + 71 | ' You can use download=True to download it') 72 | 73 | if self.dataset == 'train': 74 | self.data, self.labels = torch.load(os.path.join(root, self.processed_folder, self.training_file)) 75 | else: 76 | self.data, self.labels = torch.load(os.path.join(root, self.processed_folder, self.test_file)) 77 | 78 | def __getitem__(self, index): 79 | """ 80 | Args: 81 | index (int): Index 82 | Returns: 83 | tuple: (image, target) where target is index of the target class. 84 | """ 85 | img, target = self.data[index], self.labels[index] 86 | 87 | # doing this so that it is consistent with all other datasets 88 | # to return a PIL Image 89 | img = Image.fromarray(img.numpy(), mode='L') 90 | 91 | if self.transform is not None: 92 | img = self.transform(img) 93 | 94 | if self.target_transform is not None: 95 | target = self.target_transform(target) 96 | 97 | return img, target 98 | 99 | def __len__(self): 100 | return len(self.data) 101 | 102 | def _check_exists(self): 103 | return os.path.exists(os.path.join(self.root, self.processed_folder, self.training_file)) and \ 104 | os.path.exists(os.path.join(self.root, self.processed_folder, self.test_file)) 105 | 106 | def download(self): 107 | """Download the MNIST data if it doesn't exist in processed_folder already.""" 108 | 109 | if self._check_exists() and (not self.force_download): 110 | return 111 | 112 | # download files 113 | try: 114 | os.makedirs(os.path.join(self.root, self.raw_folder)) 115 | os.makedirs(os.path.join(self.root, self.processed_folder)) 116 | except OSError as e: 117 | if e.errno == errno.EEXIST: 118 | pass 119 | else: 120 | raise 121 | 122 | for url in self.urls: 123 | print('Downloading ' + url) 124 | data = urllib.request.urlopen(url) 125 | filename = url.rpartition('/')[2] 126 | file_path = os.path.join(self.root, self.raw_folder, filename) 127 | with open(file_path, 'wb') as f: 128 | f.write(data.read()) 129 | with open(file_path.replace('.gz', ''), 'wb') as out_f, \ 130 | gzip.GzipFile(file_path) as zip_f: 131 | out_f.write(zip_f.read()) 132 | os.unlink(file_path) 133 | 134 | # process and save as torch files 135 | print('Processing...') 136 | 137 | training_set = ( 138 | read_image_file(os.path.join(self.root, self.raw_folder, 'train-images-idx3-ubyte')), 139 | read_label_file(os.path.join(self.root, self.raw_folder, 'train-labels-idx1-ubyte')) 140 | ) 141 | test_set = ( 142 | read_image_file(os.path.join(self.root, self.raw_folder, 't10k-images-idx3-ubyte')), 143 | read_label_file(os.path.join(self.root, self.raw_folder, 't10k-labels-idx1-ubyte')) 144 | ) 145 | with open(os.path.join(self.root, self.processed_folder, self.training_file), 'wb') as f: 146 | torch.save(training_set, f) 147 | with open(os.path.join(self.root, self.processed_folder, self.test_file), 'wb') as f: 148 | torch.save(test_set, f) 149 | 150 | print('Done!') 151 | 152 | 153 | def get_int(b): 154 | return int(codecs.encode(b, 'hex'), 16) 155 | 156 | 157 | def parse_byte(b): 158 | if isinstance(b, str): 159 | return ord(b) 160 | return b 161 | 162 | 163 | def read_label_file(path): 164 | with open(path, 'rb') as f: 165 | data = f.read() 166 | assert get_int(data[:4]) == 2049 167 | length = get_int(data[4:8]) 168 | labels = [parse_byte(b) for b in data[8:]] 169 | assert len(labels) == length 170 | return torch.LongTensor(labels) 171 | 172 | 173 | def read_image_file(path): 174 | with open(path, 'rb') as f: 175 | data = f.read() 176 | assert get_int(data[:4]) == 2051 177 | length = get_int(data[4:8]) 178 | num_rows = get_int(data[8:12]) 179 | num_cols = get_int(data[12:16]) 180 | images = [] 181 | idx = 16 182 | for l in range(length): 183 | img = [] 184 | images.append(img) 185 | for r in range(num_rows): 186 | row = [] 187 | img.append(row) 188 | for c in range(num_cols): 189 | row.append(parse_byte(data[idx])) 190 | idx += 1 191 | assert len(images) == length 192 | return torch.ByteTensor(images).view(-1, 28, 28) 193 | 194 | 195 | if __name__ == '__main__': 196 | Args = namedtuple('Args', ['batch_size', 'test_batch_size', 'epochs', 'lr', 'cuda', 'seed', 'log_interval']) 197 | args = Args(batch_size=1000, test_batch_size=1000, epochs=30, lr=0.001, cuda=True, seed=0, log_interval=10) 198 | kwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {} 199 | 200 | train_loader = torch.utils.data.DataLoader( 201 | MNIST('MNIST_data', dataset='train', download=True, force_download=True, 202 | transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])), 203 | batch_size=args.batch_size, shuffle=True, **kwargs) 204 | test_loader = torch.utils.data.DataLoader( 205 | MNIST('MNIST_data', dataset='test', download=True, 206 | transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])), 207 | batch_size=args.batch_size, shuffle=True, **kwargs) 208 | -------------------------------------------------------------------------------- /train_fashion_mnist.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Queequeg92. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # ============================================================================== 15 | 16 | 17 | from __future__ import print_function 18 | 19 | import torch 20 | import torch.nn as nn 21 | import torch.optim as optim 22 | import torch.nn.functional as F 23 | import torch.backends.cudnn as cudnn 24 | 25 | import torchvision 26 | import torchvision.transforms as transforms 27 | import torchvision.utils as vutils 28 | 29 | from tensorboard import SummaryWriter 30 | 31 | from datetime import datetime 32 | import numpy as np 33 | 34 | import os 35 | import sys 36 | import time 37 | import argparse 38 | 39 | import models 40 | from torch.autograd import Variable 41 | 42 | from fashion_mnist import MNIST 43 | from utils import AverageMeter 44 | 45 | model_names = sorted(name for name in models.__dict__ 46 | if not name.startswith("__") 47 | and callable(models.__dict__[name])) 48 | 49 | parser = argparse.ArgumentParser(description='PyTorch Fashion-Mnist Classification Training') 50 | parser.add_argument('--arch', '-a', metavar='ARCH', default='SeResNet164', 51 | choices=model_names, 52 | help='model architecture: ' + 53 | ' | '.join(model_names) + 54 | ' (default: ResNet164)') 55 | parser.add_argument('--epochs', default=200, type=int, 56 | help='number of total epochs to run') 57 | parser.add_argument('--start_epoch', default=0, type=int, 58 | help='manual epoch number (useful on restarts)') 59 | parser.add_argument('--batch_size', default=128, type=int, 60 | help='mini-batch size (default: 128)') 61 | parser.add_argument('--lr', default=0.1, type=float, 62 | help='initial learning rate') 63 | parser.add_argument('--lr_schedule', default=0, type=int, 64 | help='learning rate schedule to apply') 65 | parser.add_argument('--momentum', default=0.9, type=float, help='momentum') 66 | parser.add_argument('--nesterov', default=False, action='store_true', help='nesterov momentum') 67 | parser.add_argument('--weight_decay', default=5e-4, type=float, 68 | help='weight decay (default: 5e-4)') 69 | parser.add_argument('--resume', default=False, action='store_true', help='resume from checkpoint') 70 | parser.add_argument('--ckpt_path', default='', type=str, metavar='PATH', 71 | help='path to checkpoint (default: none)') 72 | 73 | 74 | def main(): 75 | global args 76 | args = parser.parse_args() 77 | 78 | # Data preprocessing. 79 | print('==> Preparing data......') 80 | kwargs = {'num_workers': 4, 'pin_memory': True} 81 | train_loader = torch.utils.data.DataLoader( 82 | MNIST('MNIST_data', dataset='train', download=False, force_download=False, 83 | transform=transforms.Compose([transforms.RandomCrop(28, padding=4), 84 | transforms.RandomHorizontalFlip(), 85 | transforms.ToTensor(), 86 | transforms.Normalize((0.1307,), (0.3081,))])), 87 | batch_size=args.batch_size, shuffle=True, **kwargs) 88 | test_loader = torch.utils.data.DataLoader( 89 | MNIST('MNIST_data', dataset='test', download=False, 90 | transform=transforms.Compose([transforms.RandomCrop(28, padding=4), 91 | transforms.RandomHorizontalFlip(), 92 | transforms.ToTensor(), 93 | transforms.Normalize((0.1307,), (0.3081,))])), 94 | batch_size=100, shuffle=True, **kwargs) 95 | num_classes = 10 96 | 97 | # Model 98 | if args.resume: 99 | # Load checkpoint. 100 | print('==> Resuming from checkpoint..') 101 | assert os.path.isdir(args.ckpt_path), 'Error: checkpoint directory not exists!' 102 | checkpoint = torch.load(os.path.join(args.ckpt_path,'ckpt.t7')) 103 | model = checkpoint['model'] 104 | best_acc = checkpoint['best_acc'] 105 | start_epoch = checkpoint['epoch'] 106 | else: 107 | print('==> Building model..') 108 | model = models.__dict__[args.arch](num_classes) 109 | start_epoch = args.start_epoch 110 | 111 | print('Number of model parameters: {}'.format( 112 | sum([p.data.nelement() for p in model.parameters()]))) 113 | 114 | # Use GPUs if available. 115 | if torch.cuda.is_available(): 116 | model.cuda() 117 | model = torch.nn.DataParallel(model, device_ids=range(torch.cuda.device_count())) 118 | cudnn.benchmark = True 119 | 120 | # Define loss function and optimizer. 121 | criterion = nn.CrossEntropyLoss() 122 | optimizer = optim.SGD(model.parameters(), 123 | lr=args.lr, 124 | momentum=args.momentum, 125 | nesterov=args.nesterov, 126 | weight_decay=args.weight_decay) 127 | 128 | log_dir = 'logs/' + datetime.now().strftime('%B%d %H:%M:%S') 129 | train_writer = SummaryWriter(os.path.join(log_dir ,'train')) 130 | test_writer = SummaryWriter(os.path.join(log_dir ,'test')) 131 | 132 | # Save argparse commandline to a file. 133 | with open(os.path.join(log_dir, 'commandline_args.txt'), 'w') as f: 134 | f.write('\n'.join(sys.argv[1:])) 135 | 136 | best_acc = 0 # best test accuracy 137 | 138 | for epoch in range(start_epoch, args.epochs): 139 | # Learning rate schedule. 140 | lr = adjust_learning_rate(optimizer, epoch + 1) 141 | train_writer.add_scalar('lr', lr, epoch) 142 | 143 | 144 | # Train for one epoch. 145 | train(train_loader, model, criterion, optimizer, train_writer, epoch) 146 | 147 | # Eval on test set. 148 | num_iter = (epoch + 1) * len(train_loader) 149 | acc = eval(test_loader, model, criterion, test_writer, epoch, num_iter) 150 | 151 | # Save checkpoint. 152 | print('Saving Checkpoint......') 153 | state = { 154 | 'model': model.module if torch.cuda.is_available() else model, 155 | 'best_acc': best_acc, 156 | 'epoch': epoch, 157 | } 158 | if not os.path.isdir(os.path.join(log_dir, 'last_ckpt')): 159 | os.mkdir(os.path.join(log_dir, 'last_ckpt')) 160 | torch.save(state, os.path.join(log_dir, 'last_ckpt', 'ckpt.t7')) 161 | if acc > best_acc: 162 | best_acc = acc 163 | if not os.path.isdir(os.path.join(log_dir ,'best_ckpt')): 164 | os.mkdir(os.path.join(log_dir, 'best_ckpt')) 165 | torch.save(state, os.path.join(log_dir ,'best_ckpt', 'ckpt.t7')) 166 | 167 | train_writer.add_scalar('best_acc', best_acc, epoch) 168 | 169 | train_writer.close() 170 | test_writer.close() 171 | 172 | 173 | def adjust_learning_rate(optimizer, epoch): 174 | if args.lr_schedule == 0: 175 | lr = args.lr * ((0.2 ** int(epoch >= 60)) * (0.2 ** int(epoch >= 120)) * (0.2 ** int(epoch >= 160))) 176 | elif args.lr_schedule == 1: 177 | lr = args.lr * ((0.1 ** int(epoch >= 150)) * (0.1 ** int(epoch >= 225))) 178 | elif args.lr_schedule == 2: 179 | lr = args.lr * ((0.1 ** int(epoch >= 80)) * (0.1 ** int(epoch >= 120))) 180 | elif args.lr_schedule == 3: 181 | lr = args.lr * ((0.1 ** int(epoch >= 10)) * (0.1 ** int(epoch >= 20))) 182 | else: 183 | raise Exception("Invalid learning rate schedule!") 184 | for param_group in optimizer.param_groups: 185 | param_group['lr'] = lr 186 | return lr 187 | 188 | 189 | # Training 190 | def train(train_loader, model, criterion, optimizer, writer, epoch): 191 | print('\nEpoch: %d -> Training' % epoch) 192 | # Set to train mode. 193 | model.train() 194 | sample_time = AverageMeter() 195 | losses = AverageMeter() 196 | acces = AverageMeter() 197 | 198 | end = time.time() 199 | 200 | for batch_idx, (inputs, targets) in enumerate(train_loader): 201 | num_iter = epoch * len(train_loader) + batch_idx 202 | # Add summary to train images. 203 | writer.add_image('image', vutils.make_grid(inputs[0:4], normalize=False, scale_each=True), num_iter) 204 | # Add summary to conv1 weights. 205 | #conv1_weights = model.module.conv1.weight.clone().cpu().data.numpy() 206 | #writer.add_histogram('conv1', conv1_weights, num_iter) 207 | 208 | if torch.cuda.is_available(): 209 | inputs, targets = inputs.cuda(), targets.cuda() 210 | optimizer.zero_grad() 211 | inputs, targets = Variable(inputs), Variable(targets) 212 | 213 | # Compute gradients and do back propagation. 214 | outputs = model(inputs) 215 | loss = criterion(outputs, targets) 216 | loss.backward() 217 | optimizer.step() 218 | 219 | losses.update(loss.data[0]*inputs.size(0), inputs.size(0)) 220 | _, predicted = torch.max(outputs.data, 1) 221 | correct = predicted.eq(targets.data).cpu().sum() 222 | acces.update(correct, inputs.size(0)) 223 | # measure elapsed time 224 | sample_time.update(time.time() - end, inputs.size(0)) 225 | end = time.time() 226 | sys.stdout.write('Loss: %.4f | Acc: %.4f%% (%5d/%5d) \r' % (losses.avg, 100. * acces.avg, acces.numerator, acces.denominator)) 227 | sys.stdout.flush() 228 | writer.add_scalar('loss', losses.avg, epoch) 229 | writer.add_scalar('acc', acces.avg, epoch) 230 | print('Loss: %.4f | Acc: %.4f%% (%d/%d)' % (losses.avg, 100. * acces.avg, acces.numerator, acces.denominator)) 231 | 232 | 233 | # Evaluating 234 | def eval(test_loader, model, criterion, writer, epoch, num_iter): 235 | print('\nEpoch: %d -> Evaluating' % epoch) 236 | # Set to eval mode. 237 | model.eval() 238 | losses = AverageMeter() 239 | acces = AverageMeter() 240 | for batch_idx, (inputs, targets) in enumerate(test_loader): 241 | if torch.cuda.is_available(): 242 | inputs, targets = inputs.cuda(), targets.cuda() 243 | inputs, targets = Variable(inputs, volatile=True), Variable(targets) 244 | outputs = model(inputs) 245 | loss = criterion(outputs, targets) 246 | 247 | losses.update(loss.data[0]*inputs.size(0), inputs.size(0)) 248 | _, predicted = torch.max(outputs.data, 1) 249 | correct = predicted.eq(targets.data).cpu().sum() 250 | acces.update(correct, inputs.size(0)) 251 | 252 | sys.stdout.write( 253 | 'Loss: %.4f | Acc: %.4f%% (%5d/%5d) \r' % (losses.avg, 100. * acces.avg, acces.numerator, acces.denominator)) 254 | sys.stdout.flush() 255 | 256 | writer.add_scalar('loss', losses.avg, epoch) 257 | writer.add_scalar('acc', acces.avg, epoch) 258 | print('Loss: %.4f | Acc: %.4f%% (%d/%d)' % (losses.avg, 100. * acces.avg, acces.numerator, acces.denominator)) 259 | 260 | return acces.avg 261 | 262 | 263 | if __name__ == '__main__': 264 | main() 265 | 266 | 267 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Queequeg92. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /train_cifar.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Queequeg92. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # ============================================================================== 15 | 16 | from __future__ import print_function 17 | 18 | import torch 19 | import torch.nn as nn 20 | import torch.optim as optim 21 | import torch.nn.functional as F 22 | import torch.backends.cudnn as cudnn 23 | 24 | import torchvision 25 | import torchvision.transforms as transforms 26 | import torchvision.utils as vutils 27 | 28 | from tensorboard import SummaryWriter 29 | 30 | from datetime import datetime 31 | import numpy as np 32 | 33 | import os 34 | import sys 35 | import time 36 | import argparse 37 | 38 | import models 39 | from torch.autograd import Variable 40 | 41 | from utils import mean_cifar10, std_cifar10, mean_cifar100, std_cifar100 42 | from utils import AverageMeter 43 | 44 | model_names = sorted(name for name in models.__dict__ 45 | if not name.startswith("__") 46 | and callable(models.__dict__[name])) 47 | 48 | parser = argparse.ArgumentParser(description='PyTorch CIFAR Classification Training') 49 | parser.add_argument('--arch', '-a', metavar='ARCH', default='SeResNet164', 50 | choices=model_names, 51 | help='model architecture: ' + 52 | ' | '.join(model_names) + 53 | ' (default: ResNet164)') 54 | parser.add_argument('--dataset', default='cifar10', type=str, 55 | help='dataset (cifar10 [default] or cifar100)') 56 | parser.add_argument('--epochs', default=200, type=int, 57 | help='number of total epochs to run') 58 | parser.add_argument('--start_epoch', default=0, type=int, 59 | help='manual epoch number (useful on restarts)') 60 | parser.add_argument('--batch_size', default=128, type=int, 61 | help='mini-batch size (default: 128)') 62 | parser.add_argument('--lr', default=0.1, type=float, 63 | help='initial learning rate') 64 | parser.add_argument('--lr_schedule', default=0, type=int, 65 | help='learning rate schedule to apply') 66 | parser.add_argument('--momentum', default=0.9, type=float, help='momentum') 67 | parser.add_argument('--nesterov', default=False, action='store_true', help='nesterov momentum') 68 | parser.add_argument('--weight_decay', default=5e-4, type=float, 69 | help='weight decay (default: 5e-4)') 70 | parser.add_argument('--resume', default=False, action='store_true', help='resume from checkpoint') 71 | parser.add_argument('--ckpt_path', default='', type=str, metavar='PATH', 72 | help='path to checkpoint (default: none)') 73 | 74 | 75 | 76 | def main(): 77 | global args 78 | args = parser.parse_args() 79 | 80 | # Data preprocessing. 81 | print('==> Preparing data......') 82 | assert (args.dataset == 'cifar10' or args.dataset == 'cifar100'), "Only support cifar10 or cifar100 dataset" 83 | if args.dataset == 'cifar10': 84 | print('To train and eval on cifar10 dataset......') 85 | num_classes = 10 86 | transform_train = transforms.Compose([ 87 | transforms.RandomCrop(32, padding=4), 88 | transforms.RandomHorizontalFlip(), 89 | transforms.ToTensor(), 90 | transforms.Normalize(mean_cifar10, std_cifar10), 91 | ]) 92 | transform_test = transforms.Compose([ 93 | transforms.ToTensor(), 94 | transforms.Normalize(mean_cifar10, std_cifar10), 95 | ]) 96 | train_set = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train) 97 | train_loader = torch.utils.data.DataLoader(train_set, batch_size=args.batch_size, shuffle=True, num_workers=4) 98 | 99 | test_set = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test) 100 | test_loader = torch.utils.data.DataLoader(test_set, batch_size=100, shuffle=False, num_workers=4) 101 | else: 102 | print('To train and eval on cifar100 dataset......') 103 | num_classes = 100 104 | transform_train = transforms.Compose([ 105 | transforms.RandomCrop(32, padding=4), 106 | transforms.RandomHorizontalFlip(), 107 | transforms.ToTensor(), 108 | transforms.Normalize(mean_cifar100, std_cifar100), 109 | ]) 110 | transform_test = transforms.Compose([ 111 | transforms.ToTensor(), 112 | transforms.Normalize(mean_cifar100, std_cifar100), 113 | ]) 114 | train_set = torchvision.datasets.CIFAR100(root='./data', train=True, download=True, transform=transform_train) 115 | train_loader = torch.utils.data.DataLoader(train_set, batch_size=args.batch_size, shuffle=True, num_workers=4) 116 | 117 | test_set = torchvision.datasets.CIFAR100(root='./data', train=False, download=True, transform=transform_test) 118 | test_loader = torch.utils.data.DataLoader(test_set, batch_size=100, shuffle=False, num_workers=4) 119 | 120 | 121 | # Model 122 | if args.resume: 123 | # Load checkpoint. 124 | print('==> Resuming from checkpoint..') 125 | assert os.path.isdir(args.ckpt_path), 'Error: checkpoint directory not exists!' 126 | checkpoint = torch.load(os.path.join(args.ckpt_path,'ckpt.t7')) 127 | model = checkpoint['model'] 128 | best_acc = checkpoint['best_acc'] 129 | start_epoch = checkpoint['epoch'] 130 | else: 131 | print('==> Building model..') 132 | model = models.__dict__[args.arch](num_classes) 133 | start_epoch = args.start_epoch 134 | 135 | print('Number of model parameters: {}'.format( 136 | sum([p.data.nelement() for p in model.parameters()]))) 137 | 138 | # Use GPUs if available. 139 | if torch.cuda.is_available(): 140 | model.cuda() 141 | model = torch.nn.DataParallel(model, device_ids=range(torch.cuda.device_count())) 142 | cudnn.benchmark = True 143 | 144 | # Define loss function and optimizer. 145 | criterion = nn.CrossEntropyLoss() 146 | optimizer = optim.SGD(model.parameters(), 147 | lr=args.lr, 148 | momentum=args.momentum, 149 | nesterov=args.nesterov, 150 | weight_decay=args.weight_decay) 151 | 152 | log_dir = 'logs/' + datetime.now().strftime('%B%d %H:%M:%S') 153 | train_writer = SummaryWriter(os.path.join(log_dir ,'train')) 154 | test_writer = SummaryWriter(os.path.join(log_dir ,'test')) 155 | 156 | # Save argparse commandline to a file. 157 | with open(os.path.join(log_dir, 'commandline_args.txt'), 'w') as f: 158 | f.write('\n'.join(sys.argv[1:])) 159 | 160 | best_acc = 0 # best test accuracy 161 | 162 | for epoch in range(start_epoch, args.epochs): 163 | # Learning rate schedule. 164 | lr = adjust_learning_rate(optimizer, epoch + 1) 165 | train_writer.add_scalar('lr', lr, epoch) 166 | 167 | 168 | # Train for one epoch. 169 | train(train_loader, model, criterion, optimizer, train_writer, epoch) 170 | 171 | # Eval on test set. 172 | num_iter = (epoch + 1) * len(train_loader) 173 | acc = eval(test_loader, model, criterion, test_writer, epoch, num_iter) 174 | 175 | # Save checkpoint. 176 | print('Saving Checkpoint......') 177 | state = { 178 | 'model': model.module if torch.cuda.is_available() else model, 179 | 'best_acc': best_acc, 180 | 'epoch': epoch, 181 | } 182 | if not os.path.isdir(os.path.join(log_dir, 'last_ckpt')): 183 | os.mkdir(os.path.join(log_dir, 'last_ckpt')) 184 | torch.save(state, os.path.join(log_dir, 'last_ckpt', 'ckpt.t7')) 185 | if acc > best_acc: 186 | best_acc = acc 187 | if not os.path.isdir(os.path.join(log_dir ,'best_ckpt')): 188 | os.mkdir(os.path.join(log_dir, 'best_ckpt')) 189 | torch.save(state, os.path.join(log_dir ,'best_ckpt', 'ckpt.t7')) 190 | 191 | train_writer.add_scalar('best_acc', best_acc, epoch) 192 | 193 | train_writer.close() 194 | test_writer.close() 195 | 196 | 197 | def adjust_learning_rate(optimizer, epoch): 198 | if args.lr_schedule == 0: 199 | lr = args.lr * ((0.2 ** int(epoch >= 60)) * (0.2 ** int(epoch >= 120)) * (0.2 ** int(epoch >= 160))) 200 | elif args.lr_schedule == 1: 201 | lr = args.lr * ((0.1 ** int(epoch >= 150)) * (0.1 ** int(epoch >= 225))) 202 | elif args.lr_schedule == 2: 203 | lr = args.lr * ((0.1 ** int(epoch >= 80)) * (0.1 ** int(epoch >= 120))) 204 | else: 205 | raise Exception("Invalid learning rate schedule!") 206 | for param_group in optimizer.param_groups: 207 | param_group['lr'] = lr 208 | return lr 209 | 210 | 211 | # Training 212 | def train(train_loader, model, criterion, optimizer, writer, epoch): 213 | print('\nEpoch: %d -> Training' % epoch) 214 | # Set to train mode. 215 | model.train() 216 | sample_time = AverageMeter() 217 | losses = AverageMeter() 218 | acces = AverageMeter() 219 | 220 | end = time.time() 221 | 222 | for batch_idx, (inputs, targets) in enumerate(train_loader): 223 | num_iter = epoch * len(train_loader) + batch_idx 224 | # Add summary to train images. 225 | writer.add_image('image', vutils.make_grid(inputs[0:4], normalize=False, scale_each=True), num_iter) 226 | # Add summary to conv1 weights. 227 | #conv1_weights = model.module.conv1.weight.clone().cpu().data.numpy() 228 | #writer.add_histogram('conv1', conv1_weights, num_iter) 229 | 230 | if torch.cuda.is_available(): 231 | inputs, targets = inputs.cuda(), targets.cuda() 232 | optimizer.zero_grad() 233 | inputs, targets = Variable(inputs), Variable(targets) 234 | 235 | # Compute gradients and do back propagation. 236 | outputs = model(inputs) 237 | loss = criterion(outputs, targets) 238 | loss.backward() 239 | optimizer.step() 240 | 241 | losses.update(loss.data[0]*inputs.size(0), inputs.size(0)) 242 | _, predicted = torch.max(outputs.data, 1) 243 | correct = predicted.eq(targets.data).cpu().sum() 244 | acces.update(correct, inputs.size(0)) 245 | # measure elapsed time 246 | sample_time.update(time.time() - end, inputs.size(0)) 247 | end = time.time() 248 | sys.stdout.write('Loss: %.4f | Acc: %.4f%% (%5d/%5d) \r' % (losses.avg, 100. * acces.avg, acces.numerator, acces.denominator)) 249 | sys.stdout.flush() 250 | writer.add_scalar('loss', losses.avg, epoch) 251 | writer.add_scalar('acc', acces.avg, epoch) 252 | print('Loss: %.4f | Acc: %.4f%% (%d/%d)' % (losses.avg, 100. * acces.avg, acces.numerator, acces.denominator)) 253 | 254 | 255 | # Evaluating 256 | def eval(test_loader, model, criterion, writer, epoch, num_iter): 257 | print('\nEpoch: %d -> Evaluating' % epoch) 258 | # Set to eval mode. 259 | model.eval() 260 | losses = AverageMeter() 261 | acces = AverageMeter() 262 | for batch_idx, (inputs, targets) in enumerate(test_loader): 263 | if torch.cuda.is_available(): 264 | inputs, targets = inputs.cuda(), targets.cuda() 265 | inputs, targets = Variable(inputs, volatile=True), Variable(targets) 266 | outputs = model(inputs) 267 | loss = criterion(outputs, targets) 268 | 269 | losses.update(loss.data[0]*inputs.size(0), inputs.size(0)) 270 | _, predicted = torch.max(outputs.data, 1) 271 | correct = predicted.eq(targets.data).cpu().sum() 272 | acces.update(correct, inputs.size(0)) 273 | 274 | sys.stdout.write( 275 | 'Loss: %.4f | Acc: %.4f%% (%5d/%5d) \r' % (losses.avg, 100. * acces.avg, acces.numerator, acces.denominator)) 276 | sys.stdout.flush() 277 | 278 | writer.add_scalar('loss', losses.avg, epoch) 279 | writer.add_scalar('acc', acces.avg, epoch) 280 | print('Loss: %.4f | Acc: %.4f%% (%d/%d)' % (losses.avg, 100. * acces.avg, acces.numerator, acces.denominator)) 281 | 282 | return acces.avg 283 | 284 | 285 | if __name__ == '__main__': 286 | main() 287 | 288 | 289 | --------------------------------------------------------------------------------