code stringlengths 17 6.64M |
|---|
def create_model(opt):
"Create a model given the option.\n This function warps the class CustomDatasetDataLoader.\n This is the main interface between this package and 'train.py'/'test.py'\n Example:\n >>> from models import create_model\n >>> model = create_model(opt)\n "
model = fi... |
class BaseModel(ABC):
'This class is an abstract base class (ABC) for models.\n To create a subclass, you need to implement the following five functions:\n -- <__init__>: initialize the class; first call BaseModel.__init__(self, opt).\n -- <set_input>: unp... |
class DivCo2Model(BaseModel):
@staticmethod
def modify_commandline_options(parser, is_train=True):
return parser
def __init__(self, opt):
if opt.isTrain:
assert ((opt.batch_size % 2) == 0)
BaseModel.__init__(self, opt)
self.nz = 8
self.loss_names = ['G... |
class DivCoModel(BaseModel):
@staticmethod
def modify_commandline_options(parser, is_train=True):
return parser
def __init__(self, opt):
if opt.isTrain:
assert ((opt.batch_size % 2) == 0)
BaseModel.__init__(self, opt)
self.nz = 8
self.loss_names = ['G_... |
def init_weights(net, init_type='normal', init_gain=0.02):
"Initialize network weights.\n Parameters:\n net (network) -- network to be initialized\n init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal\n init_gain (float) -- scaling factor fo... |
def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]):
'Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights\n Parameters:\n net (network) -- the network to be initialized\n init_type (str) -- the name of an initializatio... |
def get_scheduler(optimizer, opt):
"Return a learning rate scheduler\n Parameters:\n optimizer -- the optimizer of the network\n opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions.\u3000\n opt.lr_policy is the name of... |
def get_norm_layer(norm_type='instance'):
'Return a normalization layer\n Parameters:\n norm_type (str) -- the name of the normalization layer: batch | instance | none\n For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev).\n For InstanceNorm, we do not use ... |
def get_non_linearity(layer_type='relu'):
if (layer_type == 'relu'):
nl_layer = functools.partial(nn.ReLU, inplace=True)
elif (layer_type == 'lrelu'):
nl_layer = functools.partial(nn.LeakyReLU, negative_slope=0.2, inplace=True)
elif (layer_type == 'elu'):
nl_layer = functools.parti... |
def define_G(input_nc, output_nc, nz, ngf, netG='unet_128', norm='batch', nl='relu', use_dropout=False, init_type='xavier', init_gain=0.02, gpu_ids=[], where_add='input', upsample='bilinear'):
net = None
norm_layer = get_norm_layer(norm_type=norm)
nl_layer = get_non_linearity(layer_type=nl)
if (nz == ... |
def define_D(input_nc, ndf, netD, norm='batch', nl='lrelu', init_type='xavier', init_gain=0.02, num_Ds=1, gpu_ids=[]):
net = None
norm_layer = get_norm_layer(norm_type=norm)
nl = 'lrelu'
nl_layer = get_non_linearity(layer_type=nl)
if (netD == 'basic_128'):
net = D_NLayers(input_nc, ndf, n_... |
def define_E(input_nc, output_nc, ndf, netE, norm='batch', nl='lrelu', init_type='xavier', init_gain=0.02, gpu_ids=[], vaeLike=False):
net = None
norm_layer = get_norm_layer(norm_type=norm)
nl = 'lrelu'
nl_layer = get_non_linearity(layer_type=nl)
if (netE == 'resnet_128'):
net = E_ResNet(i... |
class D_NLayersMulti(nn.Module):
def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d, num_D=1):
super(D_NLayersMulti, self).__init__()
self.num_D = num_D
if (num_D == 1):
layers = self.get_layers(input_nc, ndf, n_layers, norm_layer)
self.mode... |
class D_NLayers(nn.Module):
'Defines a PatchGAN discriminator'
def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d):
'Construct a PatchGAN discriminator\n Parameters:\n input_nc (int) -- the number of channels in input images\n ndf (int) -- t... |
class RecLoss(nn.Module):
def __init__(self, use_L2=True):
super(RecLoss, self).__init__()
self.use_L2 = use_L2
def __call__(self, input, target, batch_mean=True):
if self.use_L2:
diff = ((input - target) ** 2)
else:
diff = torch.abs((input - target))
... |
class GANLoss(nn.Module):
'Define different GAN objectives.\n\n The GANLoss class abstracts away the need to create the target label tensor\n that has the same size as the input.\n '
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):
' Initialize the GANLoss class.\n... |
def cal_gradient_penalty(netD, real_data, fake_data, device, type='mixed', constant=1.0, lambda_gp=10.0):
"Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028\n Arguments:\n netD (network) -- discriminator network\n real_data (tensor array) ... |
class G_Unet_add_input(nn.Module):
def __init__(self, input_nc, output_nc, nz, num_downs, ngf=64, norm_layer=None, nl_layer=None, use_dropout=False, upsample='basic'):
super(G_Unet_add_input, self).__init__()
self.nz = nz
max_nchn = 8
unet_block = UnetBlock((ngf * max_nchn), (ngf ... |
def upsampleLayer(inplanes, outplanes, upsample='basic', padding_type='zero'):
if (upsample == 'basic'):
upconv = [nn.ConvTranspose2d(inplanes, outplanes, kernel_size=4, stride=2, padding=1)]
elif (upsample == 'bilinear'):
upconv = [nn.Upsample(scale_factor=2, mode='bilinear'), nn.ReflectionPa... |
class UnetBlock(nn.Module):
def __init__(self, input_nc, outer_nc, inner_nc, submodule=None, outermost=False, innermost=False, norm_layer=None, nl_layer=None, use_dropout=False, upsample='basic', padding_type='zero'):
super(UnetBlock, self).__init__()
self.outermost = outermost
p = 0
... |
def conv3x3(in_planes, out_planes):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=1, padding=1, bias=True)
|
def upsampleConv(inplanes, outplanes, kw, padw):
sequence = []
sequence += [nn.Upsample(scale_factor=2, mode='nearest')]
sequence += [nn.Conv2d(inplanes, outplanes, kernel_size=kw, stride=1, padding=padw, bias=True)]
return nn.Sequential(*sequence)
|
def meanpoolConv(inplanes, outplanes):
sequence = []
sequence += [nn.AvgPool2d(kernel_size=2, stride=2)]
sequence += [nn.Conv2d(inplanes, outplanes, kernel_size=1, stride=1, padding=0, bias=True)]
return nn.Sequential(*sequence)
|
def convMeanpool(inplanes, outplanes):
sequence = []
sequence += [conv3x3(inplanes, outplanes)]
sequence += [nn.AvgPool2d(kernel_size=2, stride=2)]
return nn.Sequential(*sequence)
|
class BasicBlockUp(nn.Module):
def __init__(self, inplanes, outplanes, norm_layer=None, nl_layer=None):
super(BasicBlockUp, self).__init__()
layers = []
if (norm_layer is not None):
layers += [norm_layer(inplanes)]
layers += [nl_layer()]
layers += [upsampleConv... |
class BasicBlock(nn.Module):
def __init__(self, inplanes, outplanes, norm_layer=None, nl_layer=None):
super(BasicBlock, self).__init__()
layers = []
if (norm_layer is not None):
layers += [norm_layer(inplanes)]
layers += [nl_layer()]
layers += [conv3x3(inplanes... |
class E_ResNet(nn.Module):
def __init__(self, input_nc=3, output_nc=1, ndf=64, n_blocks=4, norm_layer=None, nl_layer=None, vaeLike=False):
super(E_ResNet, self).__init__()
self.vaeLike = vaeLike
max_ndf = 4
conv_layers = [nn.Conv2d(input_nc, ndf, kernel_size=4, stride=2, padding=1... |
class G_Unet_add_all(nn.Module):
def __init__(self, input_nc, output_nc, nz, num_downs, ngf=64, norm_layer=None, nl_layer=None, use_dropout=False, upsample='basic'):
super(G_Unet_add_all, self).__init__()
self.nz = nz
unet_block = UnetBlock_with_z((ngf * 8), (ngf * 8), (ngf * 8), nz, None... |
class UnetBlock_with_z(nn.Module):
def __init__(self, input_nc, outer_nc, inner_nc, nz=0, submodule=None, outermost=False, innermost=False, norm_layer=None, nl_layer=None, use_dropout=False, upsample='basic', padding_type='zero'):
super(UnetBlock_with_z, self).__init__()
p = 0
downconv = ... |
class E_NLayers(nn.Module):
def __init__(self, input_nc, output_nc=1, ndf=64, n_layers=3, norm_layer=None, nl_layer=None, vaeLike=False):
super(E_NLayers, self).__init__()
self.vaeLike = vaeLike
(kw, padw) = (4, 1)
sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, pad... |
class BaseOptions():
def __init__(self):
self.initialized = False
def initialize(self, parser):
'This class defines options used during both training and test time.\n\n It also implements several helper functions such as parsing, printing, and saving the options.\n It also gath... |
class TestOptions(BaseOptions):
def initialize(self, parser):
BaseOptions.initialize(self, parser)
parser.add_argument('--results_dir', type=str, default='../results/', help='saves results here.')
parser.add_argument('--phase', type=str, default='val', help='train, val, test, etc')
... |
class TrainOptions(BaseOptions):
def initialize(self, parser):
BaseOptions.initialize(self, parser)
parser.add_argument('--display_freq', type=int, default=400, help='frequency of showing training results on screen')
parser.add_argument('--display_ncols', type=int, default=4, help='if pos... |
class HTML():
"This HTML class allows us to save images and write texts into a single HTML file.\n\n It consists of functions such as <add_header> (add a text header to the HTML file),\n <add_images> (add a row of images to the HTML file), and <save> (save the HTML to the disk).\n It is based on Pytho... |
def save_images(webpage, images, names, image_path, aspect_ratio=1.0, width=256):
"Save images to the disk.\n Parameters:\n webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details)\n images (numpy array list) -- a list of numpy array that stores ... |
class Visualizer():
"This class includes several functions that can display/save images and print/save logging information.\n It uses a Python library 'visdom' for display, and a Python library 'dominate' (wrapped in 'HTML') for creating HTML files with images.\n "
def __init__(self, opt):
'Ini... |
class generator(nn.Module):
def __init__(self, opts, d=128):
super(generator, self).__init__()
self.deconv1 = nn.ConvTranspose2d((opts.nz + opts.class_num), (d * 4), 4, 1, 0)
self.deconv1_bn = nn.BatchNorm2d((d * 4))
self.relu1 = nn.ReLU()
self.deconv2 = nn.ConvTranspose2d... |
class discriminator(nn.Module):
def __init__(self, opts, d=128):
super(discriminator, self).__init__()
self.conv1 = nn.Conv2d((3 + opts.class_num), d, 4, 2, 1)
self.lrelu1 = nn.LeakyReLU(0.2)
self.conv2 = nn.Conv2d(d, (d * 2), 4, 2, 1)
self.conv2_bn = nn.BatchNorm2d((d * 2... |
def gaussian_weights_init(m):
classname = m.__class__.__name__
if ((classname.find('Conv') != (- 1)) and (classname.find('Conv') == 0)):
m.weight.data.normal_(0.0, 0.02)
|
class BaseOptions():
def __init__(self):
self.parser = argparse.ArgumentParser()
self.parser.add_argument('--dataroot', type=str, required=True, help='path of data')
self.parser.add_argument('--img_size', type=int, default=32, help='resized image size for training')
self.parser.ad... |
class TrainOptions(BaseOptions):
def __init__(self):
super(TrainOptions, self).__init__()
self.parser.add_argument('--phase', type=str, default='train', help='phase for dataloading')
self.parser.add_argument('--batch_size', type=int, default=32, help='batch size')
self.parser.add_... |
class TestOptions(BaseOptions):
def __init__(self):
super(TestOptions, self).__init__()
self.parser.add_argument('--phase', type=str, default='test', help='phase for dataloading')
self.parser.add_argument('--num', type=int, default=5, help='number of outputs per image')
self.parse... |
def tensor2img(img):
img = img[0].cpu().float().numpy()
if (img.shape[0] == 1):
img = np.tile(img, (3, 1, 1))
img = (((np.transpose(img, (1, 2, 0)) + 1) / 2.0) * 255.0)
return img.astype(np.uint8)
|
def save_img(img, name, path):
if (not os.path.exists(path)):
os.mkdir(path)
img = tensor2img(img)
img = Image.fromarray(img)
img.save(os.path.join(path, (name + '.png')))
|
def save_imgs(imgs, names, path):
if (not os.path.exists(path)):
os.mkdir(path)
for (img, name) in zip(imgs, names):
img = tensor2img(img)
img = Image.fromarray(img)
img.save(os.path.join(path, (name + '.png')))
|
class Saver():
def __init__(self, opts):
self.display_dir = os.path.join(opts.display_dir, opts.name)
self.model_dir = os.path.join(opts.result_dir, opts.name)
self.image_dir = os.path.join(self.model_dir, 'images')
self.display_freq = opts.display_freq
self.img_save_freq ... |
def main():
parser = TestOptions()
opts = parser.parse()
print('\n--- load dataset ---')
dataset = torchvision.datasets.CIFAR10(opts.dataroot, train=False, download=True, transform=transforms.Compose([transforms.Resize(opts.img_size), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, ... |
def main():
parser = TrainOptions()
opts = parser.parse()
print('\n--- load dataset ---')
os.makedirs(opts.dataroot, exist_ok=True)
dataset = torchvision.datasets.CIFAR10(opts.dataroot, train=True, download=True, transform=transforms.Compose([transforms.Resize(opts.img_size), transforms.ToTensor()... |
class dataset_single(data.Dataset):
def __init__(self, opts, setname, input_dim):
self.dataroot = opts.dataroot
images = os.listdir(os.path.join(self.dataroot, (opts.phase + setname)))
self.img = [os.path.join(self.dataroot, (opts.phase + setname), x) for x in images]
self.size = ... |
class dataset_unpair(data.Dataset):
def __init__(self, opts):
self.dataroot = opts.dataroot
images_A = os.listdir(os.path.join(self.dataroot, (opts.phase + 'A')))
self.A = [os.path.join(self.dataroot, (opts.phase + 'A'), x) for x in images_A]
images_B = os.listdir(os.path.join(sel... |
class Dis_content(nn.Module):
def __init__(self):
super(Dis_content, self).__init__()
model = []
model += [LeakyReLUConv2d(256, 256, kernel_size=7, stride=2, padding=1, norm='Instance')]
model += [LeakyReLUConv2d(256, 256, kernel_size=7, stride=2, padding=1, norm='Instance')]
... |
class MultiScaleDis(nn.Module):
def __init__(self, input_dim, n_scale=3, n_layer=4, norm='None', sn=False):
super(MultiScaleDis, self).__init__()
ch = 64
self.downsample = nn.AvgPool2d(3, stride=2, padding=1, count_include_pad=False)
self.Diss = nn.ModuleList()
for _ in ra... |
class Dis(nn.Module):
def __init__(self, input_dim, norm='None', sn=False):
super(Dis, self).__init__()
ch = 64
n_layer = 6
self.model = self._make_net(ch, input_dim, n_layer, norm, sn)
def _make_net(self, ch, input_dim, n_layer, norm, sn):
model = []
model +=... |
class E_content(nn.Module):
def __init__(self, input_dim_a, input_dim_b):
super(E_content, self).__init__()
encA_c = []
tch = 64
encA_c += [LeakyReLUConv2d(input_dim_a, tch, kernel_size=7, stride=1, padding=3)]
for i in range(1, 3):
encA_c += [ReLUINSConv2d(tch... |
class E_attr(nn.Module):
def __init__(self, input_dim_a, input_dim_b, output_nc=8):
super(E_attr, self).__init__()
dim = 64
self.model_a = nn.Sequential(nn.ReflectionPad2d(3), nn.Conv2d(input_dim_a, dim, 7, 1), nn.ReLU(inplace=True), nn.ReflectionPad2d(1), nn.Conv2d(dim, (dim * 2), 4, 2),... |
class E_attr_concat(nn.Module):
def __init__(self, input_dim_a, input_dim_b, output_nc=8, norm_layer=None, nl_layer=None):
super(E_attr_concat, self).__init__()
ndf = 64
n_blocks = 4
max_ndf = 4
conv_layers_A = [nn.ReflectionPad2d(1)]
conv_layers_A += [nn.Conv2d(in... |
class G(nn.Module):
def __init__(self, output_dim_a, output_dim_b, nz):
super(G, self).__init__()
self.nz = nz
ini_tch = 256
tch_add = ini_tch
tch = ini_tch
self.tch_add = tch_add
self.decA1 = MisINSResBlock(tch, tch_add)
self.decA2 = MisINSResBlock... |
class G_concat(nn.Module):
def __init__(self, output_dim_a, output_dim_b, nz):
super(G_concat, self).__init__()
self.nz = nz
tch = 256
dec_share = []
dec_share += [INSResBlock(tch, tch)]
self.dec_share = nn.Sequential(*dec_share)
tch = (256 + self.nz)
... |
def get_scheduler(optimizer, opts, cur_ep=(- 1)):
if (opts.lr_policy == 'lambda'):
def lambda_rule(ep):
lr_l = (1.0 - (max(0, (ep - opts.n_ep_decay)) / float(((opts.n_ep - opts.n_ep_decay) + 1))))
return lr_l
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_ru... |
def meanpoolConv(inplanes, outplanes):
sequence = []
sequence += [nn.AvgPool2d(kernel_size=2, stride=2)]
sequence += [nn.Conv2d(inplanes, outplanes, kernel_size=1, stride=1, padding=0, bias=True)]
return nn.Sequential(*sequence)
|
def convMeanpool(inplanes, outplanes):
sequence = []
sequence += conv3x3(inplanes, outplanes)
sequence += [nn.AvgPool2d(kernel_size=2, stride=2)]
return nn.Sequential(*sequence)
|
def get_norm_layer(layer_type='instance'):
if (layer_type == 'batch'):
norm_layer = functools.partial(nn.BatchNorm2d, affine=True)
elif (layer_type == 'instance'):
norm_layer = functools.partial(nn.InstanceNorm2d, affine=False)
elif (layer_type == 'none'):
norm_layer = None
els... |
def get_non_linearity(layer_type='relu'):
if (layer_type == 'relu'):
nl_layer = functools.partial(nn.ReLU, inplace=True)
elif (layer_type == 'lrelu'):
nl_layer = functools.partial(nn.LeakyReLU, negative_slope=0.2, inplace=False)
elif (layer_type == 'elu'):
nl_layer = functools.part... |
def conv3x3(in_planes, out_planes):
return [nn.ReflectionPad2d(1), nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=1, padding=0, bias=True)]
|
def gaussian_weights_init(m):
classname = m.__class__.__name__
if ((classname.find('Conv') != (- 1)) and (classname.find('Conv') == 0)):
m.weight.data.normal_(0.0, 0.02)
|
class LayerNorm(nn.Module):
def __init__(self, n_out, eps=1e-05, affine=True):
super(LayerNorm, self).__init__()
self.n_out = n_out
self.affine = affine
if self.affine:
self.weight = nn.Parameter(torch.ones(n_out, 1, 1))
self.bias = nn.Parameter(torch.zeros... |
class BasicBlock(nn.Module):
def __init__(self, inplanes, outplanes, norm_layer=None, nl_layer=None):
super(BasicBlock, self).__init__()
layers = []
if (norm_layer is not None):
layers += [norm_layer(inplanes)]
layers += [nl_layer()]
layers += conv3x3(inplanes,... |
class LeakyReLUConv2d(nn.Module):
def __init__(self, n_in, n_out, kernel_size, stride, padding=0, norm='None', sn=False):
super(LeakyReLUConv2d, self).__init__()
model = []
model += [nn.ReflectionPad2d(padding)]
if sn:
model += [spectral_norm(nn.Conv2d(n_in, n_out, ker... |
class ReLUINSConv2d(nn.Module):
def __init__(self, n_in, n_out, kernel_size, stride, padding=0):
super(ReLUINSConv2d, self).__init__()
model = []
model += [nn.ReflectionPad2d(padding)]
model += [nn.Conv2d(n_in, n_out, kernel_size=kernel_size, stride=stride, padding=0, bias=True)]
... |
class INSResBlock(nn.Module):
def conv3x3(self, inplanes, out_planes, stride=1):
return [nn.ReflectionPad2d(1), nn.Conv2d(inplanes, out_planes, kernel_size=3, stride=stride)]
def __init__(self, inplanes, planes, stride=1, dropout=0.0):
super(INSResBlock, self).__init__()
model = []
... |
class MisINSResBlock(nn.Module):
def conv3x3(self, dim_in, dim_out, stride=1):
return nn.Sequential(nn.ReflectionPad2d(1), nn.Conv2d(dim_in, dim_out, kernel_size=3, stride=stride))
def conv1x1(self, dim_in, dim_out):
return nn.Conv2d(dim_in, dim_out, kernel_size=1, stride=1, padding=0)
... |
class GaussianNoiseLayer(nn.Module):
def __init__(self):
super(GaussianNoiseLayer, self).__init__()
def forward(self, x):
if (self.training == False):
return x
noise = Variable(torch.randn(x.size()).cuda(x.get_device()))
return (x + noise)
|
class ReLUINSConvTranspose2d(nn.Module):
def __init__(self, n_in, n_out, kernel_size, stride, padding, output_padding):
super(ReLUINSConvTranspose2d, self).__init__()
model = []
model += [nn.ConvTranspose2d(n_in, n_out, kernel_size=kernel_size, stride=stride, padding=padding, output_paddi... |
class SpectralNorm(object):
def __init__(self, name='weight', n_power_iterations=1, dim=0, eps=1e-12):
self.name = name
self.dim = dim
if (n_power_iterations <= 0):
raise ValueError('Expected n_power_iterations to be positive, but got n_power_iterations={}'.format(n_power_iter... |
def spectral_norm(module, name='weight', n_power_iterations=1, eps=1e-12, dim=None):
if (dim is None):
if isinstance(module, (torch.nn.ConvTranspose1d, torch.nn.ConvTranspose2d, torch.nn.ConvTranspose3d)):
dim = 1
else:
dim = 0
SpectralNorm.apply(module, name, n_power_i... |
def remove_spectral_norm(module, name='weight'):
for (k, hook) in module._forward_pre_hooks.items():
if (isinstance(hook, SpectralNorm) and (hook.name == name)):
hook.remove(module)
del module._forward_pre_hooks[k]
return module
raise ValueError("spectral_norm of '{... |
class TrainOptions():
def __init__(self):
self.parser = argparse.ArgumentParser()
self.parser.add_argument('--gpu_ids', type=str, default='0', help='path of data')
self.parser.add_argument('--dataroot', type=str, required=True, help='path of data')
self.parser.add_argument('--phas... |
class TestOptions():
def __init__(self):
self.parser = argparse.ArgumentParser()
self.parser.add_argument('--dataroot', type=str, required=True, help='path of data')
self.parser.add_argument('--phase', type=str, default='test', help='phase for dataloading')
self.parser.add_argumen... |
def tensor2img(img):
img = img[0].cpu().float().numpy()
if (img.shape[0] == 1):
img = np.tile(img, (3, 1, 1))
img = (((np.transpose(img, (1, 2, 0)) + 1) / 2.0) * 255.0)
return img.astype(np.uint8)
|
def save_imgs(imgs, names, path):
if (not os.path.exists(path)):
os.makedirs(path)
for (img, name) in zip(imgs, names):
img = tensor2img(img)
img = Image.fromarray(img)
img.save(os.path.join(path, (name + '.png')))
|
class Saver():
def __init__(self, opts):
self.display_dir = os.path.join(opts.display_dir, opts.name)
self.model_dir = os.path.join(opts.result_dir, opts.name)
self.image_dir = os.path.join(self.model_dir, 'images')
self.display_freq = opts.display_freq
self.img_save_freq ... |
def main():
parser = TestOptions()
opts = parser.parse()
print('\n--- load dataset ---')
if opts.a2b:
dataset = dataset_single(opts, 'A', opts.input_dim_a)
else:
dataset = dataset_single(opts, 'B', opts.input_dim_b)
loader = torch.utils.data.DataLoader(dataset, batch_size=1, nu... |
def main():
parser = TrainOptions()
opts = parser.parse()
print('\n--- load dataset ---')
dataset = dataset_unpair(opts)
train_loader = torch.utils.data.DataLoader(dataset, batch_size=opts.batch_size, shuffle=True, num_workers=opts.nThreads)
print('\n--- load model ---')
model = DivCo_DRIT... |
def create_model(args, maxlen, vocab):
def ortho_reg(weight_matrix):
w_n = (weight_matrix / K.cast((K.epsilon() + K.sqrt(K.sum(K.square(weight_matrix), axis=(- 1), keepdims=True))), K.floatx()))
reg = K.sum(K.square((K.dot(w_n, K.transpose(w_n)) - K.eye(w_n.shape[0].eval()))))
return (arg... |
class Attention(Layer):
def __init__(self, W_regularizer=None, b_regularizer=None, W_constraint=None, b_constraint=None, bias=True, **kwargs):
'\n Keras Layer that implements an Content Attention mechanism.\n Supports Masking.\n '
self.supports_masking = True
self.ini... |
class WeightedSum(Layer):
def __init__(self, **kwargs):
self.supports_masking = True
super(WeightedSum, self).__init__(**kwargs)
def call(self, input_tensor, mask=None):
assert (type(input_tensor) == list)
assert (type(mask) == list)
x = input_tensor[0]
a = in... |
class WeightedAspectEmb(Layer):
def __init__(self, input_dim, output_dim, init='uniform', input_length=None, W_regularizer=None, activity_regularizer=None, W_constraint=None, weights=None, dropout=0.0, **kwargs):
self.input_dim = input_dim
self.output_dim = output_dim
self.init = initiali... |
class Average(Layer):
def __init__(self, **kwargs):
self.supports_masking = True
super(Average, self).__init__(**kwargs)
def call(self, x, mask=None):
if (mask is not None):
mask = K.cast(mask, K.floatx())
mask = K.expand_dims(mask)
x = (x * mask)
... |
class MaxMargin(Layer):
def __init__(self, **kwargs):
super(MaxMargin, self).__init__(**kwargs)
def call(self, input_tensor, mask=None):
z_s = input_tensor[0]
z_n = input_tensor[1]
r_s = input_tensor[2]
z_s = (z_s / K.cast((K.epsilon() + K.sqrt(K.sum(K.square(z_s), ax... |
def get_optimizer(args):
clipvalue = 0
clipnorm = 10
if (args.algorithm == 'rmsprop'):
optimizer = opt.RMSprop(lr=0.001, rho=0.9, epsilon=1e-06, clipnorm=clipnorm, clipvalue=clipvalue)
elif (args.algorithm == 'sgd'):
optimizer = opt.SGD(lr=0.01, momentum=0.0, decay=0.0, nesterov=False,... |
class W2VEmbReader():
def __init__(self, emb_path, emb_dim=None):
logger.info(('Loading embeddings from: ' + emb_path))
self.embeddings = {}
emb_matrix = []
model = gensim.models.Word2Vec.load(emb_path)
self.emb_dim = emb_dim
for word in model.vocab:
se... |
class CheckpointIO(object):
def __init__(self, fname_template, **kwargs):
os.makedirs(os.path.dirname(fname_template), exist_ok=True)
self.fname_template = fname_template
self.module_dict = kwargs
def register(self, **kwargs):
self.module_dict.update(kwargs)
def save(sel... |
def listdir(dname):
fnames = list(chain(*[list(Path(dname).rglob(('*.' + ext))) for ext in ['png', 'jpg', 'jpeg', 'JPG']]))
return fnames
|
class DefaultDataset(data.Dataset):
def __init__(self, root, transform=None):
self.samples = listdir(root)
self.samples.sort()
self.transform = transform
self.targets = None
def __getitem__(self, index):
fname = self.samples[index]
img = Image.open(fname).conv... |
class ReferenceDataset(data.Dataset):
def __init__(self, root, transform=None):
(self.samples, self.targets) = self._make_dataset(root)
self.transform = transform
def _make_dataset(self, root):
domains = os.listdir(root)
(fnames, fnames2, labels) = ([], [], [])
for (i... |
def _make_balanced_sampler(labels):
class_counts = np.bincount(labels)
class_weights = (1.0 / class_counts)
weights = class_weights[labels]
return WeightedRandomSampler(weights, len(weights))
|
def get_train_loader(root, which='source', img_size=256, batch_size=8, prob=0.5, num_workers=4):
print(('Preparing DataLoader to fetch %s images during the training phase...' % which))
crop = transforms.RandomResizedCrop(img_size, scale=[0.8, 1.0], ratio=[0.9, 1.1])
rand_crop = transforms.Lambda((lambda x... |
def get_eval_loader(root, img_size=256, batch_size=32, imagenet_normalize=True, shuffle=True, num_workers=4, drop_last=False):
print('Preparing DataLoader for the evaluation phase...')
if imagenet_normalize:
(height, width) = (299, 299)
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224,... |
def get_test_loader(root, img_size=256, batch_size=32, shuffle=True, num_workers=4):
print('Preparing DataLoader for the generation phase...')
transform = transforms.Compose([transforms.Resize([img_size, img_size]), transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])])
d... |
class InputFetcher():
def __init__(self, loader, loader_ref=None, latent_dim=16, mode=''):
self.loader = loader
self.loader_ref = loader_ref
self.latent_dim = latent_dim
self.device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
self.mode = mode
def ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.