code
stringlengths
17
6.64M
class BaseOptions(): def __init__(self): self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) self.initialized = False def initialize(self): self.parser.add_argument('--dataroot', required=True, help='path to images (should have subfolders tra...
class TestOptions(BaseOptions): def initialize(self): BaseOptions.initialize(self) self.parser.add_argument('--ntest', type=int, default=float('inf'), help='# of test examples.') self.parser.add_argument('--results_dir', type=str, default='./results/', help='saves results here.') ...
class TrainOptions(BaseOptions): def initialize(self): BaseOptions.initialize(self) self.parser.add_argument('--display_freq', type=int, default=100, help='frequency of showing training results on screen') self.parser.add_argument('--display_single_pane_ncols', type=int, default=0, help='...
class GetData(object): "\n\n Download CycleGAN or Pix2Pix Data.\n\n Args:\n technique : str\n One of: 'cyclegan' or 'pix2pix'.\n verbose : bool\n If True, print additional information.\n\n Examples:\n >>> from util.get_data import GetData\n >>> gd = GetDa...
class HTML(): def __init__(self, web_dir, title, reflesh=0): self.title = title self.web_dir = web_dir self.img_dir = os.path.join(self.web_dir, 'images') if (not os.path.exists(self.web_dir)): os.makedirs(self.web_dir) if (not os.path.exists(self.img_dir)): ...
class ImagePool(): def __init__(self, pool_size): self.pool_size = pool_size if (self.pool_size > 0): self.num_imgs = 0 self.images = [] def query(self, images): if (self.pool_size == 0): return Variable(images) return_images = [] f...
def tensor2im(image_tensor, imtype=np.uint8): image_numpy = image_tensor[0].cpu().float().numpy() if (image_numpy.shape[0] == 1): image_numpy = np.tile(image_numpy, (3, 1, 1)) image_numpy = (((np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0) * 255.0) return image_numpy.astype(imtype)
def diagnose_network(net, name='network'): mean = 0.0 count = 0 for param in net.parameters(): if (param.grad is not None): mean += torch.mean(torch.abs(param.grad.data)) count += 1 if (count > 0): mean = (mean / count) print(name) print(mean)
def save_image(image_numpy, image_path): image_pil = Image.fromarray(image_numpy) image_pil.save(image_path)
def print_numpy(x, val=True, shp=False): x = x.astype(np.float64) if shp: print('shape,', x.shape) if val: x = x.flatten() print(('mean = %3.3f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f' % (np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x))))
def mkdirs(paths): if (isinstance(paths, list) and (not isinstance(paths, str))): for path in paths: mkdir(path) else: mkdir(paths)
def mkdir(path): if (not os.path.exists(path)): os.makedirs(path)
class Visualizer(): def __init__(self, opt): self.display_id = opt.display_id self.use_html = (opt.isTrain and (not opt.no_html)) self.win_size = opt.display_winsize self.name = opt.name self.opt = opt self.saved = False if (self.display_id > 0): ...
def get_loader(config): 'Builds and returns Dataloader for MNIST and SVHN dataset.' transform_list = [] if config.use_augmentation: transform_list.append(transforms.RandomHorizontalFlip()) transform_list.append(transforms.RandomRotation(0.1)) transform_list.append(transforms.Scale(conf...
def str2bool(v): return (v.lower() in 'true')
def main(config): (svhn_loader, mnist_loader, svhn_test_loader, mnist_test_loader) = get_loader(config) solver = Solver(config, svhn_loader, mnist_loader) cudnn.benchmark = True if (not os.path.exists(config.model_path)): os.makedirs(config.model_path) if (not os.path.exists(config.sample_...
def str2bool(v): return (v.lower() in 'true')
def main(config): (svhn_loader, mnist_loader, svhn_test_loader, mnist_test_loader) = get_loader(config) solver = Solver(config, svhn_loader, mnist_loader) cudnn.benchmark = True if (not os.path.exists(config.model_path)): os.makedirs(config.model_path) if (not os.path.exists(config.sample_...
def str2bool(v): return (v.lower() in 'true')
def main(config): (svhn_loader, mnist_loader, svhn_test_loader, mnist_test_loader) = get_loader(config) solver = Solver(config, svhn_loader, mnist_loader) cudnn.benchmark = True if (not os.path.exists(config.model_path)): os.makedirs(config.model_path) if (not os.path.exists(config.sample_...
def deconv(c_in, c_out, k_size, stride=2, pad=1, bn=True): 'Custom deconvolutional layer for simplicity.' layers = [] layers.append(nn.ConvTranspose2d(c_in, c_out, k_size, stride, pad, bias=False)) if bn: layers.append(nn.BatchNorm2d(c_out)) return nn.Sequential(*layers)
def conv(c_in, c_out, k_size, stride=2, pad=1, bn=True): 'Custom convolutional layer for simplicity.' layers = [] layers.append(nn.Conv2d(c_in, c_out, k_size, stride, pad, bias=False)) if bn: layers.append(nn.BatchNorm2d(c_out)) return nn.Sequential(*layers)
class G11(nn.Module): def __init__(self, conv_dim=64): super(G11, self).__init__() self.conv1 = conv(1, conv_dim, 4) self.conv1_svhn = conv(3, conv_dim, 4) self.conv2 = conv(conv_dim, (conv_dim * 2), 4) res_dim = (conv_dim * 2) self.conv3 = conv(res_dim, res_dim, 3...
class G22(nn.Module): def __init__(self, conv_dim=64): super(G22, self).__init__() self.conv1 = conv(3, conv_dim, 4) self.conv1_mnist = conv(1, conv_dim, 4) self.conv2 = conv(conv_dim, (conv_dim * 2), 4) res_dim = (conv_dim * 2) self.conv3 = conv(res_dim, res_dim, ...
class D1(nn.Module): 'Discriminator for mnist.' def __init__(self, conv_dim=64, use_labels=False): super(D1, self).__init__() self.conv1 = conv(1, conv_dim, 4, bn=False) self.conv2 = conv(conv_dim, (conv_dim * 2), 4) self.conv3 = conv((conv_dim * 2), (conv_dim * 4), 4) ...
class D2(nn.Module): 'Discriminator for svhn.' def __init__(self, conv_dim=64, use_labels=False): super(D2, self).__init__() self.conv1 = conv(3, conv_dim, 4, bn=False) self.conv2 = conv(conv_dim, (conv_dim * 2), 4) self.conv3 = conv((conv_dim * 2), (conv_dim * 4), 4) ...
def relu6(x): return K.relu(x, max_value=6)
def load_model(input_shape=(224, 224, 3), n_veid=576, Mode='train', Weights_path='./weights'): alpha = 1.0 depth_multiplier = 1 dropout = 0.001 gauss_size = 1024 input_layer = Input(shape=input_shape) y = Input(shape=[n_veid]) x = _conv_block(input_layer, 32, alpha, strides=(2, 2)) x =...
def _conv_block(inputs, filters, alpha, kernel=(3, 3), strides=(1, 1)): channel_axis = (1 if (K.image_data_format() == 'channels_first') else (- 1)) filters = int((filters * alpha)) x = ZeroPadding2D(padding=(1, 1), name='conv1_pad')(inputs) x = Conv2D(filters, kernel, padding='valid', use_bias=False,...
def _depthwise_conv_block(inputs, pointwise_conv_filters, alpha, depth_multiplier=1, strides=(1, 1), block_id=1): channel_axis = (1 if (K.image_data_format() == 'channels_first') else (- 1)) pointwise_conv_filters = int((pointwise_conv_filters * alpha)) x = ZeroPadding2D(padding=(1, 1), name=('conv_pad_%d...
def display_output(output): sys.stdout.write('\x1b[F') print(output)
def eval(args): e_common = E_common(args.sep, int((args.resize / 64))) e_separate_A = E_separate_A(args.sep, int((args.resize / 64))) e_separate_B = E_separate_B(args.sep, int((args.resize / 64))) decoder = Decoder(int((args.resize / 64))) if torch.cuda.is_available(): e_common = e_common....
class E_common(nn.Module): def __init__(self, sep, size, dim=512): super(E_common, self).__init__() self.sep = sep self.size = size self.dim = dim self.layer1 = [] self.layer2 = [] self.layer3 = [] self.layer4 = [] self.layer5 = [] s...
class E_separate_A(nn.Module): def __init__(self, sep, size): super(E_separate_A, self).__init__() self.sep = sep self.size = size self.layer1 = [] self.layer2 = [] self.layer3 = [] self.layer4 = [] self.layer5 = [] self.layer6 = [] ...
class E_separate_B(nn.Module): def __init__(self, sep, size): super(E_separate_B, self).__init__() self.sep = sep self.size = size self.layer1 = [] self.layer2 = [] self.layer3 = [] self.layer4 = [] self.layer5 = [] self.layer6 = [] ...
class Decoder(nn.Module): def __init__(self, size, dim=512): super(Decoder, self).__init__() self.size = size self.dim = dim self.layer1 = [] self.layer2 = [] self.layer3 = [] self.layer4 = [] self.layer5 = [] self.layer6 = [] self.l...
class Disc(nn.Module): def __init__(self, sep, size, dim=512): super(Disc, self).__init__() self.sep = sep self.size = size self.dim = dim self.classify = nn.Sequential(nn.Linear((((dim - (2 * self.sep)) * self.size) * self.size), dim), nn.LeakyReLU(0.2, inplace=True), nn....
def l2normalize(v, eps=1e-12): return (v / (v.norm() + eps))
class SpectralNorm(nn.Module): def __init__(self, module, name='weight', power_iterations=1): super(SpectralNorm, self).__init__() self.module = module self.name = name self.power_iterations = power_iterations if (not self._made_params()): self._make_params() ...
def preprocess_celeba(args): if (not os.path.exists(args.dest)): os.mkdir(args.dest) allA = [] allB = [] with open(args.attributes) as f: lines = f.readlines() if (args.config == 'beard_glasses'): for line in lines[2:]: line = line.split() if (male_n...
def male_no_5_oclock(line): return ((int(line[21]) == 1) and (int(line[1]) == (- 1)))
def beard(line): return ((int(line[23]) == 1) or (int(line[17]) == 1) or (int(line[25]) == (- 1)))
def glasses(line): return (int(line[16]) == 1)
def smile(line): return (int(line[32]) == 1)
def blonde_hair(line): return (int(line[10]) == 1)
def black_hair(line): return (int(line[9]) == 1)
def preprocess_folders(args): if (not os.path.exists(args.dest)): os.mkdir(args.dest) trainA = os.listdir(os.path.join(args.root, 'trainA')) trainB = os.listdir(os.path.join(args.root, 'trainB')) testA = os.listdir(os.path.join(args.root, 'testA')) testB = os.listdir(os.path.join(args.root...
def train(args): if (not os.path.exists(args.out)): os.makedirs(args.out) _iter = 0 (domA_train, domB_train) = get_train_dataset(args) size = (args.resize // 64) dim = 512 e_common = E_common(args.sep, size, dim=dim) e_separate_A = E_separate_A(args.sep, size) e_separate_B = E_...
def get_test_dataset(args, crop=None, resize=None): if (crop is None): crop = args.crop if (resize is None): resize = args.resize comp_transform = transforms.Compose([transforms.CenterCrop(crop), transforms.Resize(resize), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, ...
def get_train_dataset(args, crop=None, resize=None): if (crop is None): crop = args.crop if (resize is None): resize = args.resize comp_transform = transforms.Compose([transforms.CenterCrop(crop), transforms.Resize(resize), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transfor...
def save_imgs(args, e_common, e_separate_A, e_separate_B, decoder, iters, size, BtoA=True, num_offsets=1): ' saves images of translation B -> A or A -> B' (test_domA, test_domB) = get_test_imgs(args) for k in range(num_offsets): exps = [] for i in range((k * args.num_display), ((k + 1) * a...
def get_test_imgs(args, crop=None, resize=None): (domA_test, domB_test) = get_test_dataset(args, crop=crop, resize=resize) domA_test_loader = torch.utils.data.DataLoader(domA_test, batch_size=64, shuffle=False, num_workers=6) domB_test_loader = torch.utils.data.DataLoader(domB_test, batch_size=64, shuffle...
def save_model(out_file, e_common, e_separate_A, e_separate_B, decoder, ae_opt, disc, disc_opt, iters): state = {'e_common': e_common.state_dict(), 'e_separate_A': e_separate_A.state_dict(), 'e_separate_B': e_separate_B.state_dict(), 'decoder': decoder.state_dict(), 'ae_opt': ae_opt.state_dict(), 'disc': disc.sta...
def load_model(load_path, e_common, e_separate_A, e_separate_B, decoder, ae_opt, disc, disc_opt): state = torch.load(load_path) e_common.load_state_dict(state['e_common']) e_separate_A.load_state_dict(state['e_separate_A']) e_separate_B.load_state_dict(state['e_separate_B']) decoder.load_state_dic...
def load_model_for_eval(load_path, e_common, e_separate_A, e_separate_B, decoder): state = torch.load(load_path) e_common.load_state_dict(state['e_common']) e_separate_A.load_state_dict(state['e_separate_A']) e_separate_B.load_state_dict(state['e_separate_B']) decoder.load_state_dict(state['decode...
def edges_loader(path, train=True): image = Image.open(path).convert('RGB') image_A = image.crop((0, 0, 256, 256)) image_B = image.crop((0, 256, 512, 256)) if train: return image_A else: return image_B
def default_loader(path): return Image.open(path).convert('RGB')
class Logger(): def __init__(self, path): self.full_path = ('%s/log.txt' % path) self.log_file = open(self.full_path, 'w+') self.log_file.close() self.map = {} def add_value(self, tag, value): self.map[tag] = value def log(self, iter): self.log_file = ope...
class CustomDataset(data.Dataset): def __init__(self, path, transform=None, return_paths=False, loader=default_loader): super(CustomDataset, self).__init__() with open(path) as f: imgs = [s.replace('\n', '') for s in f.readlines()] if (len(imgs) == 0): raise Runtim...
def default_flist_reader(flist): "\n flist format: impath label\nimpath label\n ...(same to caffe's filelist)\n " imlist = [] with open(flist, 'r') as rf: for line in rf.readlines(): impath = line.strip() imlist.append(impath) return imlist
def is_image_file(filename): return any((filename.endswith(extension) for extension in IMG_EXTENSIONS))
def save_stripped_imgs(args, e_common, e_separate_A, e_separate_B, decoder, iters, size, A=True): (test_domA, test_domB) = get_test_imgs(args) exps = [] zero_encoding = torch.full((1, ((args.sep * size) * size)), 0) one_encoding = torch.full((1, ((args.sep * size) * size)), 1) if torch.cuda.is_ava...
def save_chosen_imgs(args, e_common, e_separate_A, e_separate_B, decoder, iters, listA, listB, BtoA=True): ' saves images of translation B -> A or A -> B' (test_domA, test_domB) = get_test_imgs(args) exps = [] for i in range(args.num_display): with torch.no_grad(): if (i == 0): ...
def interpolate_fixed_common(args, e_common, e_separate_A, e_separate_B, decoder, imgA1, imgA2, imgB1, imgB2, content_img): (test_domA, test_domB) = get_test_imgs(args) exps = [] common = e_common(test_domB[content_img].unsqueeze(0)) a1 = e_separate_A(test_domA[imgA1].unsqueeze(0)) a2 = e_separate...
def interpolate_fixed_A(args, e_common, e_separate_A, e_separate_B, decoder, imgC1, imgC2, imgB1, imgB2, imgA): (test_domA, test_domB) = get_test_imgs(args) exps = [] c1 = e_common(test_domB[imgC1].unsqueeze(0)) c2 = e_common(test_domB[imgC2].unsqueeze(0)) a = e_separate_A(test_domA[imgA].unsqueez...
def interpolate_fixed_B(args, e_common, e_separate_A, e_separate_B, decoder, imgC1, imgC2, imgA1, imgA2, imgB): (test_domA, test_domB) = get_test_imgs(args) exps = [] c1 = e_common(test_domB[imgC1].unsqueeze(0)) c2 = e_common(test_domB[imgC2].unsqueeze(0)) a1 = e_separate_A(test_domA[imgA1].unsque...
class BUILD_NET_VGG16(): def __init__(self, vgg16_npy_path=None): self.data_dict = np.load(vgg16_npy_path, encoding='latin1').item() print('npy file loaded') def build(self, rgb, ROIMap, NUM_CLASSES, keep_prob): '\n load variable from npy to build the VGG\n\n :param rgb...
def CheckVGG16(model_path): TensorflowUtils.maybe_download_and_extract(model_path.split('/')[0], 'ftp://mi.eng.cam.ac.uk/pub/mttt2/models/vgg16.npy') if (not os.path.isfile(model_path)): print('Error: Cant find pretrained vgg16 model for network initiation. Please download model from:') print(...
def main(argv=None): tf.reset_default_graph() keep_prob = tf.placeholder(tf.float32, name='keep_probabilty') image = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='input_image') ROIMap = tf.placeholder(tf.int32, shape=[None, None, None, 1], name='ROIMap') Net = BuildNetVgg16.BUILD_N...
def GetIOU(Pred, GT, NumClasses, ClassNames=[], DisplyResults=False): ClassIOU = np.zeros(NumClasses) ClassWeight = np.zeros(NumClasses) for i in range(NumClasses): Intersection = np.float32(np.sum(((Pred == GT) * (GT == i)))) Union = ((np.sum((GT == i)) + np.sum((Pred == i))) - Intersecti...
def main(argv=None): keep_prob = tf.placeholder(tf.float32, name='keep_probabilty') image = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='input_image') ROIMap = tf.placeholder(tf.int32, shape=[None, None, None, 1], name='ROIMap') Net = BuildNetVgg16.BUILD_NET_VGG16(vgg16_npy_path=model...
def train(loss_val, var_list): optimizer = tf.train.AdamOptimizer(learning_rate) grads = optimizer.compute_gradients(loss_val, var_list=var_list) return optimizer.apply_gradients(grads)
def main(argv=None): tf.reset_default_graph() keep_prob = tf.placeholder(tf.float32, name='keep_probabilty') image = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='input_image') ROIMap = tf.placeholder(tf.int32, shape=[None, None, None, 1], name='ROIMap') GTLabel = tf.placeholder(tf...
def get_model_data(dir_path, model_url): maybe_download_and_extract(dir_path, model_url) filename = model_url.split('/')[(- 1)] filepath = os.path.join(dir_path, filename) if (not os.path.exists(filepath)): raise IOError('VGG Model not found!') data = scipy.io.loadmat(filepath) return ...
def maybe_download_and_extract(dir_path, url_name, is_tarfile=False, is_zipfile=False): if (not os.path.exists(dir_path)): os.makedirs(dir_path) filename = url_name.split('/')[(- 1)] filepath = os.path.join(dir_path, filename) if (not os.path.exists(filepath)): def _progress(count, bl...
def save_image(image, save_dir, name, mean=None): '\n Save image by unprocessing if mean given else just save\n :param mean:\n :param image:\n :param save_dir:\n :param name:\n :return:\n ' if mean: image = unprocess_image(image, mean) misc.imsave(os.path.join(save_dir, (name ...
def get_variable(weights, name): init = tf.constant_initializer(weights, dtype=tf.float32) var = tf.get_variable(name=name, initializer=init, shape=weights.shape) return var
def weight_variable(shape, stddev=0.02, name=None): initial = tf.truncated_normal(shape, stddev=stddev) if (name is None): return tf.Variable(initial) else: return tf.get_variable(name, initializer=initial)
def bias_variable(shape, name=None): initial = tf.constant(0.0, shape=shape) if (name is None): return tf.Variable(initial) else: return tf.get_variable(name, initializer=initial)
def get_tensor_size(tensor): from operator import mul return reduce(mul, (d.value for d in tensor.get_shape()), 1)
def conv2d_basic(x, W, bias): conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') return tf.nn.bias_add(conv, bias)
def conv2d_strided(x, W, b): conv = tf.nn.conv2d(x, W, strides=[1, 2, 2, 1], padding='SAME') return tf.nn.bias_add(conv, b)
def conv2d_transpose_strided(x, W, b, output_shape=None, stride=2): if (output_shape is None): output_shape = x.get_shape().as_list() output_shape[1] *= 2 output_shape[2] *= 2 output_shape[3] = W.get_shape().as_list()[2] conv = tf.nn.conv2d_transpose(x, W, output_shape, strides...
def leaky_relu(x, alpha=0.0, name=''): return tf.maximum((alpha * x), x, name)
def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
def avg_pool_2x2(x): return tf.nn.avg_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
def local_response_norm(x): return tf.nn.lrn(x, depth_radius=5, bias=2, alpha=0.0001, beta=0.75)
def batch_norm(x, n_out, phase_train, scope='bn', decay=0.9, eps=1e-05): '\n Code taken from http://stackoverflow.com/a/34634291/2267819\n ' with tf.variable_scope(scope): beta = tf.get_variable(name='beta', shape=[n_out], initializer=tf.constant_initializer(0.0), trainable=True) gamma =...
def process_image(image, mean_pixel): return (image - mean_pixel)
def unprocess_image(image, mean_pixel): return (image + mean_pixel)
def bottleneck_unit(x, out_chan1, out_chan2, down_stride=False, up_stride=False, name=None): '\n Modified implementation from github ry?!\n ' def conv_transpose(tensor, out_channel, shape, strides, name=None): out_shape = tensor.get_shape().as_list() in_channel = out_shape[(- 1)] ...
def add_to_regularization_and_summary(var): if (var is not None): tf.summary.histogram(var.op.name, var) tf.add_to_collection('reg_loss', tf.nn.l2_loss(var))
def add_activation_summary(var): if (var is not None): tf.summary.histogram((var.op.name + '/activation'), var) tf.summary.scalar((var.op.name + '/sparsity'), tf.nn.zero_fraction(var))
def add_gradient_summary(grad, var): if (grad is not None): tf.summary.histogram((var.op.name + '/gradient'), grad)
class BUILD_NET_VGG16(): def __init__(self, vgg16_npy_path=None): self.data_dict = np.load(vgg16_npy_path, encoding='latin1').item() print('npy file loaded') def build(self, rgb, NUM_CLASSES, keep_prob): '\n load variable from npy to build the VGG\n\n :param rgb: rgb im...
def CheckVGG16(model_path): TensorflowUtils.maybe_download_and_extract(model_path.split('/')[0], 'ftp://mi.eng.cam.ac.uk/pub/mttt2/models/vgg16.npy') if (not os.path.isfile(model_path)): print('Error: Cant find pretrained vgg16 model for network initiation. Please download model from:') print(...
def main(argv=None): tf.reset_default_graph() keep_prob = tf.placeholder(tf.float32, name='keep_probabilty') image = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='input_image') Net = BuildNetVgg16.BUILD_NET_VGG16(vgg16_npy_path=model_path) Net.build(image, NUM_CLASSES, keep_prob) ...
def GetIOU(Pred, GT, NumClasses, ClassNames=[], DisplyResults=False): ClassIOU = np.zeros(NumClasses) ClassWeight = np.zeros(NumClasses) for i in range(NumClasses): Intersection = np.float32(np.sum(((Pred == GT) * (GT == i)))) Union = ((np.sum((GT == i)) + np.sum((Pred == i))) - Intersecti...
def main(argv=None): keep_prob = tf.placeholder(tf.float32, name='keep_probabilty') image = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='input_image') Net = BuildNetVgg16.BUILD_NET_VGG16(vgg16_npy_path=model_path) Net.build(image, NUM_CLASSES, keep_prob) ValidReader = Data_Reader....
def train(loss_val, var_list): optimizer = tf.train.AdamOptimizer(learning_rate) grads = optimizer.compute_gradients(loss_val, var_list=var_list) return optimizer.apply_gradients(grads)