|
| 1 | +import os |
| 2 | +import numpy as np |
| 3 | +import errno |
| 4 | +import torchvision.utils as vutils |
| 5 | +from tensorboardX import SummaryWriter |
| 6 | +from IPython import display |
| 7 | +from matplotlib import pyplot as plt |
| 8 | +import torch |
| 9 | + |
| 10 | +''' |
| 11 | + TensorBoard Data will be stored in './runs' path |
| 12 | +''' |
| 13 | + |
| 14 | +class Logger: |
| 15 | + def __init__(self, model_name, data_name): |
| 16 | + self.model_name = model_name |
| 17 | + self.data_name = data_name |
| 18 | + |
| 19 | + self.comment = '{}_{}'.format(model_name, data_name) |
| 20 | + self.data_subdir = '{}/{}'.format(model_name, data_name) |
| 21 | + |
| 22 | + # TensorBoard |
| 23 | + self.writer = SummaryWriter(comment=self.comment) |
| 24 | + |
| 25 | + def log(self, d_error, g_error, epoch, n_batch, num_batches): |
| 26 | + |
| 27 | + # var_class = torch.autograd.variable.Variable |
| 28 | + if isinstance(d_error, torch.autograd.Variable): |
| 29 | + d_error = d_error.data.cpu().numpy() |
| 30 | + if isinstance(g_error, torch.autograd.Variable): |
| 31 | + g_error = g_error.data.cpu().numpy() |
| 32 | + |
| 33 | + step = Logger._step(epoch, n_batch, num_batches) |
| 34 | + self.writer.add_scalar( |
| 35 | + '{}/D_error'.format(self.comment), d_error, step) |
| 36 | + self.writer.add_scalar( |
| 37 | + '{}/G_error'.format(self.comment), g_error, step) |
| 38 | + |
| 39 | + def log_images(self, images, num_images, epoch, n_batch, num_batches, format='NCHW', normalize=True): |
| 40 | + ''' |
| 41 | + input images are expected in format (NCHW) |
| 42 | + ''' |
| 43 | + if type(images) == np.ndarray: |
| 44 | + images = torch.from_numpy(images) |
| 45 | + |
| 46 | + if format=='NHWC': |
| 47 | + images = images.transpose(1,3) |
| 48 | + |
| 49 | + |
| 50 | + step = Logger._step(epoch, n_batch, num_batches) |
| 51 | + img_name = '{}/images{}'.format(self.comment, '') |
| 52 | + |
| 53 | + # Make horizontal grid from image tensor |
| 54 | + horizontal_grid = vutils.make_grid( |
| 55 | + images, normalize=normalize, scale_each=True) |
| 56 | + # Make vertical grid from image tensor |
| 57 | + nrows = int(np.sqrt(num_images)) |
| 58 | + grid = vutils.make_grid( |
| 59 | + images, nrow=nrows, normalize=True, scale_each=True) |
| 60 | + |
| 61 | + # Add horizontal images to tensorboard |
| 62 | + self.writer.add_image(img_name, horizontal_grid, step) |
| 63 | + |
| 64 | + # Save plots |
| 65 | + self.save_torch_images(horizontal_grid, grid, epoch, n_batch) |
| 66 | + |
| 67 | + def save_torch_images(self, horizontal_grid, grid, epoch, n_batch, plot_horizontal=True): |
| 68 | + out_dir = './data/images/{}'.format(self.data_subdir) |
| 69 | + Logger._make_dir(out_dir) |
| 70 | + |
| 71 | + # Plot and save horizontal |
| 72 | + fig = plt.figure(figsize=(16, 16)) |
| 73 | + plt.imshow(np.moveaxis(horizontal_grid.numpy(), 0, -1)) |
| 74 | + plt.axis('off') |
| 75 | + if plot_horizontal: |
| 76 | + display.display(plt.gcf()) |
| 77 | + self._save_images(fig, epoch, n_batch, 'hori') |
| 78 | + plt.close() |
| 79 | + |
| 80 | + # Save squared |
| 81 | + fig = plt.figure() |
| 82 | + plt.imshow(np.moveaxis(grid.numpy(), 0, -1)) |
| 83 | + plt.axis('off') |
| 84 | + self._save_images(fig, epoch, n_batch) |
| 85 | + plt.close() |
| 86 | + |
| 87 | + def _save_images(self, fig, epoch, n_batch, comment=''): |
| 88 | + out_dir = './data/images/{}'.format(self.data_subdir) |
| 89 | + Logger._make_dir(out_dir) |
| 90 | + fig.savefig('{}/{}_epoch_{}_batch_{}.png'.format( |
| 91 | + out_dir, comment, epoch, n_batch)) |
| 92 | + |
| 93 | + def display_status(self, epoch, num_epochs, n_batch, num_batches, d_error, g_error, d_pred_real, d_pred_fake): |
| 94 | + |
| 95 | + # var_class = torch.autograd.variable.Variable |
| 96 | + if isinstance(d_error, torch.autograd.Variable): |
| 97 | + d_error = d_error.data.cpu().numpy() |
| 98 | + if isinstance(g_error, torch.autograd.Variable): |
| 99 | + g_error = g_error.data.cpu().numpy() |
| 100 | + if isinstance(d_pred_real, torch.autograd.Variable): |
| 101 | + d_pred_real = d_pred_real.data |
| 102 | + if isinstance(d_pred_fake, torch.autograd.Variable): |
| 103 | + d_pred_fake = d_pred_fake.data |
| 104 | + |
| 105 | + |
| 106 | + print('Epoch: [{}/{}], Batch Num: [{}/{}]'.format( |
| 107 | + epoch,num_epochs, n_batch, num_batches)) |
| 108 | + print('Discriminator Loss: {:.4f}, Generator Loss: {:.4f}'.format(d_error, g_error)) |
| 109 | + print('D(x): {:.4f}, D(G(z)): {:.4f}'.format(d_pred_real.mean(), d_pred_fake.mean())) |
| 110 | + |
| 111 | + def save_models(self, generator, discriminator, epoch): |
| 112 | + out_dir = './data/models/{}'.format(self.data_subdir) |
| 113 | + Logger._make_dir(out_dir) |
| 114 | + torch.save( |
| 115 | + generator.state_dict(), |
| 116 | + '{}/G_epoch_{}'.format(out_dir, epoch)) |
| 117 | + torch.save( |
| 118 | + discriminator.state_dict(), |
| 119 | + '{}/D_epoch_{}'.format(out_dir, epoch)) |
| 120 | + |
| 121 | + def close(self): |
| 122 | + self.writer.close() |
| 123 | + |
| 124 | + # Private Functionality |
| 125 | + |
| 126 | + @staticmethod |
| 127 | + def _step(epoch, n_batch, num_batches): |
| 128 | + return epoch * num_batches + n_batch |
| 129 | + |
| 130 | + @staticmethod |
| 131 | + def _make_dir(directory): |
| 132 | + try: |
| 133 | + os.makedirs(directory) |
| 134 | + except OSError as e: |
| 135 | + if e.errno != errno.EEXIST: |
| 136 | + raise |
0 commit comments