code stringlengths 17 6.64M |
|---|
class UnpairedMaskDataset(data.Dataset):
'A dataset class for loading images within a single folder\n '
def __init__(self, opt, im_path, label, is_val=False):
'Initialize this dataset class.\n\n Parameters:\n opt -- experiment options\n im_path -- path to folder of ima... |
class Struct():
def __init__(self, **entries):
self.__dict__.update(entries)
|
def find_model_using_name(model_name):
model_filename = (('models.' + model_name) + '_model')
modellib = importlib.import_module(model_filename)
model = None
target_model_name = (model_name.replace('_', '') + 'model')
for (name, cls) in modellib.__dict__.items():
if ((name.lower() == targe... |
def get_option_setter(model_name):
model_class = find_model_using_name(model_name)
return model_class.modify_commandline_options
|
def create_model(opt, **kwargs):
model = find_model_using_name(opt.model)
instance = model(opt, **kwargs)
print(('model [%s] was created' % instance.name()))
return instance
|
class BaseModel():
@staticmethod
def modify_commandline_options(parser):
networks.modify_commandline_options(parser)
return parser
def __init__(self, opt):
self.opt = opt
self.gpu_ids = opt.gpu_ids
self.isTrain = opt.isTrain
self.device = (torch.device('cu... |
def compute_mhsa(q, k, v, scale_factor=1, mask=None):
scaled_dot_prod = (torch.einsum('... i d , ... j d -> ... i j', q, k) * scale_factor)
if (mask is not None):
assert (mask.shape == scaled_dot_prod.shape[2:])
scaled_dot_prod = scaled_dot_prod.masked_fill(mask, (- np.inf))
attention = to... |
class MultiHeadSelfAttention(nn.Module):
def __init__(self, dim, heads=8, dim_head=None):
"\n Implementation of multi-head attention layer of the original transformer model.\n einsum and einops.rearrange is used whenever possible\n Args:\n dim: token's dimension, i.e. word... |
class NLBlockND(nn.Module):
def __init__(self, in_channels=256):
"Implementation of Non-Local Block with 4 different pairwise functions but doesn't include subsampling trick\n args:\n in_channels: original channel size (1024 in the paper)\n inter_channels: channel size inside... |
def make_patch_resnet(depth, layername, num_classes=2, extra_output=None):
def change_out(layers):
(ind, layer) = [(i, l) for (i, (n, l)) in enumerate(layers) if (n == layername)][0]
if layername.startswith('layer'):
bn = list(layer.modules())[((- 1) if (depth < 50) else (- 2))]
... |
def make_patch_xceptionnet(layername, num_classes=2, extra_output=None):
def change_out(layers):
(ind, layer) = [(i, l) for (i, (n, l)) in enumerate(layers) if (n == layername)][0]
if layername.startswith('block'):
module_list = list(layer.modules())
bn = module_list[(- 1)... |
def make_pcl(backbone='xception', layername='block3', input_size=128):
if (backbone == 'xception'):
channels = [128, 256, 728, 728, 728, 728, 728, 728, 728, 728, 728, 1024]
(b1, b2, b3, b12) = (int((input_size / 4)), int((input_size / 8)), int((input_size / 16)), int((input_size / 32)))
ou... |
def make_xceptionnet_long():
from . import xception
def change_out(layers):
channels = [3, 32, 64, 128, 256, 728, 728, 728, 728, 728, 728, 728, 728, 728, 1024, 1536, 2048]
(ind, layer) = [(i, l) for (i, (n, l)) in enumerate(layers) if (n == 'block2')][0]
new_layers = [('pblock3', xcep... |
class CustomResNet(nn.Module):
"\n Customizable ResNet, compatible with pytorch's resnet, but:\n * The top-level sequence of modules can be modified to add\n or remove or alter layers.\n * Extra outputs can be produced, to allow backprop and access\n to internal features.\n * Pooling is... |
class CustomXceptionNet(nn.Module):
'\n Customizable Xceptionnet, compatible with https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/xception.py\n but:\n * The top-level sequence of modules can be modified to add\n or remove or alter layers.\n * Extra outpu... |
class Vectorize(nn.Module):
def __init__(self):
super(Vectorize, self).__init__()
def forward(self, x):
x = x.view(x.size(0), int(numpy.prod(x.size()[1:])))
return x
|
class GlobalAveragePool2d(nn.Module):
def __init__(self):
super(GlobalAveragePool2d, self).__init__()
def forward(self, x):
x = torch.mean(x.view(x.size(0), x.size(1), (- 1)), dim=2)
return x
|
def get_scheduler(optimizer, opt):
if (opt.lr_policy == 'plateau'):
scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', factor=0.1, threshold=0.0001, patience=opt.patience, eps=1e-06)
elif (opt.lr_policy == 'constant'):
scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='... |
def init_weights(net, init_type='xavier', gain=0.02):
def init_func(m):
classname = m.__class__.__name__
if (hasattr(m, 'weight') and ((classname.find('Conv') != (- 1)) or (classname.find('Linear') != (- 1)))):
if (init_type == 'normal'):
init.normal_(m.weight.data, 0.... |
def init_net(net, init_type='xavier', gpu_ids=[]):
if (len(gpu_ids) > 0):
assert torch.cuda.is_available()
net.to(gpu_ids[0])
net = torch.nn.DataParallel(net, gpu_ids)
if (init_type is None):
return net
init_weights(net, init_type)
return net
|
def modify_commandline_options(parser):
(opt, _) = parser.parse_known_args()
if ('xception' in opt.which_model_netD):
parser.set_defaults(loadSize=333, fineSize=299)
elif ('resnet' in opt.which_model_netD):
parser.set_defaults(loadSize=256, fineSize=224)
else:
raise NotImplemen... |
def define_D(which_model_netD, init_type, gpu_ids=[]):
if ('resnet' in which_model_netD):
from torchvision.models import resnet
model = getattr(resnet, which_model_netD)
netD = model(pretrained=False, num_classes=2)
elif ('xception' in which_model_netD):
from . import xception
... |
def define_patch_D(which_model_netD, init_type, gpu_ids=[]):
if which_model_netD.startswith('resnet'):
from . import customnet
splits = which_model_netD.split('_')
depth = int(splits[0][6:])
layer = splits[1]
if (len(splits) == 2):
netD = customnet.make_patch_re... |
def define_PCL(which_model_netD, init_type, gpu_ids=[], input_size=128):
if which_model_netD.startswith('resnet'):
from . import customnet
backbone = which_model_netD.split('_')[0]
layer = which_model_netD.split('_')[1]
(netPCL, out_ch) = customnet.make_pcl(backbone=backbone, layer... |
class WideNet(nn.Module):
def __init__(self, kernel_size=7, dilation=1):
super().__init__()
sequence = [nn.Conv2d(3, 256, kernel_size=kernel_size, dilation=dilation, stride=2, padding=(kernel_size // 2), bias=False), nn.BatchNorm2d(256), nn.ReLU(inplace=True), nn.MaxPool2d(3, stride=2, padding=1)... |
class SeparableConv2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0, dilation=1, bias=False):
super(SeparableConv2d, self).__init__()
self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size, stride, padding, dilation, groups=in_channels, bias=bi... |
class PixelBlock(nn.Module):
def __init__(self, in_filters, out_filters, reps, strides=1, start_with_relu=True, grow_first=True):
super(PixelBlock, self).__init__()
assert (strides == 1)
if ((out_filters != in_filters) or (strides != 1)):
self.skip = nn.Conv2d(in_filters, out_... |
class Block(nn.Module):
def __init__(self, in_filters, out_filters, reps, strides=1, start_with_relu=True, grow_first=True):
super(Block, self).__init__()
if ((out_filters != in_filters) or (strides != 1)):
self.skip = nn.Conv2d(in_filters, out_filters, 1, stride=strides, bias=False)
... |
class Xception(nn.Module):
'\n Xception optimized for the ImageNet dataset, as specified in\n https://arxiv.org/pdf/1610.02357.pdf\n '
def __init__(self, num_classes=1000):
' Constructor\n Args:\n num_classes: number of classes\n '
super(Xception, self).__ini... |
def xception(num_classes=1000, pretrained='imagenet'):
model = Xception(num_classes=num_classes)
if pretrained:
settings = pretrained_settings['xception'][pretrained]
model = Xception(num_classes=num_classes)
pretrained_state = model_zoo.load_url(settings['url'])
model_state = ... |
class BaseOptions(options.Options):
def __init__(self, print_opt=True):
options.Options.__init__(self)
self.isTrain = False
self.print_opt = print_opt
parser = self.parser
parser.add_argument('--model', type=str, default='basic_discriminator', help='chooses which model to ... |
class TestOptions(BaseOptions):
def __init__(self):
BaseOptions.__init__(self, print_opt=False)
parser = self.parser
parser.add_argument('--train_config', type=argparse.FileType(mode='r'), required=True, help='config file saved from model training')
parser.add_argument('--partitio... |
class TrainOptions(BaseOptions):
def __init__(self, print_opt=True):
BaseOptions.__init__(self, print_opt)
parser = self.parser
parser.add_argument('--display_freq', type=int, default=1000, help='frequency of showing training results visualization')
parser.add_argument('--print_fr... |
def train(opt):
torch.manual_seed(opt.seed)
if (opt.model == 'patch_inconsistency_discriminator'):
WITH_MASK = True
else:
WITH_MASK = False
if (not WITH_MASK):
dset = PairedDataset(opt, os.path.join(opt.real_im_path, 'train'), os.path.join(opt.fake_im_path, 'train'), with_mask=... |
def validate(model, opt):
logging.info('Starting evaluation loop ...')
model.reset()
assert (not model.net_D.training)
if (opt.model == 'patch_inconsistency_discriminator'):
WITH_MASK = True
else:
WITH_MASK = False
if (not WITH_MASK):
val_dset = PairedDataset(opt, os.pa... |
def train(opt):
torch.manual_seed(opt.seed)
dset = I2GDataset(opt, os.path.join(opt.real_im_path, 'train'))
dset.get32frames()
dl = DataLoader(dset, batch_size=opt.batch_size, num_workers=opt.nThreads, pin_memory=False, shuffle=True)
assert (opt.fake_class_id in [0, 1])
fake_label = opt.fake_c... |
def validate(model, opt):
logging.info('Starting evaluation loop ...')
model.reset()
assert (not model.net_D.training)
val_dset = I2GDataset(opt, os.path.join(opt.real_im_path, 'val'), is_val=True)
val_dset.get32frames()
val_dl = DataLoader(val_dset, batch_size=opt.batch_size, num_workers=opt.... |
class TqdmLoggingHandler(logging.Handler):
def __init__(self, level=logging.NOTSET):
super(self.__class__, self).__init__(level)
def emit(self, record):
try:
msg = self.format(record)
tqdm.tqdm.write(msg)
self.flush()
except (KeyboardInterrupt, Sys... |
class MultiLineFormatter(logging.Formatter):
def __init__(self, fmt=None, datefmt=None, style='%'):
assert (style == '%')
super(MultiLineFormatter, self).__init__(fmt, datefmt, style)
self.multiline_fmt = fmt
def format(self, record):
"\n This is mostly the same as log... |
def handle_exception(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
logging.error('Uncaught exception', exc_info=(exc_type, exc_value, exc_traceback))
|
def configure(logging_file, log_level=logging.INFO, level_prefix='', prefix='', write_to_stdout=True, append=True):
logging.getLogger().setLevel(logging.INFO)
sys.excepthook = handle_exception
handlers = []
if write_to_stdout:
handlers.append(TqdmLoggingHandler())
delayed_logging = []
... |
@contextlib.contextmanager
def disable(level):
prev_level = logging.getLogger().getEffectiveLevel()
logging.disable(level)
(yield)
logging.disable(prev_level)
|
class Options():
def __init__(self):
self.parser = parser = argparse.ArgumentParser()
self.parser.add_argument('config_file', nargs='?', type=argparse.FileType(mode='r'))
self.parser.add_argument('--overwrite_config', action='store_true', help='overwrite config files if they exist')
... |
def verbose(verbose):
'\n Sets default verbosity level. Set to True to see progress bars.\n '
global default_verbosity
default_verbosity = verbose
|
def post(**kwargs):
'\n When within a progress loop, pbar.post(k=str) will display\n the given k=str status on the right-hand-side of the progress\n status bar. If not within a visible progress bar, does nothing.\n '
innermost = innermost_tqdm()
if innermost:
innermost.set_postfix(**k... |
def desc(desc):
'\n When within a progress loop, pbar.desc(str) changes the\n left-hand-side description of the loop toe the given description.\n '
innermost = innermost_tqdm()
if innermost:
innermost.set_description(str(desc))
|
def descnext(desc):
'\n Called before starting a progress loop, pbar.descnext(str)\n sets the description text that will be used in the following loop.\n '
global next_description
if ((not default_verbosity) or (tqdm is None)):
return
next_description = desc
|
def print(*args):
'\n When within a progress loop, will print above the progress loop.\n '
global next_description
next_description = None
if default_verbosity:
msg = ' '.join((str(s) for s in args))
if (tqdm is None):
print(msg)
else:
tqdm.write(m... |
def tqdm_terminal(it, *args, **kwargs):
'\n Some settings for tqdm that make it run better in resizable terminals.\n '
return tqdm(it, *args, dynamic_ncols=True, ascii=True, leave=(not innermost_tqdm()), **kwargs)
|
def in_notebook():
'\n True if running inside a Jupyter notebook.\n '
try:
shell = get_ipython().__class__.__name__
if (shell == 'ZMQInteractiveShell'):
return True
elif (shell == 'TerminalInteractiveShell'):
return False
else:
return F... |
def innermost_tqdm():
'\n Returns the innermost active tqdm progress loop on the stack.\n '
if (hasattr(tqdm, '_instances') and (len(tqdm._instances) > 0)):
return max(tqdm._instances, key=(lambda x: x.pos))
else:
return None
|
def __call__(x, *args, **kwargs):
'\n Invokes a progress function that can wrap iterators to print\n progress messages, if verbose is True.\n \n If verbose is False or tqdm is unavailable, then a quiet\n non-printing identity function is used.\n\n verbose can also be set to a spefific progress fu... |
class CallableModule(types.ModuleType):
def __init__(self):
types.ModuleType.__init__(self, __name__)
self.__dict__.update(sys.modules[__name__].__dict__)
def __call__(self, x, *args, **kwargs):
return __call__(x, *args, **kwargs)
|
def exit_if_job_done(directory, redo=False, force=False, verbose=True):
if pidfile_taken(os.path.join(directory, 'lockfile.pid'), force=force, verbose=verbose):
sys.exit(0)
donefile = os.path.join(directory, 'done.txt')
if os.path.isfile(donefile):
with open(donefile) as f:
msg... |
def mark_job_done(directory):
with open(os.path.join(directory, 'done.txt'), 'w') as f:
f.write(('done by %d@%s %s at %s' % (os.getpid(), socket.gethostname(), os.getenv('STY', ''), time.strftime('%c'))))
|
def pidfile_taken(path, verbose=False, force=False):
"\n Usage. To grab an exclusive lock for the remaining duration of the\n current process (and exit if another process already has the lock),\n do this:\n\n if pidfile_taken('job_423/lockfile.pid', verbose=True):\n sys.exit(0)\n\n To do a ... |
def delete_pidfile(lockfile, path):
'\n Runs at exit after pidfile_taken succeeds.\n '
if (lockfile is not None):
try:
lockfile.close()
except:
pass
try:
os.unlink(path)
except:
pass
|
def blocks(obj, space=''):
return IPython.display.HTML(space.join(blocks_tags(obj)))
|
def rows(obj, space=''):
return IPython.display.HTML(space.join(rows_tags(obj)))
|
def rows_tags(obj):
if isinstance(obj, dict):
obj = obj.items()
results = []
results.append('<table style="display:inline-table">')
for row in obj:
results.append('<tr style="padding:0">')
for item in row:
results.append(('<td style="text-align:left; vertical-align:... |
def blocks_tags(obj):
results = []
if isinstance(obj, PIL.Image.Image):
results.append(pil_to_html(obj))
elif isinstance(obj, (str, int, float)):
results.append('<div>')
results.append(html_module.escape(str(obj)))
results.append('</div>')
elif isinstance(obj, IPython.d... |
def pil_to_b64(img, format='png'):
buffered = io.BytesIO()
img.save(buffered, format=format)
return base64.b64encode(buffered.getvalue()).decode('utf-8')
|
def pil_to_url(img, format='png'):
return ('data:image/%s;base64,%s' % (format, pil_to_b64(img, format)))
|
def pil_to_html(img, margin=1):
mattr = (' style="margin:%dpx"' % margin)
return ('<img src="%s"%s>' % (pil_to_url(img), mattr))
|
def a(x, cols=None):
global g_buffer
if (g_buffer is None):
g_buffer = []
g_buffer.append(x)
if ((cols is not None) and (len(g_buffer) >= cols)):
flush()
|
def reset():
global g_buffer
g_buffer = []
|
def flush(*args, **kwargs):
global g_buffer
if (g_buffer is not None):
x = g_buffer
g_buffer = None
display(blocks(x, *args, **kwargs))
|
def show(x=None, *args, **kwargs):
flush(*args, **kwargs)
if (x is not None):
display(blocks(x, *args, **kwargs))
|
class CallableModule(types.ModuleType):
def __init__(self):
types.ModuleType.__init__(self, __name__)
self.__dict__.update(sys.modules[__name__].__dict__)
def __call__(self, x=None, *args, **kwargs):
show(x, *args, **kwargs)
|
class LinePlotter(object):
def __init__(self, writer, tag):
self.writer = writer
self.tag = tag
def plot(self, x, data, walltime=None):
if (not hasattr(self, 'plot_data')):
self.plot_data = {'X': [], 'Y': []}
self.plot_data['X'].append(x)
self.plot_data['Y... |
class ImageGridPlotter(object):
def __init__(self, writer, ncols, grid=False):
self.ncols = ncols
self.writer = writer
self.grid = grid
def plot(self, visuals, niter=0):
ncols = self.ncols
ncols = min(ncols, len(visuals))
if self.grid:
images = []
... |
def remove_prefix(s, prefix):
if s.startswith(prefix):
s = s[len(prefix):]
return s
|
def get_subset_dict(in_dict, keys):
if len(keys):
subset = OrderedDict()
for key in keys:
subset[key] = in_dict[key]
else:
subset = in_dict
return subset
|
def datestring():
return time.strftime('%Y-%m-%d %H:%M:%S')
|
def format_str_one(v, float_prec=6, int_pad=1):
if (isinstance(v, torch.Tensor) and (v.numel() == 1)):
v = v.item()
if isinstance(v, float):
return (('{:.' + str(float_prec)) + 'f}').format(v)
if (isinstance(v, int) and int_pad):
return (('{:0' + str(int_pad)) + 'd}').format(v)
... |
def format_str(*args, format_opts={}, **kwargs):
ss = [format_str_one(arg, **format_opts) for arg in args]
for (k, v) in kwargs.items():
ss.append('{}: {}'.format(k, format_str_one(v, **format_opts)))
return '\t'.join(ss)
|
def complete_device(device):
if (not torch.cuda.is_available()):
return torch.device('cpu')
if (type(device) == str):
device = torch.device(device)
if ((device.type == 'cuda') and (device.index is None)):
return torch.device(device.type, torch.cuda.current_device())
return devi... |
def check_timestamp(checkpoint_path, timestamp_path):
" returns True if checkpoint_path timestamp is different\n from timestamp path or timestamp_path doesn't exist"
if (not os.path.isfile(timestamp_path)):
print('No timestamp found')
return True
newtime = os.path.getmtime(checkpoin... |
def update_timestamp(checkpoint_path, timestamp_path):
' write the last modified date of checkpoint_path to the\n the file timestamp_path '
newtime = os.path.getmtime(checkpoint_path)
newtime = datetime.fromtimestamp(newtime).strftime('%Y-%m-%d %H:%M:%S')
with open(timestamp_path, 'w') as f:
... |
class AverageMeter(object):
'Computes and stores the average and current value'
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += (val... |
class Visualizer():
def __init__(self, opt, loss_names, visual_names=None):
from . import tensorboard_utils as tb_utils
self.name = opt.name
self.opt = opt
self.visual_names = visual_names
tb_path = os.path.join('runs', self.name)
if os.path.isdir(tb_path):
... |
def init_matrix(data):
for i in range(len(data)):
data[i][0] = float('inf')
for i in range(len(data[0])):
data[0][i] = float('inf')
data[0][0] = 0
return data
|
def LpDist(time_pt_1, time_pt_2):
if ((type(time_pt_1) == int) and (type(time_pt_2) == int)):
return abs((time_pt_1 - time_pt_2))
else:
return sum(abs((time_pt_1 - time_pt_2)))
|
def TWED(t1, t2, lam, nu):
'"Requires: t1: multivariate time series in numpy matrix format. t2: multivariate time series in numpy matrix format. lam: penalty lambda parameter, nu: stiffness coefficient'
'Returns the TWED distance between the two time series. '
t1_data = t1
t2_data = t2
result = [(... |
class HyperParams():
def __init__(self):
pass
def get_uniwarp_config(self, argv):
config = {}
config['optimizer:num_epochs'] = 1000000
config['model:num_batch_pairs'] = 100
config['uniwarp:length'] = 1024
config['uniwarp:rnn_encoder_layers'] = [256, 128, 64]
... |
class Inference_Experiments():
def __init__(self, model_type, model_file, dataset_path):
self.model_type = model_type
self.model_file = model_file
self.dataset_path = dataset_path
hp = HyperParams()
self.config = hp.get_uniwarp_config(None)
self.ds = Dataset()
... |
class Optimizer():
def __init__(self, config, dataset, sim_model):
self.config = config
self.dataset = dataset
self.num_epochs = self.config['optimizer:num_epochs']
self.sim_model = sim_model
self.saver = tf.train.Saver(max_to_keep=100)
def optimize(self):
wit... |
class AbstractSimModel():
def __init__(self, config):
self.config = config
self.minus_one_constant = tf.constant((- 1.0), dtype=tf.float32)
self.sequence_length = self.config['uniwarp:length']
self.X_batch = tf.placeholder(shape=((2 * self.config['model:num_batch_pairs']), self.co... |
class BaseArgs():
'\n Arguments for data, model, and checkpoints.\n '
def __init__(self):
(self.is_train, self.split) = (None, None)
self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
self.parser.add_argument('--n_workers', type=int, defaul... |
class TestArgs(BaseArgs):
'\n Arguments for testing.\n '
def __init__(self):
super(TestArgs, self).__init__()
self.is_train = False
self.split = 'val'
self.parser.add_argument('--batch_size', type=int, default=1, help='batch size')
self.parser.add_argument('--which_e... |
class TrainArgs(BaseArgs):
'\n Arguments specific for training.\n '
def __init__(self):
super(TrainArgs, self).__init__()
self.is_train = True
self.split = 'train'
self.parser.add_argument('--batch_size', type=int, default=4, help='batch size per gpu')
self.parser.ad... |
def make_dataset(root, is_train):
if is_train:
folder = 'balls_n4_t60_ex50000'
else:
folder = 'balls_n4_t60_ex2000'
dataset = np.load(os.path.join(root, folder, 'dataset_info.npy'))
return dataset
|
class BouncingBalls(data.Dataset):
'\n Bouncing balls dataset.\n '
def __init__(self, root, is_train, n_frames_input, n_frames_output, image_size, transform=None, return_positions=False):
super(BouncingBalls, self).__init__()
self.n_frames = (n_frames_input + n_frames_output)
self.d... |
def get_data_loader(opt):
if (opt.dset_name == 'moving_mnist'):
transform = transforms.Compose([vtransforms.ToTensor()])
dset = MovingMNIST(opt.dset_path, opt.is_train, opt.n_frames_input, opt.n_frames_output, opt.num_objects, transform)
elif (opt.dset_name == 'bouncing_balls'):
transf... |
def get_model(opt):
if (opt.model == 'crop'):
model = DDPAE(opt)
else:
raise NotImplementedError
model.setup_training()
model.initialize_weights()
return model
|
class ImageDecoder(nn.Module):
'\n Decode images from vectors. Similar structure as DCGAN.\n '
def __init__(self, input_size, n_channels, ngf, n_layers, activation='tanh'):
super(ImageDecoder, self).__init__()
ngf = (ngf * (2 ** (n_layers - 2)))
layers = [nn.ConvTranspose2d(input_si... |
class ImageEncoder(nn.Module):
'\n Encodes images. Similar structure as DCGAN.\n '
def __init__(self, n_channels, output_size, ngf, n_layers):
super(ImageEncoder, self).__init__()
layers = [nn.Conv2d(n_channels, ngf, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, inplace=True)]
for i in ra... |
def build(is_train, tb_dir=None):
'\n Parse arguments, setup logger and tensorboardX directory.\n '
(opt, log) = (args.TrainArgs().parse() if is_train else args.TestArgs().parse())
os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpus
os.makedirs(opt.ckpt_path, exist_ok=True)
torch.manual_seed(666)
... |
class Logger():
'\n Logger to write logs to file.\n '
def __init__(self, ckpt_path, name='train'):
self.logger = logging.getLogger()
self.logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(message)s', datefmt=blue('[%Y-%m-%d,%H:%M:%S]'))
fh = logging.... |
def to_numpy(array):
'\n :param array: Variable, GPU tensor, or CPU tensor\n :return: numpy\n '
if isinstance(array, np.ndarray):
return array
if isinstance(array, torch.autograd.Variable):
array = array.data
if array.is_cuda:
array = array.cpu()
return array.numpy()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.