Computes and stores the minimum loss value and its epoch index
| 41 | |
| 42 | |
| 43 | class RecorderMeter(object): |
| 44 | """Computes and stores the minimum loss value and its epoch index""" |
| 45 | |
| 46 | def __init__(self, total_epoch): |
| 47 | self.reset(total_epoch) |
| 48 | |
| 49 | def reset(self, total_epoch): |
| 50 | assert total_epoch > 0 |
| 51 | self.total_epoch = total_epoch |
| 52 | self.current_epoch = 0 |
| 53 | self.epoch_losses = np.zeros((self.total_epoch, 2), |
| 54 | dtype=np.float32) # [epoch, train/val] |
| 55 | self.epoch_losses = self.epoch_losses - 1 |
| 56 | |
| 57 | self.epoch_accuracy = np.zeros((self.total_epoch, 2), |
| 58 | dtype=np.float32) # [epoch, train/val] |
| 59 | self.epoch_accuracy = self.epoch_accuracy |
| 60 | |
| 61 | def update(self, idx, train_loss, train_acc, val_loss, val_acc): |
| 62 | assert idx >= 0 and idx < self.total_epoch, 'total_epoch : {} , but update with the {} index'.format( |
| 63 | self.total_epoch, idx) |
| 64 | self.epoch_losses[idx, 0] = train_loss |
| 65 | self.epoch_losses[idx, 1] = val_loss |
| 66 | self.epoch_accuracy[idx, 0] = train_acc |
| 67 | self.epoch_accuracy[idx, 1] = val_acc |
| 68 | self.current_epoch = idx + 1 |
| 69 | # return self.max_accuracy(False) == val_acc |
| 70 | |
| 71 | def max_accuracy(self, istrain): |
| 72 | if self.current_epoch <= 0: return 0 |
| 73 | if istrain: return self.epoch_accuracy[:self.current_epoch, 0].max() |
| 74 | else: return self.epoch_accuracy[:self.current_epoch, 1].max() |
| 75 | |
| 76 | def plot_curve(self, save_path): |
| 77 | title = 'the accuracy/loss curve of train/val' |
| 78 | dpi = 80 |
| 79 | width, height = 1200, 800 |
| 80 | legend_fontsize = 10 |
| 81 | scale_distance = 48.8 |
| 82 | figsize = width / float(dpi), height / float(dpi) |
| 83 | |
| 84 | fig = plt.figure(figsize=figsize) |
| 85 | x_axis = np.array([i for i in range(self.total_epoch)]) # epochs |
| 86 | y_axis = np.zeros(self.total_epoch) |
| 87 | |
| 88 | plt.xlim(0, self.total_epoch) |
| 89 | plt.ylim(0, 1) |
| 90 | interval_y = 0.05 |
| 91 | interval_x = 5 |
| 92 | plt.xticks(np.arange(0, self.total_epoch + interval_x, interval_x)) |
| 93 | plt.yticks(np.arange(0, 1 + interval_y, interval_y)) |
| 94 | plt.grid() |
| 95 | plt.title(title, fontsize=20) |
| 96 | plt.xlabel('the training epoch', fontsize=16) |
| 97 | plt.ylabel('accuracy', fontsize=16) |
| 98 | |
| 99 | y_axis[:] = self.epoch_accuracy[:, 0] |
| 100 | plt.plot(x_axis, |