CNNSupervisedTrainer_VGG16.py 14.6 KB
 Nicola Gatto committed Apr 08, 2019 1 2 3 4 5 6 ``````import mxnet as mx import logging import numpy as np import time import os import shutil `````` Christian Fuß committed Oct 08, 2019 7 ``````import pickle `````` Sebastian Nickels committed Oct 18, 2019 8 9 ``````import math import sys `````` Nicola Gatto committed Apr 08, 2019 10 11 ``````from mxnet import gluon, autograd, nd `````` Eyüp Harputlu committed Jun 05, 2019 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 ``````class CrossEntropyLoss(gluon.loss.Loss): def __init__(self, axis=-1, sparse_label=True, weight=None, batch_axis=0, **kwargs): super(CrossEntropyLoss, self).__init__(weight, batch_axis, **kwargs) self._axis = axis self._sparse_label = sparse_label def hybrid_forward(self, F, pred, label, sample_weight=None): pred = F.log(pred) if self._sparse_label: loss = -F.pick(pred, label, axis=self._axis, keepdims=True) else: label = gluon.loss._reshape_like(F, label, pred) loss = -F.sum(pred * label, axis=self._axis, keepdims=True) loss = gluon.loss._apply_weighting(F, loss, self._weight, sample_weight) return F.mean(loss, axis=self._batch_axis, exclude=True) `````` Eyüp Harputlu committed Jun 24, 2019 28 29 30 31 32 33 34 35 36 ``````class LogCoshLoss(gluon.loss.Loss): def __init__(self, weight=None, batch_axis=0, **kwargs): super(LogCoshLoss, self).__init__(weight, batch_axis, **kwargs) def hybrid_forward(self, F, pred, label, sample_weight=None): loss = F.log(F.cosh(pred - label)) loss = gluon.loss._apply_weighting(F, loss, self._weight, sample_weight) return F.mean(loss, axis=self._batch_axis, exclude=True) `````` Sebastian Nickels committed Oct 18, 2019 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 ``````@mx.metric.register class BLEU(mx.metric.EvalMetric): N = 4 def __init__(self, exclude=None, name='bleu', output_names=None, label_names=None): super(BLEU, self).__init__(name=name, output_names=output_names, label_names=label_names) self._exclude = exclude or [] self._match_counts = [0 for _ in range(self.N)] self._counts = [0 for _ in range(self.N)] self._size_ref = 0 self._size_hyp = 0 def update(self, labels, preds): labels, preds = mx.metric.check_label_shapes(labels, preds, True) new_labels = self._convert(labels) new_preds = self._convert(preds) for label, pred in zip(new_labels, new_preds): reference = [word for word in label if word not in self._exclude] hypothesis = [word for word in pred if word not in self._exclude] self._size_ref += len(reference) self._size_hyp += len(hypothesis) for n in range(self.N): reference_ngrams = self._get_ngrams(reference, n + 1) hypothesis_ngrams = self._get_ngrams(hypothesis, n + 1) match_count = 0 for ngram in hypothesis_ngrams: if ngram in reference_ngrams: reference_ngrams.remove(ngram) match_count += 1 self._match_counts[n] += match_count self._counts[n] += len(hypothesis_ngrams) def get(self): precisions = [sys.float_info.min for n in range(self.N)] i = 1 for n in range(self.N): match_counts = self._match_counts[n] counts = self._counts[n] if counts != 0: if match_counts == 0: i *= 2 match_counts = 1 / i precisions[n] = match_counts / counts bleu = self._get_brevity_penalty() * math.exp(sum(map(math.log, precisions)) / self.N) return (self.name, bleu) def calculate(self): precisions = [sys.float_info.min for n in range(self.N)] i = 1 for n in range(self.N): match_counts = self._match_counts[n] counts = self._counts[n] if counts != 0: if match_counts == 0: i *= 2 match_counts = 1 / i precisions[n] = match_counts / counts return self._get_brevity_penalty() * math.exp(sum(map(math.log, precisions)) / self.N) def _get_brevity_penalty(self): if self._size_hyp >= self._size_ref: return 1 else: return math.exp(1 - (self._size_ref / self._size_hyp)) @staticmethod def _get_ngrams(sentence, n): ngrams = [] if len(sentence) >= n: for i in range(len(sentence) - n + 1): ngrams.append(sentence[i:i+n]) return ngrams @staticmethod def _convert(nd_list): if len(nd_list) == 0: return [] new_list = [[] for _ in range(nd_list[0].shape[0])] for element in nd_list: for i in range(element.shape[0]): new_list[i].append(element[i].asscalar()) return new_list `````` Christian Fuß committed Oct 08, 2019 146 `````` `````` Sebastian Nickels committed May 26, 2019 147 ``````class CNNSupervisedTrainer_VGG16: `````` Christian Fuß committed Sep 24, 2019 148 `````` def applyBeamSearch(input, length, width, maxLength, currProb, netIndex, bestOutput): `````` Christian Fuß committed Sep 23, 2019 149 `````` bestProb = 0.0 `````` Christian Fuß committed Sep 24, 2019 150 151 `````` while length < maxLength: length += 1 `````` Christian Fuß committed Sep 23, 2019 152 153 154 155 156 157 158 159 `````` batchIndex = 0 for batchEntry in input: top_k_indices = mx.nd.topk(batchEntry, axis=0, k=width) top_k_values = mx.nd.topk(batchEntry, ret_typ='value', axis=0, k=width) for index in range(top_k_indices.size): #print mx.nd.array(top_k_indices[index]) #print top_k_values[index] `````` Christian Fuß committed Sep 24, 2019 160 `````` if length == 1: `````` Christian Fuß committed Sep 23, 2019 161 `````` #print mx.nd.array(top_k_indices[index]) `````` Christian Fuß committed Sep 24, 2019 162 `````` result = applyBeamSearch(self._networks[netIndex](mx.nd.array(top_k_indices[index])), length, width, maxLength, `````` Christian Fuß committed Sep 23, 2019 163 164 `````` currProb * top_k_values[index], netIndex, self._networks[netIndex](mx.nd.array(top_k_indices[index]))) else: `````` Christian Fuß committed Sep 24, 2019 165 `````` result = applyBeamSearch(self._networks[netIndex](mx.nd.array(top_k_indices[index])), length, width, maxLength, `````` Christian Fuß committed Sep 23, 2019 166 167 `````` currProb * top_k_values[index], netIndex, bestOutput) `````` Christian Fuß committed Sep 24, 2019 168 `````` if length == maxLength: `````` Christian Fuß committed Sep 23, 2019 169 170 171 172 173 174 175 176 177 178 179 180 `````` #print currProb if currProb > bestProb: bestProb = currProb bestOutput[batchIndex] = result[batchIndex] #print "new bestOutput: ", bestOutput batchIndex += 1 #print bestOutput #print bestProb return bestOutput `````` Sebastian Nickels committed Jun 21, 2019 181 `````` def __init__(self, data_loader, net_constructor): `````` Nicola Gatto committed Apr 08, 2019 182 183 `````` self._data_loader = data_loader self._net_creator = net_constructor `````` Sebastian Nickels committed Jun 21, 2019 184 `````` self._networks = {} `````` Nicola Gatto committed Apr 08, 2019 185 186 187 188 `````` def train(self, batch_size=64, num_epoch=10, eval_metric='acc', `````` Sebastian Nickels committed Oct 18, 2019 189 `````` eval_metric_params={}, `````` Eyüp Harputlu committed Jun 05, 2019 190 191 `````` loss ='softmax_cross_entropy', loss_params={}, `````` Nicola Gatto committed Apr 08, 2019 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 `````` optimizer='adam', optimizer_params=(('learning_rate', 0.001),), load_checkpoint=True, context='gpu', checkpoint_period=5, normalize=True): if context == 'gpu': mx_context = mx.gpu() elif context == 'cpu': mx_context = mx.cpu() else: logging.error("Context argument is '" + context + "'. Only 'cpu' and 'gpu are valid arguments'.") if 'weight_decay' in optimizer_params: optimizer_params['wd'] = optimizer_params['weight_decay'] del optimizer_params['weight_decay'] if 'learning_rate_decay' in optimizer_params: min_learning_rate = 1e-08 if 'learning_rate_minimum' in optimizer_params: min_learning_rate = optimizer_params['learning_rate_minimum'] del optimizer_params['learning_rate_minimum'] optimizer_params['lr_scheduler'] = mx.lr_scheduler.FactorScheduler( optimizer_params['step_size'], factor=optimizer_params['learning_rate_decay'], stop_factor_lr=min_learning_rate) del optimizer_params['step_size'] del optimizer_params['learning_rate_decay'] train_iter, test_iter, data_mean, data_std = self._data_loader.load_data(batch_size) `````` Sebastian Nickels committed Jun 21, 2019 222 223 224 225 226 `````` if normalize: self._net_creator.construct(context=mx_context, data_mean=data_mean, data_std=data_std) else: self._net_creator.construct(context=mx_context) `````` Nicola Gatto committed Apr 08, 2019 227 228 229 230 231 232 233 234 `````` begin_epoch = 0 if load_checkpoint: begin_epoch = self._net_creator.load(mx_context) else: if os.path.isdir(self._net_creator._model_dir_): shutil.rmtree(self._net_creator._model_dir_) `````` Sebastian Nickels committed Jun 21, 2019 235 `````` self._networks = self._net_creator.networks `````` Nicola Gatto committed Apr 08, 2019 236 237 238 239 240 241 242 `````` try: os.makedirs(self._net_creator._model_dir_) except OSError: if not os.path.isdir(self._net_creator._model_dir_): raise `````` Sebastian Nickels committed Jun 21, 2019 243 `````` trainers = [mx.gluon.Trainer(network.collect_params(), optimizer, optimizer_params) for network in self._networks.values()] `````` Nicola Gatto committed Apr 08, 2019 244 `````` `````` Eyüp Harputlu committed Jun 05, 2019 245 246 247 248 249 250 `````` margin = loss_params['margin'] if 'margin' in loss_params else 1.0 sparseLabel = loss_params['sparse_label'] if 'sparse_label' in loss_params else True if loss == 'softmax_cross_entropy': fromLogits = loss_params['from_logits'] if 'from_logits' in loss_params else False loss_function = mx.gluon.loss.SoftmaxCrossEntropyLoss(from_logits=fromLogits, sparse_label=sparseLabel) elif loss == 'sigmoid_binary_cross_entropy': `````` Nicola Gatto committed Apr 08, 2019 251 `````` loss_function = mx.gluon.loss.SigmoidBinaryCrossEntropyLoss() `````` Eyüp Harputlu committed Jun 05, 2019 252 253 254 `````` elif loss == 'cross_entropy': loss_function = CrossEntropyLoss(sparse_label=sparseLabel) elif loss == 'l2': `````` Nicola Gatto committed Apr 08, 2019 255 `````` loss_function = mx.gluon.loss.L2Loss() `````` Eyüp Harputlu committed Jun 05, 2019 256 `````` elif loss == 'l1': `````` Nicola Gatto committed Apr 08, 2019 257 `````` loss_function = mx.gluon.loss.L2Loss() `````` Eyüp Harputlu committed Jun 05, 2019 258 259 260 261 262 263 264 265 266 267 268 269 270 `````` elif loss == 'huber': rho = loss_params['rho'] if 'rho' in loss_params else 1 loss_function = mx.gluon.loss.HuberLoss(rho=rho) elif loss == 'hinge': loss_function = mx.gluon.loss.HingeLoss(margin=margin) elif loss == 'squared_hinge': loss_function = mx.gluon.loss.SquaredHingeLoss(margin=margin) elif loss == 'logistic': labelFormat = loss_params['label_format'] if 'label_format' in loss_params else 'signed' loss_function = mx.gluon.loss.LogisticLoss(label_format=labelFormat) elif loss == 'kullback_leibler': fromLogits = loss_params['from_logits'] if 'from_logits' in loss_params else True loss_function = mx.gluon.loss.KLDivLoss(from_logits=fromLogits) `````` Eyüp Harputlu committed Jun 24, 2019 271 272 `````` elif loss == 'log_cosh': loss_function = LogCoshLoss() `````` Eyüp Harputlu committed Jun 05, 2019 273 274 `````` else: logging.error("Invalid loss parameter.") `````` Nicola Gatto committed Apr 08, 2019 275 276 277 278 279 280 281 `````` speed_period = 50 tic = None for epoch in range(begin_epoch, begin_epoch + num_epoch): train_iter.reset() for batch_i, batch in enumerate(train_iter): `````` Sebastian Nickels committed Aug 12, 2019 282 `````` data_ = batch.data[0].as_in_context(mx_context) `````` Sebastian Nickels committed Jun 06, 2019 283 `````` predictions_label = batch.label[0].as_in_context(mx_context) `````` Sebastian Nickels committed May 26, 2019 284 `````` `````` Christian Fuß committed Oct 08, 2019 285 286 `````` outputs=[] `````` Nicola Gatto committed Apr 08, 2019 287 `````` with autograd.record(): `````` Sebastian Nickels committed Sep 06, 2019 288 `````` predictions_ = mx.nd.zeros((batch_size, 1000,), ctx=mx_context) `````` Sebastian Nickels committed Aug 12, 2019 289 `````` `````` Christian Fuß committed Sep 10, 2019 290 `````` lossList = [] `````` Sebastian Nickels committed Aug 12, 2019 291 `````` predictions_ = self._networks[0](data_) `````` Christian Fuß committed Sep 10, 2019 292 293 294 295 296 `````` lossList.append(loss_function(predictions_, predictions_label)) loss = 0 for element in lossList: loss = loss + element `````` Sebastian Nickels committed Jun 06, 2019 297 `````` `````` Nicola Gatto committed Apr 08, 2019 298 `````` loss.backward() `````` Sebastian Nickels committed Jun 21, 2019 299 300 301 `````` for trainer in trainers: trainer.step(batch_size) `````` Nicola Gatto committed Apr 08, 2019 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 `````` if tic is None: tic = time.time() else: if batch_i % speed_period == 0: try: speed = speed_period * batch_size / (time.time() - tic) except ZeroDivisionError: speed = float("inf") logging.info("Epoch[%d] Batch[%d] Speed: %.2f samples/sec" % (epoch, batch_i, speed)) tic = time.time() tic = None train_iter.reset() `````` Sebastian Nickels committed Oct 18, 2019 319 `````` metric = mx.metric.create(eval_metric, **eval_metric_params) `````` Nicola Gatto committed Apr 08, 2019 320 `````` for batch_i, batch in enumerate(train_iter): `````` Sebastian Nickels committed Aug 12, 2019 321 `````` data_ = batch.data[0].as_in_context(mx_context) `````` Sebastian Nickels committed Jun 06, 2019 322 323 324 325 326 `````` labels = [ batch.label[0].as_in_context(mx_context) ] `````` Christian Fuß committed Sep 23, 2019 327 `````` outputs=[] `````` Christian Fuß committed Sep 15, 2019 328 `````` `````` Sebastian Nickels committed Oct 18, 2019 329 `````` if True: `````` Sebastian Nickels committed Sep 06, 2019 330 `````` predictions_ = mx.nd.zeros((batch_size, 1000,), ctx=mx_context) `````` Sebastian Nickels committed Aug 12, 2019 331 332 `````` predictions_ = self._networks[0](data_) `````` Christian Fuß committed Sep 23, 2019 333 `````` outputs.append(predictions_) `````` Sebastian Nickels committed May 26, 2019 334 `````` `````` Christian Fuß committed Sep 09, 2019 335 `````` predictions = [] `````` Christian Fuß committed Sep 23, 2019 336 `````` for output_name in outputs: `````` Christian Fuß committed Sep 09, 2019 337 338 339 340 341 `````` if mx.nd.shape_array(output_name).size > 1: predictions.append(mx.nd.argmax(output_name, axis=1)) #ArgMax already applied else: predictions.append(output_name) `````` Christian Fuß committed Aug 28, 2019 342 `````` `````` Sebastian Nickels committed Jun 06, 2019 343 `````` metric.update(preds=predictions, labels=labels) `````` Nicola Gatto committed Apr 08, 2019 344 345 346 `````` train_metric_score = metric.get()[1] test_iter.reset() `````` Sebastian Nickels committed Oct 18, 2019 347 `````` metric = mx.metric.create(eval_metric, **eval_metric_params) `````` Nicola Gatto committed Apr 08, 2019 348 `````` for batch_i, batch in enumerate(test_iter): `````` Sebastian Nickels committed Aug 12, 2019 349 `````` data_ = batch.data[0].as_in_context(mx_context) `````` Sebastian Nickels committed Jun 06, 2019 350 351 352 353 354 `````` labels = [ batch.label[0].as_in_context(mx_context) ] `````` Christian Fuß committed Sep 23, 2019 355 356 `````` outputs=[] `````` Christian Fuß committed Aug 21, 2019 357 `````` if True: `````` Sebastian Nickels committed Sep 06, 2019 358 `````` predictions_ = mx.nd.zeros((batch_size, 1000,), ctx=mx_context) `````` Sebastian Nickels committed Aug 12, 2019 359 360 `````` predictions_ = self._networks[0](data_) `````` Christian Fuß committed Sep 23, 2019 361 `````` outputs.append(predictions_) `````` 362 `````` `````` Christian Fuß committed Sep 09, 2019 363 `````` predictions = [] `````` Christian Fuß committed Sep 23, 2019 364 `````` for output_name in outputs: `````` Christian Fuß committed Sep 09, 2019 365 366 367 368 369 `````` if mx.nd.shape_array(output_name).size > 1: predictions.append(mx.nd.argmax(output_name, axis=1)) #ArgMax already applied else: predictions.append(output_name) `````` Sebastian Nickels committed May 26, 2019 370 `````` `````` Sebastian Nickels committed Jun 06, 2019 371 `````` metric.update(preds=predictions, labels=labels) `````` Nicola Gatto committed Apr 08, 2019 372 373 374 375 `````` test_metric_score = metric.get()[1] logging.info("Epoch[%d] Train: %f, Test: %f" % (epoch, train_metric_score, test_metric_score)) `````` Christian Fuß committed Aug 28, 2019 376 `````` `````` Nicola Gatto committed Apr 08, 2019 377 `````` if (epoch - begin_epoch) % checkpoint_period == 0: `````` Sebastian Nickels committed Jun 21, 2019 378 379 `````` for i, network in self._networks.items(): network.save_parameters(self.parameter_path(i) + '-' + str(epoch).zfill(4) + '.params') `````` Nicola Gatto committed Apr 08, 2019 380 `````` `````` Sebastian Nickels committed Jun 21, 2019 381 382 383 `````` for i, network in self._networks.items(): network.save_parameters(self.parameter_path(i) + '-' + str(num_epoch + begin_epoch).zfill(4) + '.params') network.export(self.parameter_path(i) + '_newest', epoch=0) `````` Nicola Gatto committed Apr 08, 2019 384 `````` `````` Sebastian Nickels committed Jun 21, 2019 385 386 `````` def parameter_path(self, index): return self._net_creator._model_dir_ + self._net_creator._model_prefix_ + '_' + str(index)``````