|
| 1 | +import datetime, re |
| 2 | +from collections import OrderedDict |
| 3 | +import torch |
| 4 | +import torch.nn as nn |
| 5 | +import torch.nn.parallel |
| 6 | +import torch.backends.cudnn as cudnn |
| 7 | +import torch.optim |
| 8 | +import torch.utils.data |
| 9 | + |
| 10 | +from shared.base_model import BaseModel |
| 11 | +from shared.resnet_3x3 import resnet18 |
| 12 | + |
| 13 | + |
| 14 | +use_cuda = False |
| 15 | + |
| 16 | + |
| 17 | +''' The final model ''' |
| 18 | + |
| 19 | + |
| 20 | +class SmallNet(nn.Module): |
| 21 | + ''' |
| 22 | + This model extract features for each single input frame. |
| 23 | + ''' |
| 24 | + |
| 25 | + def __init__(self): |
| 26 | + super(SmallNet, self).__init__() |
| 27 | + self.features = resnet18(pretrained=False) |
| 28 | + self.features.fc = nn.Threshold(-1e20, -1e20) # a pass-through layer for snapshot compatibility |
| 29 | + |
| 30 | + def forward(self, pressure): |
| 31 | + x = self.features(pressure) |
| 32 | + return x |
| 33 | + |
| 34 | + |
| 35 | +class TouchNet(nn.Module): |
| 36 | + ''' |
| 37 | + This model represents our classification network for 1..N input frames. |
| 38 | + ''' |
| 39 | + |
| 40 | + def __init__(self, num_classes=1000, nFrames=5): |
| 41 | + super(TouchNet, self).__init__() |
| 42 | + self.net = SmallNet() |
| 43 | + self.combination = nn.Conv2d(128*nFrames, 128, kernel_size=1, padding=0) |
| 44 | + self.classifier = nn.Linear(128, num_classes) |
| 45 | + self.avgpool = nn.AdaptiveAvgPool2d(1) |
| 46 | + |
| 47 | + def forward(self, x): |
| 48 | + xs = [] |
| 49 | + # CNN of each input frame |
| 50 | + for i in range(x.size(1)): |
| 51 | + xi = x[:,i:i+1,...] |
| 52 | + xi = self.net(xi) |
| 53 | + xs += [xi] |
| 54 | + x = torch.cat(xs, dim=1) |
| 55 | + |
| 56 | + # combine |
| 57 | + x = self.combination(x) |
| 58 | + x = self.avgpool(x) |
| 59 | + x = x.view(x.size(0), -1) |
| 60 | + |
| 61 | + x = self.classifier(x) |
| 62 | + return x |
| 63 | + |
| 64 | + |
| 65 | +class ClassificationModel(BaseModel): |
| 66 | + ''' |
| 67 | + This class encapsulates the network and handles I/O. |
| 68 | + ''' |
| 69 | + |
| 70 | + @property |
| 71 | + def name(self): |
| 72 | + return 'ClassificationModel' |
| 73 | + |
| 74 | + def initialize(self, numClasses, sequenceLength=1, baseLr=1e-3): |
| 75 | + BaseModel.initialize(self) |
| 76 | + |
| 77 | + print('Base LR = %e' % baseLr) |
| 78 | + self.baseLr = baseLr |
| 79 | + self.numClasses = numClasses |
| 80 | + self.sequenceLength = sequenceLength |
| 81 | + |
| 82 | + self.model = TouchNet(num_classes=self.numClasses, |
| 83 | + nFrames=self.sequenceLength) |
| 84 | + self.model = torch.nn.DataParallel(self.model) |
| 85 | + |
| 86 | + # TODO: FIX THIS. NOT WORKING WITH MY MAC |
| 87 | + self.device = torch.device('cuda' if use_cuda else 'cpu') |
| 88 | + |
| 89 | + # self.model.cuda(self.device) |
| 90 | + self.model.to(self.device) |
| 91 | + |
| 92 | + cudnn.benchmark = True |
| 93 | + |
| 94 | + self.optimizer = torch.optim.Adam( |
| 95 | + [{'params': self.model.module.parameters(), 'lr_mult': 1.0}], |
| 96 | + self.baseLr) |
| 97 | + |
| 98 | + self.optimizers = [self.optimizer] |
| 99 | + |
| 100 | + self.criterion = nn.CrossEntropyLoss().cuda(self.device) |
| 101 | + |
| 102 | + self.epoch = 0 |
| 103 | + self.error = 1e20 # last error |
| 104 | + self.bestPrec = 1e20 # best error |
| 105 | + |
| 106 | + self.dataProcessor = None |
| 107 | + |
| 108 | + def step(self, inputs, isTrain=True, params={}): |
| 109 | + |
| 110 | + if isTrain: |
| 111 | + self.model.train() |
| 112 | + assert not inputs['objectId'] is None |
| 113 | + else: |
| 114 | + self.model.eval() |
| 115 | + |
| 116 | + # TODO: Make it asyncronous. Will be if cuda enabled |
| 117 | + # image = torch.autograd.Variable( |
| 118 | + # inputs['image'].cuda(async=True), requires_grad=(isTrain)) |
| 119 | + # pressure = torch.autograd.Variable( |
| 120 | + # inputs['pressure'].cuda(async=True), requires_grad = (isTrain)) |
| 121 | + # objectId = torch.autograd.Variable( |
| 122 | + # inputs['objectId'].cuda(async=True), requires_grad=False |
| 123 | + # ) if 'objectId' in inputs else None |
| 124 | + image = torch.autograd.Variable(inputs['image'].to( |
| 125 | + self.device), requires_grad=(isTrain)) |
| 126 | + pressure = torch.autograd.Variable(inputs['pressure'].to( |
| 127 | + self.device), requires_grad = (isTrain)) |
| 128 | + objectId = torch.autograd.Variable( |
| 129 | + inputs['objectId'].to(self.device), requires_grad=False |
| 130 | + ) if 'objectId' in inputs else None |
| 131 | + |
| 132 | + if isTrain: |
| 133 | + output = self.model(pressure) |
| 134 | + else: |
| 135 | + with torch.no_grad(): |
| 136 | + output = self.model(pressure) |
| 137 | + |
| 138 | + _, pred = output.data.topk(1, 1, True, True) |
| 139 | + res = {'gt': None if objectId is None else objectId.data, 'pred': pred} |
| 140 | + |
| 141 | + if objectId is None: |
| 142 | + return res, {} |
| 143 | + |
| 144 | + loss = self.criterion(output, objectId.view(-1)) |
| 145 | + |
| 146 | + (prec1, prec3) = self.accuracy( |
| 147 | + output, objectId, topk=(1, min(3, self.numClasses))) |
| 148 | + |
| 149 | + if isTrain: |
| 150 | + # compute gradient and do SGD step |
| 151 | + self.optimizer.zero_grad() |
| 152 | + loss.backward() |
| 153 | + self.optimizer.step() |
| 154 | + |
| 155 | + losses = OrderedDict([ |
| 156 | + ('Loss', loss.data.item()), |
| 157 | + ('Top1', prec1), |
| 158 | + ('Top3', prec3), |
| 159 | + ]) |
| 160 | + |
| 161 | + return res, losses |
| 162 | + |
| 163 | + def accuracy(self, output, target, topk=(1,)): |
| 164 | + """Computes the precision@k for the specified values of k""" |
| 165 | + maxk = max(topk) |
| 166 | + batch_size = target.size(0) |
| 167 | + |
| 168 | + _, pred = output.data.topk(maxk, 1, True, True) |
| 169 | + pred = pred.t() |
| 170 | + correct = pred.eq(target.data.view(1, -1).expand_as(pred)) |
| 171 | + |
| 172 | + res = [] |
| 173 | + for k in topk: |
| 174 | + correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) |
| 175 | + res.append(correct_k.mul_(100.0 / batch_size).item()) |
| 176 | + return res[0], res[1] |
| 177 | + |
| 178 | + def importState(self, save): |
| 179 | + self.model.load_state_dict(save) |
| 180 | + print('Model imported') |
| 181 | + #params = save['state_dict'] |
| 182 | + #if hasattr(self.model, 'module'): |
| 183 | + # try: |
| 184 | + # self.model.load_state_dict(params, strict=True) |
| 185 | + # except: |
| 186 | + # self.model.module.load_state_dict(params, strict=True) |
| 187 | + #else: |
| 188 | + # params = self._clearState(params) |
| 189 | + # self.model.load_state_dict(params, strict=True) |
| 190 | + |
| 191 | + #self.epoch = save['epoch'] if 'epoch' in save else 0 |
| 192 | + #self.bestPrec = save['best_prec1'] if 'best_prec1' in save else 1e20 |
| 193 | + #self.error = save['error'] if 'error' in save else 1e20 |
| 194 | + #print('Imported checkpoint for epoch %05d with loss = %.3f...' % ( |
| 195 | + # self.epoch, self.bestPrec)) |
| 196 | + |
| 197 | + def _clearState(self, params): |
| 198 | + res = dict() |
| 199 | + for k, v in params.items(): |
| 200 | + kNew = re.sub('^module\.', '', k) |
| 201 | + res[kNew] = v |
| 202 | + |
| 203 | + return res |
| 204 | + |
| 205 | + def exportState(self): |
| 206 | + return self.model.state_dict() |
| 207 | + #dt = datetime.datetime.now() |
| 208 | + #state = self.model.state_dict() |
| 209 | + #for k in state.keys(): |
| 210 | + # # state[k] = state[k].share_memory_() |
| 211 | + # state[k] = state[k].cpu() |
| 212 | + #return { |
| 213 | + # 'state_dict': state, |
| 214 | + # 'epoch': self.epoch, |
| 215 | + # 'error': self.error, |
| 216 | + # 'best_prec1': self.bestPrec, |
| 217 | + # 'datetime': dt.strftime("%Y-%m-%d %H:%M:%S") |
| 218 | + #} |
| 219 | + |
| 220 | + def updateLearningRate(self, epoch): |
| 221 | + self.adjust_learning_rate_new(epoch, self.baseLr) |
| 222 | + |
| 223 | + def adjust_learning_rate_new(self, epoch, base_lr, period=100): # train for 2x100 epochs |
| 224 | + gamma = 0.1 ** (1.0/period) |
| 225 | + lr_default = base_lr * (gamma ** (epoch)) |
| 226 | + print('New lr_default = %f' % lr_default) |
| 227 | + |
| 228 | + for optimizer in self.optimizers: |
| 229 | + for param_group in optimizer.param_groups: |
| 230 | + param_group['lr'] = param_group['lr_mult'] * lr_default |
| 231 | + |
0 commit comments