├── images
├── ring.jpg
├── sample.jpg
├── overview.png
└── linear_inverse_problem.png
├── admm
├── vec.py
├── add_noise.py
├── inpaint.py
├── cs.py
├── inpaint_center.py
├── inpaint_block.py
├── superres.py
├── update_popmean.py
├── solver_paper.py
├── solver_l1.py
└── paper_demo.py
├── projector
├── smooth_stream.py
├── noise.py
├── run_celeb.sh
├── load_imagenet.py
├── load_celeb.py
├── layers.py
├── layers_nearest.py
├── layers_nearest_2.py
└── main.py
├── README.md
└── LICENSE
/images/ring.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rick-chang/OneNet/HEAD/images/ring.jpg
--------------------------------------------------------------------------------
/images/sample.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rick-chang/OneNet/HEAD/images/sample.jpg
--------------------------------------------------------------------------------
/images/overview.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rick-chang/OneNet/HEAD/images/overview.png
--------------------------------------------------------------------------------
/admm/vec.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | import numpy as np
4 |
5 | def vec(x):
6 | return np.reshape(x, (-1), order='F')
--------------------------------------------------------------------------------
/images/linear_inverse_problem.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rick-chang/OneNet/HEAD/images/linear_inverse_problem.png
--------------------------------------------------------------------------------
/admm/add_noise.py:
--------------------------------------------------------------------------------
1 |
2 | import numpy as np
3 |
4 | def exe(x, noise_mean = 0.0, noise_std = 0.1):
5 | noise = np.random.randn(*x.shape) * noise_std + noise_mean;
6 | y = x + noise
7 | return y, noise
8 |
--------------------------------------------------------------------------------
/admm/inpaint.py:
--------------------------------------------------------------------------------
1 |
2 | import numpy as np
3 | from vec import vec
4 |
5 |
6 | def setup(x_shape, drop_prob = 0.5):
7 |
8 | mask = np.random.rand(*x_shape) > drop_prob;
9 | mask = mask.astype('double')
10 |
11 | def A_fun(x):
12 | y = np.multiply(x, mask);
13 | return y
14 |
15 | def AT_fun(y):
16 | x = np.multiply(y, mask);
17 | return x
18 |
19 | return (A_fun, AT_fun, mask)
--------------------------------------------------------------------------------
/admm/cs.py:
--------------------------------------------------------------------------------
1 |
2 | import numpy as np
3 | import scipy as sp
4 | from vec import vec
5 | import matplotlib.pyplot as plt
6 |
7 |
8 |
9 | def setup(x_shape, compress_ratio):
10 |
11 | d = np.prod(x_shape).astype(int)
12 | m = np.round(compress_ratio * d).astype(int)
13 |
14 | A = np.random.randn(m,d) / np.sqrt(m)
15 |
16 |
17 | def A_fun(x):
18 | y = np.dot(A, x.ravel(order='F'))
19 | y = np.reshape(y, [1, m], order='F')
20 | return y
21 |
22 | def AT_fun(y):
23 | y = np.reshape(y, [m, 1], order='F')
24 | x = np.dot(A.T, y)
25 | x = np.reshape(x, x_shape, order='F')
26 | return x
27 |
28 | return (A_fun, AT_fun, A)
29 |
30 |
--------------------------------------------------------------------------------
/admm/inpaint_center.py:
--------------------------------------------------------------------------------
1 |
2 | import numpy as np
3 | import scipy as sp
4 | from vec import vec
5 | import matplotlib.pyplot as plt
6 |
7 |
8 | def setup(x_shape, box_size):
9 |
10 |
11 | mask = np.ones(x_shape)
12 |
13 |
14 | idx_row = np.round(float(x_shape[1]) / 2.0 - float(box_size) / 2.0).astype(int)
15 | idx_col = np.round(float(x_shape[2]) / 2.0 - float(box_size) / 2.0).astype(int)
16 |
17 | mask[0,idx_row:idx_row+box_size,idx_col:idx_col+box_size,:] = 0.
18 |
19 |
20 | def A_fun(x):
21 | y = np.multiply(x, mask);
22 | return y
23 |
24 | def AT_fun(y):
25 | x = np.multiply(y, mask);
26 | return x
27 |
28 | return (A_fun, AT_fun, mask)
29 |
30 |
31 |
--------------------------------------------------------------------------------
/projector/smooth_stream.py:
--------------------------------------------------------------------------------
1 |
2 | import numpy as np
3 |
4 |
5 | class SmoothStream:
6 |
7 | def __init__(self, window_size=10):
8 |
9 | self.smoothed_stream = []
10 | self.stream = []
11 | self.current_sum = 0.
12 | self.window_size = window_size
13 |
14 |
15 | def get_moving_avg(self):
16 | if len(self.stream) == 0:
17 | return 0.
18 | if len(self.stream) < self.window_size:
19 | return self.current_sum / len(self.stream)
20 | return self.current_sum / self.window_size
21 |
22 | def insert(self, x):
23 | if self.stream == None:
24 | self.stream = np.array(x)
25 | else:
26 | self.stream.append(x)
27 |
28 | self.current_sum += x
29 |
30 | if len(self.stream) > self.window_size:
31 | self.current_sum -= self.stream[-(self.window_size+1)]
32 |
33 | self.smoothed_stream.append(self.get_moving_avg())
--------------------------------------------------------------------------------
/admm/inpaint_block.py:
--------------------------------------------------------------------------------
1 |
2 | import numpy as np
3 | import scipy as sp
4 | from vec import vec
5 | import matplotlib.pyplot as plt
6 |
7 |
8 | """ currently only support width (and height) * resize_ratio is an interger! """
9 | def setup(x_shape, box_size, total_box = 1):
10 |
11 | spare = 0.25 * box_size
12 |
13 | mask = np.ones(x_shape)
14 |
15 | for i in range(total_box):
16 |
17 | start_row = spare
18 | end_row = x_shape[1] - spare - box_size - 1
19 | start_col = spare
20 | end_col = x_shape[2] - spare - box_size - 1
21 |
22 | idx_row = int(np.random.rand(1) * (end_row - start_row) + start_row)
23 | idx_col = int(np.random.rand(1) * (end_col - start_col) + start_col)
24 |
25 | mask[0,idx_row:idx_row+box_size,idx_col:idx_col+box_size,:] = 0.
26 |
27 |
28 | def A_fun(x):
29 | y = np.multiply(x, mask);
30 | return y
31 |
32 | def AT_fun(y):
33 | x = np.multiply(y, mask);
34 | return x
35 |
36 | return (A_fun, AT_fun, mask)
37 |
38 |
39 |
--------------------------------------------------------------------------------
/admm/superres.py:
--------------------------------------------------------------------------------
1 |
2 | import numpy as np
3 | import scipy as sp
4 | from vec import vec
5 | import matplotlib.pyplot as plt
6 |
7 |
8 | """ currently only support width (and height) * resize_ratio is an interger! """
9 | def setup(x_shape, resize_ratio):
10 |
11 | box_size = 1.0 / resize_ratio
12 | if np.mod(x_shape[1], box_size) != 0 or np.mod(x_shape[2], box_size) != 0:
13 | print "only support width (and height) * resize_ratio is an interger!"
14 |
15 |
16 | def A_fun(x):
17 | y = box_average(x, int(box_size))
18 | return y
19 |
20 | def AT_fun(y):
21 | x = box_repeat(y, int(box_size))
22 | return x
23 |
24 | return (A_fun, AT_fun)
25 |
26 |
27 |
28 | def box_average(x, box_size):
29 | """ x: [1, row, col, channel] """
30 | im_row = x.shape[1]
31 | im_col = x.shape[2]
32 | channel = x.shape[3]
33 | out_row = np.floor(float(im_row) / float(box_size)).astype(int)
34 | out_col = np.floor(float(im_col) / float(box_size)).astype(int)
35 | y = np.zeros((1,out_row,out_col,channel))
36 | total_i = int(im_row / box_size)
37 | total_j = int(im_col / box_size)
38 |
39 | for c in range(channel):
40 | for i in range(total_i):
41 | for j in range(total_j):
42 | avg = np.average(x[0, i*int(box_size):(i+1)*int(box_size), j*int(box_size):(j+1)*int(box_size), c], axis=None)
43 | y[0,i,j,c] = avg
44 |
45 | return y
46 |
47 |
48 | def box_repeat(x, box_size):
49 | """ x: [1, row, col, channel] """
50 | im_row = x.shape[1]
51 | im_col = x.shape[2]
52 | channel = x.shape[3]
53 | out_row = np.floor(float(im_row) * float(box_size)).astype(int)
54 | out_col = np.floor(float(im_col) * float(box_size)).astype(int)
55 | y = np.zeros((1,out_row,out_col,channel))
56 | total_i = im_row
57 | total_j = im_col
58 |
59 | for c in range(channel):
60 | for i in range(total_i):
61 | for j in range(total_j):
62 | y[0, i*int(box_size):(i+1)*int(box_size), j*int(box_size):(j+1)*int(box_size), c] = x[0,i,j,c]
63 | return y
--------------------------------------------------------------------------------
/projector/noise.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import scipy as sp
3 | import scipy.misc
4 |
5 |
6 | def add_noise(x, local_random,
7 | std=0.6,
8 | uniform_max=3.464,
9 | continuous_noise=0,
10 | use_spatially_varying_uniform_on_top=1,
11 | min_spatially_continuous_noise_factor=0.01,
12 | max_spatially_continuous_noise_factor=0.5,
13 | clean_img_prob=0.0,
14 | clip_input=0, clip_input_bound=10.0,
15 | ):
16 | """
17 | Perturb an input m*n*3 image x by adding Gaussian noise with spatially-varying standard deviation
18 | and smoothing the image by downsampling and upsampling with nearest neighbor algorithm. The
19 | smoothing method generates blurred and blocky outputs.
20 | """
21 |
22 | def actually_add_noise(x):
23 | y = x
24 | x_shape = x.shape
25 |
26 | if len(x_shape) == 2:
27 | x_shape.append(1)
28 |
29 | if continuous_noise > 0:
30 | rand_std = local_random.rand() * (std - 0.05) + 0.05
31 | noise = local_random.randn(x_shape[0], x_shape[1], x_shape[2]) * rand_std
32 | else:
33 | noise = local_random.randn(x_shape[0], x_shape[1], x_shape[2]) * std
34 |
35 | if use_spatially_varying_uniform_on_top > 0:
36 | for channel in range(x_shape[2]):
37 | low_res_row = np.amax( [np.round(float(x_shape[0]) * local_random.rand() * (max_spatially_continuous_noise_factor - min_spatially_continuous_noise_factor)).astype(int), 1])
38 | low_res_col = np.amax( [np.round(float(x_shape[1]) * local_random.rand() * (max_spatially_continuous_noise_factor - min_spatially_continuous_noise_factor)).astype(int), 1])
39 |
40 |
41 | lowres_noise_map = local_random.rand(low_res_row,low_res_col) * 2 * uniform_max - uniform_max
42 | highres_noise_map = sp.misc.imresize(lowres_noise_map, [x_shape[0], x_shape[1]], interp='bicubic', mode='F')
43 | noise[:,:,channel] *= highres_noise_map
44 |
45 | y += noise
46 |
47 | return y
48 |
49 | def create_blocky_image(x, min_resize_ratio):
50 | ratio = local_random.rand() * (0.95 - min_resize_ratio) + min_resize_ratio
51 | tmp = sp.misc.imresize(x, ratio, interp='nearest')
52 | y = sp.misc.imresize(tmp, [x.shape[0], x.shape[1]], interp='nearest').astype(float) / 255.0
53 |
54 | return y
55 |
56 | y = np.copy(x)
57 |
58 | # the probability to smooth the input before adding noise
59 | prob_block = 0.3
60 |
61 | r = local_random.rand()
62 | if r < prob_block:
63 | y = create_blocky_image(x, min_resize_ratio=0.2)
64 |
65 | result = actually_add_noise(y)
66 |
67 | return result
68 |
69 |
--------------------------------------------------------------------------------
/admm/update_popmean.py:
--------------------------------------------------------------------------------
1 |
2 | import sys
3 | sys.path.append("../projector")
4 | import main as model
5 | import tensorflow as tf
6 | import numpy as np
7 | import scipy as sp
8 | import scipy.io
9 | import math
10 | import load_celeb
11 | import os
12 | import timeit
13 | import matplotlib.pyplot as plt
14 |
15 | import add_noise
16 |
17 | import solver_paper as solver
18 | import solver_l1 as solver_l1
19 |
20 |
21 | import scipy as sp
22 |
23 | #np.random.seed(1085)
24 |
25 |
26 | img_size = (64,64,3)
27 |
28 |
29 | # filename of the trained model. If using virtual batch normalization,
30 | use_latent = 1 # if lambda_latent > 0
31 | iter = 49999
32 | pretrained_folder = os.path.expanduser("../projector/model/imsize64_ratio0.010000_dis0.005000_latent0.000100_img0.001000_de1.000000_derate1.000000_dp1_gd1_softpos0.850000_wdcy_0.000000_seed0")
33 | pretrained_model_file = '%s/model/model_iter-%d' % (pretrained_folder, iter)
34 |
35 | # the filename of saved the reference batch
36 | ref_file = '%s/ref_batch_25.mat' % pretrained_folder
37 | ref_batch = sp.io.loadmat(ref_file)['ref_batch']
38 | n_reference = ref_batch.shape[0]
39 |
40 |
41 | # setup the variables in the session
42 | batch_size = n_reference
43 | images_tf = tf.placeholder( tf.float32, [batch_size, img_size[0], img_size[1], img_size[2]], name="images")
44 | is_train = True
45 | proj, latent = model.build_projection_model(images_tf, is_train, n_reference, use_bias=True, reuse=None)
46 | dis, _ = model.build_classifier_model_imagespace(proj, is_train, n_reference, reuse=None)
47 |
48 | if use_latent > 0:
49 | dis_latent,_ = model.build_classifier_model_latentspace(latent, is_train, n_reference, reuse=None)
50 |
51 |
52 | # We create a session to use the graph and restore the variables
53 | print 'loading model...'
54 | sess = tf.Session()
55 | sess.run(tf.global_variables_initializer())
56 | saver = tf.train.Saver(max_to_keep=100)
57 | saver.restore(sess, pretrained_model_file)
58 | print 'finished reload.'
59 |
60 |
61 | # updating popmean for faster evaluation
62 |
63 | update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
64 | updates = tf.group(*update_ops)
65 | with tf.control_dependencies([updates]):
66 | proj_update = proj * 1
67 | latent_update = latent * 1
68 | dis_udpate = dis * 1
69 | if use_latent > 0:
70 | dis_latent_update = dis_latent * 1
71 |
72 | if use_latent > 0:
73 | _,_,_,_,_, = sess.run([proj_update, latent_update, dis_udpate, dis_latent_update, updates],
74 | feed_dict={images_tf: ref_batch})
75 | else:
76 | _,_,_,_, = sess.run([proj_update, latent_update, dis_udpate, updates],
77 | feed_dict={images_tf: ref_batch})
78 |
79 | updated_folder = '%s/update' % (pretrained_folder)
80 | if not os.path.exists(updated_folder):
81 | os.makedirs(updated_folder)
82 | update_file = '%s/model_iter-%d' % (updated_folder, iter)
83 | saver.save(sess, update_file)
84 |
--------------------------------------------------------------------------------
/projector/run_celeb.sh:
--------------------------------------------------------------------------------
1 | IMG_SIZE=64
2 | TRIAL=1
3 | PRETRAIN_RECON=0
4 | BATCH_SIZE=50 # reference batch included
5 | N_REFERENCE=25
6 | DPERIOD=1
7 | GPERIOD=1
8 | LEARNING_RATE_PROJ=2e-4
9 | LEARNING_RATE_DIS=2e-4 # 2e-4 in context encoder, 2e-4 in dcgan, 5e-5 in wgan
10 | WEIGHT_DECAY_RATE=0 #1e-6
11 | LAMBDA_RATIO=1e-2
12 | LAMBDA_L2=5e-3
13 | LAMBDA_LATENT=1e-4
14 | LAMBDA_IMG=1e-3
15 | LAMBDA_DE=1.0
16 | DE_DECAY_RATE=1.0
17 | SOFT_POS=0.85
18 | CONT_NOISE=1
19 | NOISE_STD=0.5
20 | USE_SPATIAL_VARYING_NOISE=1
21 | UNIFORM_NOISE_MAX=1.732 # 1.732 (sqrt(3) to retain the std) # (wrong) 3.464 (sqrt(12) to retain the standard deviation)
22 | MIN_SPATIALLY_CONTINOUS_NOISE_FACTOR=0.01
23 | MAX_SPATIALLY_CONTINOUS_NOISE_FACTOR=0.1
24 | PRETRAIN_ITER=0
25 | ADAM_BETA1_D=0.5 # 0.5 in all the papers
26 | ADAM_BETA2_D=0.999
27 | ADAM_EPS_D=1e-8
28 | ADAM_BETA1_G=0.9 # 0.5 in all the papers
29 | ADAM_BETA2_G=0.999
30 | ADAM_EPS_G=1e-6
31 | BASE_FOLDER='model'
32 | USE_TENSORBOARD=1
33 | TENSORBOARD_PERIOD=30
34 | OUTPUT_IMG=0
35 | OUTPUT_IMG_PERIOD=200
36 | CLIP_INPUT=0
37 | CLIP_INPUT_BOUND=10.0
38 | CLAMP_WEIGHT=1
39 | CLAMP_LOWER=-10.0
40 | CLAMP_UPPER=10.0
41 |
42 |
43 | STD_FOLDER='std_outputs/'${BASE_FOLDER}
44 |
45 | if [ ! -d 'std_outputs' ]; then
46 | mkdir 'std_outputs'
47 | fi
48 |
49 | if [ ! -d ${STD_FOLDER} ]; then
50 | mkdir ${STD_FOLDER}
51 | fi
52 |
53 | STD_FOLDER+='/'ratio${LAMBDA_RATIO}_dis${LAMBDA_L2}_latent${LAMBDA_LATENT}_img${LAMBDA_IMG}_de${LAMBDA_DE}_derate${DE_DECAY_RATE}_dp${DPERIOD}_gd${GPERIOD}_softpos${SOFT_POS}
54 |
55 | if [ ! -d ${STD_FOLDER} ]; then
56 | mkdir ${STD_FOLDER}
57 | fi
58 |
59 | SCRIPT_NAME=${0##*/}
60 |
61 |
62 | python -u main.py \
63 | --img_size $IMG_SIZE \
64 | --Dperiod $DPERIOD \
65 | --Gperiod $GPERIOD \
66 | --clamp_lower $CLAMP_LOWER \
67 | --clamp_upper $CLAMP_UPPER \
68 | --clamp_weight $CLAMP_WEIGHT \
69 | --batch_size $BATCH_SIZE \
70 | --n_reference $N_REFERENCE \
71 | --learning_rate_val_proj $LEARNING_RATE_PROJ \
72 | --learning_rate_val_dis $LEARNING_RATE_DIS\
73 | --weight_decay_rate $WEIGHT_DECAY_RATE \
74 | --one_sided_label_smooth $SOFT_POS \
75 | --lambda_ratio $LAMBDA_RATIO \
76 | --lambda_l2 $LAMBDA_L2 \
77 | --lambda_latent $LAMBDA_LATENT \
78 | --lambda_img $LAMBDA_IMG \
79 | --lambda_de $LAMBDA_DE \
80 | --de_decay_rate $DE_DECAY_RATE \
81 | --noise_std $NOISE_STD \
82 | --continuous_noise $CONT_NOISE \
83 | --use_spatially_varying_uniform_on_top $USE_SPATIAL_VARYING_NOISE \
84 | --uniform_noise_max $UNIFORM_NOISE_MAX \
85 | --min_spatially_continuous_noise_factor $MIN_SPATIALLY_CONTINOUS_NOISE_FACTOR \
86 | --max_spatially_continuous_noise_factor $MAX_SPATIALLY_CONTINOUS_NOISE_FACTOR \
87 | --adam_beta1_d $ADAM_BETA1_D \
88 | --adam_beta2_d $ADAM_BETA2_D \
89 | --adam_eps_d $ADAM_EPS_D \
90 | --adam_beta1_g $ADAM_BETA1_G \
91 | --adam_beta2_g $ADAM_BETA2_G \
92 | --adam_eps_g $ADAM_EPS_G \
93 | --base_folder $BASE_FOLDER \
94 | --pretrained_iter $PRETRAIN_ITER \
95 | --use_tensorboard $USE_TENSORBOARD \
96 | --tensorboard_period $TENSORBOARD_PERIOD \
97 | --output_img $OUTPUT_IMG \
98 | --output_img_period $OUTPUT_IMG_PERIOD \
99 | --clip_input $CLIP_INPUT \
100 | --clip_input_bound $CLIP_INPUT_BOUND \
101 | > >(tee ${STD_FOLDER}/${SCRIPT_NAME}_trail${TRIAL}.out) \
102 | 2> >(tee ${STD_FOLDER}/${SCRIPT_NAME}_trail${TRIAL}.err >&2)
103 |
--------------------------------------------------------------------------------
/admm/solver_paper.py:
--------------------------------------------------------------------------------
1 |
2 | import numpy as np
3 | import scipy as sp
4 | import scipy.misc
5 | from scipy.sparse.linalg import LinearOperator
6 | import matplotlib.pyplot as plt
7 | import matplotlib
8 | from vec import vec
9 | import timeit
10 | import os
11 |
12 |
13 | def vec(x):
14 | return x.ravel(order='F')
15 |
16 |
17 | def sigmoid(x):
18 | return 1/(1+np.exp(-x))
19 |
20 |
21 | # A_fun, AT_fun takes a vector (d,1) or (d,) as input
22 | def solve(y, A_fun, AT_fun, denoiser, reshape_img_fun, base_folder, show_img_progress=False, alpha=0.2, max_iter=100, solver_tol=1e-6):
23 | """ See Wang, Yu, Wotao Yin, and Jinshan Zeng. "Global convergence of ADMM in nonconvex nonsmooth optimization."
24 | arXiv preprint arXiv:1511.06324 (2015).
25 | It provides convergence condition: basically with large enough alpha, the program will converge. """
26 |
27 | #result_folder = '%s/iter-imgs' % base_folder
28 | #if not os.path.exists(result_folder):
29 | #os.makedirs(result_folder)
30 |
31 | obj_lss = np.zeros(max_iter)
32 | x_zs = np.zeros(max_iter)
33 | u_norms = np.zeros(max_iter)
34 | times = np.zeros(max_iter)
35 |
36 | ATy = AT_fun(y)
37 | x_shape = ATy.shape
38 | d = np.prod(x_shape)
39 |
40 | def A_cgs_fun(x):
41 | x = np.reshape(x, x_shape, order='F')
42 | y = AT_fun(A_fun(x)) + alpha * x
43 | return vec(y)
44 | A_cgs = LinearOperator((d,d), matvec=A_cgs_fun, dtype='float')
45 |
46 | def compute_p_inv_A(b, z0):
47 | (z,info) = sp.sparse.linalg.cgs(A_cgs, vec(b), x0=vec(z0), tol=1e-2)
48 | if info > 0:
49 | print 'cgs convergence to tolerance not achieved'
50 | elif info <0:
51 | print 'cgs gets illegal input or breakdown'
52 | z = np.reshape(z, x_shape, order='F')
53 | return z
54 |
55 |
56 | def A_cgs_fun_init(x):
57 | x = np.reshape(x, x_shape, order='F')
58 | y = AT_fun(A_fun(x))
59 | return vec(y)
60 | A_cgs_init = LinearOperator((d,d), matvec=A_cgs_fun_init, dtype='float')
61 |
62 | def compute_init(b, z0):
63 | (z,info) = sp.sparse.linalg.cgs(A_cgs_init, vec(b), x0=vec(z0), tol=1e-2)
64 | if info > 0:
65 | print 'cgs convergence to tolerance not achieved'
66 | elif info <0:
67 | print 'cgs gets illegal input or breakdown'
68 | z = np.reshape(z, x_shape, order='F')
69 | return z
70 |
71 | # initialize z and u
72 | z = compute_init(ATy, ATy)
73 |
74 | u = np.zeros(x_shape)
75 |
76 | plot_normalozer = matplotlib.colors.Normalize(vmin=0.0, vmax=1.0, clip=True)
77 |
78 | start_time = timeit.default_timer()
79 |
80 | for iter in range(max_iter):
81 |
82 | # x-update
83 | net_input = z+u
84 | x = np.reshape(denoiser(net_input), x_shape, order='F')
85 |
86 | # z-update
87 | b = ATy + alpha * (x - u)
88 | z = compute_p_inv_A(b, z)
89 |
90 | # u-update
91 | u += z - x;
92 |
93 |
94 | if show_img_progress == True:
95 |
96 | fig = plt.figure('current_sol')
97 | plt.gcf().clear()
98 | fig.canvas.set_window_title('iter %d' % iter)
99 | plt.subplot(1,3,1)
100 | plt.imshow(reshape_img_fun(np.clip(x, 0.0, 1.0)), interpolation='nearest', norm=plot_normalozer)
101 | plt.title('x')
102 | plt.subplot(1,3,2)
103 | plt.imshow(reshape_img_fun(np.clip(z, 0.0, 1.0)), interpolation='nearest', norm=plot_normalozer)
104 | plt.title('z')
105 | plt.subplot(1,3,3)
106 | plt.imshow(reshape_img_fun(np.clip(net_input, 0.0, 1.0)), interpolation='nearest', norm=plot_normalozer)
107 | plt.title('netin')
108 | plt.pause(0.00001)
109 |
110 |
111 | obj_ls = 0.5 * np.sum(np.square(y - A_fun(x)))
112 | x_z = np.sqrt(np.mean(np.square(x-z)))
113 | u_norm = np.sqrt(np.mean(np.square(u)))
114 |
115 | print 'iter = %d: obj_ls = %.3e |x-z| = %.3e u_norm = %.3e' % (iter, obj_ls, x_z, u_norm)
116 |
117 |
118 | obj_lss[iter] = obj_ls
119 | x_zs[iter] = x_z
120 | u_norms[iter] = u_norm
121 | times[iter] = timeit.default_timer() - start_time
122 |
123 | ## save images
124 | #filename = '%s/%d-x.jpg' % (result_folder, iter)
125 | #sp.misc.imsave(filename, sp.misc.imresize((reshape_img_fun(np.clip(x, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
126 | #filename = '%s/%d-z.jpg' % (result_folder, iter)
127 | #sp.misc.imsave(filename, sp.misc.imresize((reshape_img_fun(np.clip(z, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
128 | #filename = '%s/%d-u.jpg' % (result_folder, iter)
129 | #sp.misc.imsave(filename, sp.misc.imresize((reshape_img_fun(np.clip(u, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
130 |
131 |
132 |
133 | #_ = raw_input('')
134 | if x_z < solver_tol:
135 | break
136 |
137 |
138 |
139 |
140 | infos = {'obj_lss': obj_lss, 'x_zs': x_zs, 'u_norms': u_norms,
141 | 'times': times, 'alpha':alpha,
142 | 'max_iter':max_iter, 'solver_tol':solver_tol}
143 |
144 | return (x, z, u, infos)
145 |
--------------------------------------------------------------------------------
/projector/load_imagenet.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import os
3 | import numpy as np
4 | import glob
5 | import os
6 | import timeit
7 | import scipy as sp
8 | import pickle
9 |
10 |
11 |
12 | dataset_base_path = os.path.expanduser("~/datasets/imagenet")
13 | trainset_path = dataset_base_path + '/' + 'train'
14 | validset_path = dataset_base_path + '/' + 'valid'
15 | testset_path = dataset_base_path + '/' + 'test'
16 |
17 | trainset_pickle_path = dataset_base_path + '/' + 'train_filename.pickle'
18 | validset_pickle_path = dataset_base_path + '/' + 'valid_filename.pickle'
19 | testset_pickle_path = dataset_base_path + '/' + 'test_filename.pickle'
20 |
21 |
22 | def load_pickle(pickle_path, dataset_path):
23 | if not os.path.exists(pickle_path):
24 |
25 | import magic
26 |
27 | image_files = []
28 | for dir, _, _, in os.walk(dataset_path):
29 | filenames = glob.glob( os.path.join(dir, '*.JPEG')) # may be JPEG, depending on your image files
30 | image_files.append(filenames)
31 |
32 | ## use magic to perform a simple check of the images
33 | # import magic
34 | # for filename in filenames:
35 | # if magic.from_file(filename, mime=True) == 'image/jpeg':
36 | # image_files.append(filename)
37 | # else:
38 | # print '%s is not a jpeg!' % filename
39 | # print magic.from_file(filename)
40 |
41 | if len(image_files) > 0:
42 | image_files = np.hstack(image_files)
43 |
44 | dataset_filenames = {'image_path':image_files}
45 | pickle.dump( dataset_filenames, open( pickle_path, "wb" ) )
46 | else:
47 | dataset_filenames = pickle.load( open( pickle_path, "rb" ) )
48 | return dataset_filenames
49 |
50 |
51 | # return a pd object
52 | def load_trainset_path():
53 | return load_pickle(trainset_pickle_path, trainset_path)
54 |
55 | def load_validset_path():
56 | return load_pickle(validset_pickle_path, validset_path)
57 |
58 | def load_testset_path():
59 | return load_pickle(testset_pickle_path, testset_path)
60 |
61 |
62 | # return a list containing all the filenames
63 | def load_trainset_path_list():
64 | return load_trainset_path()['image_path'].tolist()
65 |
66 | def load_validset_path_list():
67 | return load_validset_path()['image_path'].tolist()
68 |
69 | def load_testset_path_list():
70 | return load_testset_path()['image_path'].tolist()
71 |
72 | def load_image( path, pre_height=146, pre_width=146, height=128, width=128 ):
73 |
74 | import skimage.io
75 | import skimage.transform
76 |
77 | try:
78 | img = skimage.io.imread( path ).astype( float )
79 | except:
80 | return None
81 |
82 | img /= 255.
83 |
84 | if img is None: return None
85 | if len(img.shape) < 2: return None
86 | if len(img.shape) == 4: return None
87 | if len(img.shape) == 2: img=np.tile(img[:,:,None], 3)
88 | if img.shape[2] == 4: img=img[:,:,:3]
89 | if img.shape[2] > 4: return None
90 |
91 | short_edge = min( img.shape[:2] )
92 | yy = int((img.shape[0] - short_edge) / 2)
93 | xx = int((img.shape[1] - short_edge) / 2)
94 | crop_img = img[yy:yy+short_edge, xx:xx+short_edge]
95 | resized_img = skimage.transform.resize( crop_img, [pre_height,pre_width] )
96 |
97 | rand_y = np.random.randint(0, pre_height - height)
98 | rand_x = np.random.randint(0, pre_width - width)
99 |
100 | resized_img = resized_img[ rand_y:rand_y+height, rand_x:rand_x+width, : ]
101 |
102 | resized_img -= 0.5
103 | resized_img /= 2.0
104 |
105 | return resized_img #(resized_img - 127.5)/127.5
106 |
107 |
108 | def cache_batch(trainset, queue, batch_size, num_prepare, rseed=None, identifier=None):
109 |
110 | np.random.seed(rseed)
111 |
112 | current_idx = 0
113 | n_train = len(trainset)
114 | trainset.index = range(n_train)
115 | trainset = trainset.ix[np.random.permutation(n_train)]
116 | idx = 0
117 | while True:
118 |
119 | # read in data if the queue is too short
120 | while queue.qsize() < num_prepare:
121 | start = timeit.default_timer()
122 | image_paths = trainset[idx:idx+batch_size]['image_path'].values
123 | images_ori = map(lambda x: load_image( x ), image_paths)
124 | X = np.asarray(images_ori)
125 | # put in queue
126 | queue.put(X) # block until free slot is available
127 | idx += batch_size
128 | if idx + batch_size > n_train: #reset when last batch is smaller than batch_size or reaching the last batch
129 | trainset = trainset.ix[np.random.permutation(n_train)]
130 | idx = 0
131 |
132 |
133 |
134 | def cache_train_batch_cube(queue, batch_size, num_prepare, identifier=None):
135 | trainset = load_pickle(trainset_path, dataset_path)
136 | cache_batch(trainset, queue, batch_size, num_prepare)
137 |
138 | def cache_test_batch_cube(queue, batch_size, num_prepare, identifier=None):
139 | testset = load_pickle(testset_path, dataset_path)
140 | cache_batch(testset, queue, batch_size, num_prepare)
141 |
142 |
143 | def cache_batch_list_style(trainset, Xlist, batch_size, num_prepare, identifier=None):
144 |
145 | current_idx = 0
146 | n_train = len(trainset)
147 | trainset.index = range(n_train)
148 | trainset = trainset.ix[np.random.permutation(n_train)]
149 | idx = 0
150 | while True:
151 |
152 | # read in data if the queue is too short
153 | while len(Xlist) < num_prepare:
154 | image_paths = trainset[idx:idx+batch_size]['image_path'].values
155 | images_ori = map(lambda x: load_image( x ), image_paths)
156 | X = np.asarray(images_ori, dtype=float)
157 | Xlist.append(X)
158 | idx += batch_size
159 | if idx + batch_size > n_train: #reset when last batch is smaller than batch_size or reaching the last batch
160 | trainset = trainset.ix[np.random.permutation(n_train)]
161 | idx = 0
162 |
163 | if __name__ == "__main__":
164 | trainset = load_trainset_path_list() #
165 | validset = load_validset_path_list()
166 | testset = load_testset_path_list() #
167 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # One-Network-to-Solve-Them-All
2 | It is a Tensorflow implementation of our paper One Network to Solve Them All --- Solving Linear Inverse Problems using Deep Projection Models. If you find our paper or implementation useful in your research, please cite:
3 |
4 |
5 |
6 |
7 |
8 |
9 | @article{chang2017projector,
10 | title={One Network to Solve Them All ---
11 | Solving Linear Inverse Problems using Deep Projection Models},
12 | author={J. H. Rick Chang and
13 | Chun-Liang Li and
14 | Barnab{\'a}s P{\'o}czos and
15 | B. V. K. Vijaya Kumar and
16 | Aswin C. Sankaranarayanan},
17 | journal={arXiv preprint arXiv:1703.09912},
18 | year={2017}
19 | }
20 |
21 | |
22 |  |
23 |
24 |
25 |
26 |
27 | ## Brief introduction
28 | The goal of the proposed framework is to solve linear inverse problems of the following form:
29 |
where y is the linear measurements, e.g., a low-resolution image, A is the linear operator that generates y from an image x. In image super-resolution, A can indicate direct downsampling or box averaging. The optimization problem is solved with a constraint that the solution x lies in the natural image set X.
30 |
31 | To solve the optimization problem, we found that in proximal algorithms like alternating direction method of multipliers (ADMM), the constraint usually appears in solving a subproblem --- projecting current estimate of x to the set X. Thereby, we propose to learn the projection operator with a deep neural net. Since the projection opereator is independent to individual linear operator A, once the network is trained, it can be used in any linear inverse problem. Since we do not have the exaxt definition of the natural image set, we use the decision boundary of a classifier to approximate the set.
32 |
33 | There are multiple methods to achieve this approximation. For example, given a large image dataset, we can create nonimage signals by perturbing the images in the dataset and then train a classifier to differentiate the two classes. While this method is simple, the decision boundary will be loose. To get a tighter approximation, we found that during the training process, the projected images of the projection network become closer and closer to the natural image set. Thus, if we use these projected images as negative instances, we will learn a tighter decision boundary. This framework is motivated by adversarial generative net.
34 |
35 | Once the projection network is trained, we can solve any linear inverse problem with ADMM. An illustration of the testing process is shown below.
36 |
37 |

38 |
39 |
40 |
41 |
42 | ## Prerequest
43 | The code is tested under Ubuntu 16.04 with CUDA 8.0 on Titan X Pascal and GTX 1080. We use Python 2.7 and Tensorflow 0.12.1.
44 |
45 | We train the model on two datasets, MS-CELEB-1M dataset and ImageNet dataset. The dataset should be plased under ~/dataset. For example, we put MS-CELEB-1M dataset at ~/dataset/celeb-1m. We load the datasets via load_celeb.py and load_imagenet.py, both can be easily adapt to other datasets. In this tutorial, we take MS-CELEB-1M as an example to illustrate how to use our code. For ImageNet, the usage is alomst the same by replacing ``import load_celeb`` with ``import load_imagenet``. Please see the comments in these files for more information.
46 |
47 | ## Train a Projector
48 | ```bash
49 | cd projector
50 | source run_celeb.sh
51 | ```
52 | The above steps train a projection network on MS-CELEB-1M dataset. Please refer to our paper for the details of parameters. The model files are saved in ```model``` directory.
53 |
54 | ## Run ADMM to solve the Linear Inverse Problems
55 | We have to preprocess the reference batch used in virtual batch normalization for testing. Note that you need to modifiy the filepath of your trained model!
56 | ```bash
57 | cd admm
58 | python update_popmean.py
59 | ```
60 | We then run demo script for differet linear inverse problems. Likewise, you need to modifiy the filepath of your updated model!
61 | ```bash
62 | python paper_demo.py
63 | ```
64 | In our experience, models trained for 50,000 iterations should give you the result similar to we reported in the paper. Note that you may need to adjust the value of alpha (the penalty parameter) for each task and different hyper-parameters used to train the model.
65 |
66 | Here are some sampled result reported in the papers.
67 |
68 |
69 |
70 |
71 | ## Trained models
72 | The trained model used in the paper can be found here. A newer version of the model that uses imresize by nearest neighbor algorithm to replace upsampling/downsampling by stride is here. We found that using imresize to perform upsampling and downsampling provides more stable projectors. We have not fully explored this method, so the resulted images may look blurrier than the original model used in the paper.
73 |
74 | To use these models, you need to modify the filepath in admm/update_popmean.py and admm/paper_demo.py. Check the comments in these files. Also note that the alpha in admm/paper_demo.py depends on the dataset, the model, and the problem itself. So like solving the traditional LASSO problems, you need to tune alpha to get nice results. In the file admm/paper_demo.py we provide the values used in the paper to solve the ms-celeb-1m dataset. They provide a good starting point for other datasets and models.
75 |
76 | ## Acknowledgement
77 | Part of our code is based on https://github.com/jazzsaxmafia/Inpainting
78 |
79 |
--------------------------------------------------------------------------------
/admm/solver_l1.py:
--------------------------------------------------------------------------------
1 |
2 | import numpy as np
3 | import scipy as sp
4 | from scipy.sparse.linalg import LinearOperator
5 | import matplotlib
6 | import matplotlib.pyplot as plt
7 | from vec import vec
8 | import timeit
9 | import pywt
10 | import os
11 |
12 | def vec(x):
13 | return x.ravel(order='F')
14 |
15 |
16 | def sigmoid(x):
17 | return 1/(1+np.exp(-x))
18 |
19 |
20 | def wavelet_transform(x):
21 | w_coeffs_rgb = [] # np.zeros(x.shape[3], np.prod(x.shape))
22 | for i in range(x.shape[3]):
23 | w_coeffs_list = pywt.wavedec2(x[0,:,:,i], 'db4', level=None, mode='periodization')
24 | w_coeffs, coeff_slices = pywt.coeffs_to_array(w_coeffs_list)
25 | w_coeffs_rgb.append(w_coeffs)
26 |
27 | w_coeffs_rgb = np.array(w_coeffs_rgb)
28 | return w_coeffs_rgb, coeff_slices
29 |
30 |
31 | def inverse_wavelet_transform(w_coeffs_rgb, coeff_slices, x_shape):
32 | x_hat = np.zeros(x_shape)
33 | for i in range(w_coeffs_rgb.shape[0]):
34 | w_coeffs_list = pywt.array_to_coeffs(w_coeffs_rgb[i,:,:], coeff_slices)
35 | x_hat[0,:,:,i] = pywt.waverecn(w_coeffs_list, wavelet='db4', mode='periodization')
36 | return x_hat
37 |
38 |
39 | def soft_threshold(x, beta):
40 | y = np.maximum(0, x-beta) - np.maximum(0, -x-beta)
41 | return y
42 |
43 |
44 |
45 | # A_fun, AT_fun takes a vector (d,1) or (d,) as input
46 | def solve(y, A_fun, AT_fun, lambda_l1, reshape_img_fun, base_folder, show_img_progress=False, alpha=0.2, max_iter=100, solver_tol=1e-6):
47 | """ See Wang, Yu, Wotao Yin, and Jinshan Zeng. "Global convergence of ADMM in nonconvex nonsmooth optimization."
48 | arXiv preprint arXiv:1511.06324 (2015).
49 | It provides convergence condition: basically with large enough alpha, the program will converge. """
50 |
51 | #result_folder = '%s/iter-imgs' % base_folder
52 | #if not os.path.exists(result_folder):
53 | #os.makedirs(result_folder)
54 |
55 | obj_lss = np.zeros(max_iter)
56 | x_zs = np.zeros(max_iter)
57 | u_norms = np.zeros(max_iter)
58 | times = np.zeros(max_iter)
59 |
60 | ATy = AT_fun(y)
61 | x_shape = ATy.shape
62 | d = np.prod(x_shape)
63 |
64 | def A_cgs_fun(x):
65 | x = np.reshape(x, x_shape, order='F')
66 | y = AT_fun(A_fun(x)) + alpha * x
67 | return vec(y)
68 | A_cgs = LinearOperator((d,d), matvec=A_cgs_fun, dtype='float')
69 |
70 | def compute_p_inv_A(b, z0):
71 | (z,info) = sp.sparse.linalg.cgs(A_cgs, vec(b), x0=vec(z0), tol=1e-3, maxiter=100)
72 | if info > 0:
73 | print 'cgs convergence to tolerance not achieved'
74 | elif info <0:
75 | print 'cgs gets illegal input or breakdown'
76 | z = np.reshape(z, x_shape, order='F')
77 | return z
78 |
79 |
80 | def A_cgs_fun_init(x):
81 | x = np.reshape(x, x_shape, order='F')
82 | y = AT_fun(A_fun(x))
83 | return vec(y)
84 | A_cgs_init = LinearOperator((d,d), matvec=A_cgs_fun_init, dtype='float')
85 |
86 | def compute_init(b, z0):
87 | (z,info) = sp.sparse.linalg.cgs(A_cgs_init, vec(b), x0=vec(z0), tol=1e-2)
88 | if info > 0:
89 | print 'cgs convergence to tolerance not achieved'
90 | elif info <0:
91 | print 'cgs gets illegal input or breakdown'
92 | z = np.reshape(z, x_shape, order='F')
93 | return z
94 |
95 | # initialize z and u
96 | z = compute_init(ATy, ATy)
97 | u = np.zeros(x_shape)
98 |
99 |
100 | plot_normalozer = matplotlib.colors.Normalize(vmin=0.0, vmax=1.0, clip=True)
101 |
102 |
103 | start_time = timeit.default_timer()
104 |
105 | for iter in range(max_iter):
106 |
107 | # x-update
108 | net_input = z+u
109 | Wzu, wbook = wavelet_transform(net_input)
110 | q = soft_threshold(Wzu, lambda_l1/alpha)
111 | x = inverse_wavelet_transform(q, wbook, x_shape)
112 | x = np.reshape(x, x_shape)
113 |
114 | # z-update
115 | b = ATy + alpha * (x - u)
116 | z = compute_p_inv_A(b, z)
117 |
118 | # u-update
119 | u += z - x;
120 |
121 | if show_img_progress == True:
122 |
123 | fig = plt.figure('current_sol')
124 | plt.gcf().clear()
125 | fig.canvas.set_window_title('iter %d' % iter)
126 | plt.subplot(1,3,1)
127 | plt.imshow(reshape_img_fun(np.clip(x, 0.0, 1.0)), interpolation='nearest', norm=plot_normalozer)
128 | plt.title('x')
129 | plt.subplot(1,3,2)
130 | plt.imshow(reshape_img_fun(np.clip(z, 0.0, 1.0)), interpolation='nearest', norm=plot_normalozer)
131 | plt.title('z')
132 | plt.subplot(1,3,3)
133 | plt.imshow(reshape_img_fun(np.clip(net_input, 0.0, 1.0)), interpolation='nearest', norm=plot_normalozer)
134 | plt.title('netin')
135 | plt.pause(0.00001)
136 |
137 |
138 | obj_ls = 0.5 * np.sum(np.square(y - A_fun(x)))
139 | x_z = np.sqrt(np.mean(np.square(x-z)))
140 | u_norm = np.sqrt(np.mean(np.square(u)))
141 |
142 | print 'iter = %d: obj_ls = %.3e |x-z| = %.3e u_norm = %.3e' % (iter, obj_ls, x_z, u_norm)
143 |
144 |
145 | obj_lss[iter] = obj_ls
146 | x_zs[iter] = x_z
147 | u_norms[iter] = u_norm
148 | times[iter] = timeit.default_timer() - start_time
149 |
150 |
151 | ## save images
152 | #filename = '%s/%d-x.jpg' % (result_folder, iter)
153 | #sp.misc.imsave(filename, sp.misc.imresize((reshape_img_fun(np.clip(x, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
154 | #filename = '%s/%d-z.jpg' % (result_folder, iter)
155 | #sp.misc.imsave(filename, sp.misc.imresize((reshape_img_fun(np.clip(z, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
156 | #filename = '%s/%d-u.jpg' % (result_folder, iter)
157 | #sp.misc.imsave(filename, sp.misc.imresize((reshape_img_fun(np.clip(u, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
158 |
159 | #_ = raw_input('')
160 |
161 | if x_z < solver_tol:
162 | break
163 |
164 | infos = {'obj_lss': obj_lss, 'x_zs': x_zs, 'u_norms': u_norms,
165 | 'times': times, 'alpha':alpha, 'lambda_l1':lambda_l1,
166 | 'max_iter':max_iter, 'solver_tol':solver_tol}
167 |
168 |
169 | return (x, z, u, infos)
170 |
--------------------------------------------------------------------------------
/projector/load_celeb.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import os
3 | import numpy as np
4 | import glob
5 | import os
6 | import timeit
7 | import scipy as sp
8 | import pickle
9 |
10 |
11 | # the dataset is put at "dataset_base_path".
12 | # In the folder, there should be three subfolders: "train", "valid", "test", each containing
13 | # the training images, validation images, and test images, respectively.
14 | # Note that these images can also be contained in subfolders.
15 | dataset_base_path = os.path.expanduser("~/datasets/celeb-1m")
16 |
17 |
18 | trainset_path = dataset_base_path + '/' + 'train'
19 | validset_path = dataset_base_path + '/' + 'valid'
20 | testset_path = dataset_base_path + '/' + 'test'
21 |
22 | trainset_pickle_path = dataset_base_path + '/' + 'train_filename.pickle'
23 | validset_pickle_path = dataset_base_path + '/' + 'valid_filename.pickle'
24 | testset_pickle_path = dataset_base_path + '/' + 'test_filename.pickle'
25 |
26 |
27 | def load_pickle(pickle_path, dataset_path):
28 | if not os.path.exists(pickle_path):
29 |
30 | image_files = []
31 | for dir, _, _, in os.walk(dataset_path):
32 | filenames = glob.glob( os.path.join(dir, '*.jpg')) # may be JPEG, depending on your image files
33 | image_files.append(filenames)
34 |
35 | ## use magic to perform a simple check of the images
36 | # import magic
37 | # for filename in filenames:
38 | # if magic.from_file(filename, mime=True) == 'image/jpeg':
39 | # image_files.append(filename)
40 | # else:
41 | # print '%s is not a jpeg!' % filename
42 | # print magic.from_file(filename)
43 |
44 | if len(image_files) > 0:
45 | image_files = np.hstack(image_files)
46 |
47 | dataset_filenames = {'image_path':image_files}
48 | pickle.dump( dataset_filenames, open( pickle_path, "wb" ) )
49 | else:
50 | dataset_filenames = pickle.load( open( pickle_path, "rb" ) )
51 | return dataset_filenames
52 |
53 |
54 | # return a pd object
55 | def load_trainset_path():
56 | return load_pickle(trainset_pickle_path, trainset_path)
57 |
58 | def load_validset_path():
59 | return load_pickle(validset_pickle_path, validset_path)
60 |
61 | def load_testset_path():
62 | return load_pickle(testset_pickle_path, testset_path)
63 |
64 |
65 | # return a list containing all the filenames
66 | def load_trainset_path_list():
67 | return load_trainset_path()['image_path'].tolist()
68 |
69 | def load_validset_path_list():
70 | return load_validset_path()['image_path'].tolist()
71 |
72 | def load_testset_path_list():
73 | return load_testset_path()['image_path'].tolist()
74 |
75 | # output image range: [-1,1)!!
76 | def load_image( path, pre_height=146, pre_width=146, height=128, width=128 ):
77 |
78 | import skimage.io
79 | import skimage.transform
80 |
81 | try:
82 | img = skimage.io.imread( path ).astype( float )
83 | except:
84 | return None
85 |
86 | img /= 255.
87 |
88 | if img is None: return None
89 | if len(img.shape) < 2: return None
90 | if len(img.shape) == 4: return None
91 | if len(img.shape) == 2: img=np.tile(img[:,:,None], 3)
92 | if img.shape[2] == 4: img=img[:,:,:3]
93 | if img.shape[2] > 4: return None
94 |
95 | short_edge = min( img.shape[:2] )
96 | yy = int((img.shape[0] - short_edge) / 2)
97 | xx = int((img.shape[1] - short_edge) / 2)
98 | crop_img = img[yy:yy+short_edge, xx:xx+short_edge]
99 | resized_img = skimage.transform.resize( crop_img, [pre_height,pre_width] )
100 |
101 | rand_y = np.random.randint(0, pre_height - height)
102 | rand_x = np.random.randint(0, pre_width - width)
103 |
104 | resized_img = resized_img[ rand_y:rand_y+height, rand_x:rand_x+width, : ]
105 |
106 | resized_img -= 0.5
107 | resized_img /= 2.0
108 |
109 | return resized_img #(resized_img - 127.5)/127.5
110 |
111 |
112 | def cache_batch(trainset, queue, batch_size, num_prepare, rseed=None, identifier=None):
113 |
114 | np.random.seed(rseed)
115 |
116 | current_idx = 0
117 | n_train = len(trainset)
118 | trainset.index = range(n_train)
119 | trainset = trainset.ix[np.random.permutation(n_train)]
120 | idx = 0
121 | while True:
122 |
123 | # read in data if the queue is too short
124 | while queue.qsize() < num_prepare:
125 | start = timeit.default_timer()
126 | image_paths = trainset[idx:idx+batch_size]['image_path'].values
127 | images_ori = map(lambda x: load_image( x ), image_paths)
128 | X = np.asarray(images_ori)
129 | # put in queue
130 | queue.put(X) # block until free slot is available
131 | idx += batch_size
132 | if idx + batch_size > n_train: #reset when last batch is smaller than batch_size or reaching the last batch
133 | trainset = trainset.ix[np.random.permutation(n_train)]
134 | idx = 0
135 |
136 |
137 |
138 | def cache_train_batch_cube(queue, batch_size, num_prepare, identifier=None):
139 | trainset = load_pickle(trainset_path, dataset_path)
140 | cache_batch(trainset, queue, batch_size, num_prepare)
141 |
142 | def cache_test_batch_cube(queue, batch_size, num_prepare, identifier=None):
143 | testset = load_pickle(testset_path, dataset_path)
144 | cache_batch(testset, queue, batch_size, num_prepare)
145 |
146 |
147 | def cache_batch_list_style(trainset, Xlist, batch_size, num_prepare, identifier=None):
148 |
149 | current_idx = 0
150 | n_train = len(trainset)
151 | trainset.index = range(n_train)
152 | trainset = trainset.ix[np.random.permutation(n_train)]
153 | idx = 0
154 | while True:
155 |
156 | # read in data if the queue is too short
157 | while len(Xlist) < num_prepare:
158 | image_paths = trainset[idx:idx+batch_size]['image_path'].values
159 | images_ori = map(lambda x: load_image( x ), image_paths)
160 | X = np.asarray(images_ori, dtype=float)
161 | Xlist.append(X)
162 | idx += batch_size
163 | if idx + batch_size > n_train: #reset when last batch is smaller than batch_size or reaching the last batch
164 | trainset = trainset.ix[np.random.permutation(n_train)]
165 | idx = 0
166 |
167 | if __name__ == "__main__":
168 | trainset = load_trainset_path_list() #
169 | validset = load_validset_path_list()
170 | testset = load_testset_path_list() #
171 |
--------------------------------------------------------------------------------
/projector/layers.py:
--------------------------------------------------------------------------------
1 | import tensorflow as tf
2 | import numpy as np
3 | from tensorflow.contrib.layers.python.layers import batch_norm as tf_batch_norm
4 | import tensorflow.contrib.slim as slim
5 |
6 | def new_fc_layer(bottom, output_size, name=None, bias=True):
7 | """
8 | fully connected layer
9 | """
10 | shape = bottom.get_shape().as_list()
11 | dim = np.prod( shape[1:] )
12 | x = tf.reshape( bottom, [-1, dim])
13 | input_size = dim
14 |
15 | with tf.variable_scope(name):
16 | w = tf.get_variable(
17 | "W",
18 | shape=[input_size, output_size],
19 | initializer=tf.truncated_normal_initializer(0., 0.005))
20 | if bias == True:
21 | b = tf.get_variable(
22 | "b",
23 | shape=[output_size],
24 | initializer=tf.constant_initializer(0.))
25 | fc = tf.nn.bias_add( tf.matmul(x, w), b)
26 | else:
27 | fc = tf.matmul(x, w)
28 |
29 | return (fc, w)
30 |
31 | def batchnorm(bottom, is_train, num_reference, epsilon=1e-3, decay=0.999, name=None):
32 | """ virtual batch normalization (poor man's version)
33 | the first half is the true batch, the second half is the reference batch.
34 | When num_reference = 0, it is just typical batch normalization.
35 | To use virtual batch normalization in test phase, "update_popmean.py" needed to be executed first
36 | (in order to store the mean and variance of the reference batch into pop_mean and pop_variance of batchnorm.)
37 | """
38 |
39 | batch_size = bottom.get_shape().as_list()[0]
40 | inst_size = batch_size - num_reference
41 | instance_weight = np.ones([batch_size])
42 |
43 | if inst_size > 0:
44 | reference_weight = 1.0 - (1.0 / ( num_reference + 1.0))
45 | instance_weight[0:inst_size] = 1.0 - reference_weight
46 | instance_weight[inst_size:] = reference_weight
47 | else:
48 | decay = 0.0
49 |
50 | return slim.batch_norm(bottom, activation_fn=None, is_training=is_train, decay=decay, scale=True, scope=name, batch_weights=instance_weight)
51 |
52 |
53 | def new_conv_layer(bottom, filter_shape, activation=tf.identity, padding='SAME', stride=1, bias=True, name=None):
54 | """
55 | typical convolution layer using stride to down-sample
56 | """
57 | with tf.variable_scope(name):
58 | w = tf.get_variable(
59 | "W",
60 | shape=filter_shape,
61 | initializer=tf.truncated_normal_initializer(0., 0.005))
62 | conv = tf.nn.conv2d( bottom, w, [1,stride,stride,1], padding=padding)
63 |
64 | if bias == True:
65 | b = tf.get_variable(
66 | "b",
67 | shape=filter_shape[-1],
68 | initializer=tf.constant_initializer(0.))
69 | output = activation(tf.nn.bias_add(conv, b))
70 | else:
71 | output = activation(conv)
72 |
73 | return output
74 |
75 |
76 | def new_deconv_layer(bottom, filter_shape, output_shape, activation=tf.identity, padding='SAME', stride=1, bias=True, name=None):
77 | """
78 | typical deconvolution layer
79 | """
80 | with tf.variable_scope(name):
81 | W = tf.get_variable(
82 | "W",
83 | shape=filter_shape,
84 | initializer=tf.truncated_normal_initializer(0., 0.005))
85 | deconv = tf.nn.conv2d_transpose( bottom, W, output_shape, [1,stride,stride,1], padding=padding)
86 |
87 | if bias == True:
88 | b = tf.get_variable(
89 | "b",
90 | shape=filter_shape[-2],
91 | initializer=tf.constant_initializer(0.))
92 | output = activation(tf.nn.bias_add(deconv, b))
93 | else:
94 | output = activation(deconv)
95 |
96 | return output
97 |
98 |
99 | def channel_wise_fc_layer(bottom, name, bias=True):
100 | """
101 | channel-wise fully connected layer
102 | """
103 | _, width, height, n_feat_map = bottom.get_shape().as_list()
104 | input_reshape = tf.reshape( bottom, [-1, width*height, n_feat_map] ) # order='C'
105 | input_transpose = tf.transpose( input_reshape, [2,0,1] ) # n_feat_map * batch * d
106 |
107 | with tf.variable_scope(name):
108 | W = tf.get_variable(
109 | "W",
110 | shape=[n_feat_map,width*height, width*height], # n_feat_map * d * d_filter
111 | initializer=tf.truncated_normal_initializer(0., 0.005))
112 | output = tf.batch_matmul(input_transpose, W) # n_feat_map * batch * d_filter
113 |
114 | if bias == True:
115 | b = tf.get_variable(
116 | "b",
117 | shape=width*height,
118 | initializer=tf.constant_initializer(0.))
119 | output = tf.nn.bias_add(output, b)
120 |
121 | output_transpose = tf.transpose(output, [1,2,0]) # batch * d_filter * n_feat_map
122 | output_reshape = tf.reshape( output_transpose, [-1, width, height, n_feat_map] )
123 | return output_reshape
124 |
125 |
126 |
127 | def bottleneck(input, is_train, n_reference, channel_compress_ratio=4, stride=1, bias=True, name=None):
128 | """
129 | building block for creating residual net
130 | """
131 | input_shape = input.get_shape().as_list()
132 |
133 | if stride is not 1:
134 | output_channel = input_shape[3] * 2
135 | else:
136 | output_channel = input_shape[3]
137 |
138 | bottleneck_channel = output_channel / channel_compress_ratio
139 |
140 | with tf.variable_scope(name):
141 | bn1 = tf.nn.elu(batchnorm(input, is_train, n_reference, name='bn1'))
142 | # shortcut
143 | if stride is not 1:
144 | shortcut = new_conv_layer(bn1, [1,1,input_shape[3],output_channel], stride=stride, bias=bias, name="conv_sc" )
145 | else:
146 | shortcut = input
147 |
148 | # bottleneck_channel
149 | conv1 = new_conv_layer(bn1, [1,1,input_shape[3],bottleneck_channel], stride=stride, bias=bias, name="conv1" )
150 | bn2 = tf.nn.elu(batchnorm(conv1, is_train, n_reference, name='bn2'))
151 | conv2 = new_conv_layer(bn2, [3,3,bottleneck_channel,bottleneck_channel], stride=1, bias=bias, name="conv2" )
152 | bn3 = tf.nn.elu(batchnorm(conv2, is_train, n_reference, name='bn3'))
153 | conv3 = new_conv_layer(bn3, [1,1,bottleneck_channel,output_channel], stride=1, bias=bias, name="conv3" )
154 |
155 | return shortcut+conv3
156 |
157 |
158 |
159 | def bottleneck_flexible(input, is_train, output_channel, n_reference, channel_compress_ratio=4, stride=1, bias=True, name=None):
160 |
161 | input_shape = input.get_shape().as_list()
162 |
163 | bottleneck_channel = output_channel / channel_compress_ratio
164 |
165 | with tf.variable_scope(name):
166 | bn1 = tf.nn.elu(batchnorm(input, is_train, n_reference, name='bn1'))
167 | # shortcut
168 | if stride is not 1:
169 | shortcut = new_conv_layer(bn1, [1,1,input_shape[3],output_channel], stride=stride, bias=bias, name="conv_sc" )
170 | else:
171 | shortcut = input
172 |
173 | # bottleneck_channel
174 | conv1 = new_conv_layer(bn1, [1,1,input_shape[3],bottleneck_channel], stride=stride, bias=bias, name="conv1" )
175 | bn2 = tf.nn.elu(batchnorm(conv1, is_train, n_reference, name='bn2'))
176 | conv2 = new_conv_layer(bn2, [3,3,bottleneck_channel,bottleneck_channel], stride=1, bias=bias, name="conv2" )
177 | bn3 = tf.nn.elu(batchnorm(conv2, is_train, n_reference, name='bn3'))
178 | conv3 = new_conv_layer(bn3, [1,1,bottleneck_channel,output_channel], stride=1, bias=bias, name="conv3" )
179 |
180 | return shortcut+conv3
181 |
182 |
183 |
184 | def add_bottleneck_module(input, is_train, nBlocks, n_reference, channel_compress_ratio=4, bias=True, name=None):
185 |
186 | with tf.variable_scope(name):
187 | # the first block reduce spatial dimension
188 | out = bottleneck(input, is_train, n_reference, channel_compress_ratio=channel_compress_ratio, stride=2, bias=bias, name='block0')
189 |
190 | for i in range(nBlocks-1):
191 | subname = 'block%d' % (i+1)
192 | out = bottleneck(out, is_train, n_reference, channel_compress_ratio=channel_compress_ratio, stride=1, bias=bias, name=subname)
193 | return out
194 |
195 |
--------------------------------------------------------------------------------
/projector/layers_nearest.py:
--------------------------------------------------------------------------------
1 | import tensorflow as tf
2 | import numpy as np
3 | from tensorflow.contrib.layers.python.layers import batch_norm as tf_batch_norm
4 | import tensorflow.contrib.slim as slim
5 |
6 | def new_fc_layer(bottom, output_size, name=None, bias=True):
7 | """
8 | fully connected layer
9 | """
10 | shape = bottom.get_shape().as_list()
11 | dim = np.prod( shape[1:] )
12 | x = tf.reshape( bottom, [-1, dim])
13 | input_size = dim
14 |
15 | with tf.variable_scope(name):
16 | w = tf.get_variable(
17 | "W",
18 | shape=[input_size, output_size],
19 | initializer=tf.truncated_normal_initializer(0., 0.005))
20 | if bias == True:
21 | b = tf.get_variable(
22 | "b",
23 | shape=[output_size],
24 | initializer=tf.constant_initializer(0.))
25 | fc = tf.nn.bias_add( tf.matmul(x, w), b)
26 | else:
27 | fc = tf.matmul(x, w)
28 |
29 | return (fc, w)
30 |
31 | def batchnorm(bottom, is_train, num_reference, epsilon=1e-3, decay=0.999, name=None):
32 | """ virtual batch normalization (poor man's version)
33 | the first half is the true batch, the second half is the reference batch.
34 | When num_reference = 0, it is just typical batch normalization.
35 | To use virtual batch normalization in test phase, "update_popmean.py" needed to be executed first
36 | (in order to store the mean and variance of the reference batch into pop_mean and pop_variance of batchnorm.)
37 | """
38 |
39 | batch_size = bottom.get_shape().as_list()[0]
40 | inst_size = batch_size - num_reference
41 | instance_weight = np.ones([batch_size])
42 |
43 | if inst_size > 0:
44 | reference_weight = 1.0 - (1.0 / ( num_reference + 1.0))
45 | instance_weight[0:inst_size] = 1.0 - reference_weight
46 | instance_weight[inst_size:] = reference_weight
47 | else:
48 | decay = 0.0
49 |
50 | return slim.batch_norm(bottom, activation_fn=None, is_training=is_train, decay=decay, scale=True, scope=name, batch_weights=instance_weight)
51 |
52 |
53 | def new_conv_layer(bottom, filter_shape, activation=tf.identity, padding='SAME', stride=1, bias=True, name=None):
54 | """
55 | In order to alleviate the checkerboard pattern in the generated images,
56 | the downsample and upsample are performed by nearest-neighbor resizing.
57 | Here, the resizing is performed after convolution.
58 | """
59 | new_stride = 1
60 |
61 | with tf.variable_scope(name):
62 | w = tf.get_variable(
63 | "W",
64 | shape=filter_shape,
65 | initializer=tf.truncated_normal_initializer(0., 0.005))
66 | conv = tf.nn.conv2d( bottom, w, [1,new_stride,new_stride,1], padding=padding)
67 |
68 | if bias == True:
69 | b = tf.get_variable(
70 | "b",
71 | shape=filter_shape[-1],
72 | initializer=tf.constant_initializer(0.))
73 | output = activation(tf.nn.bias_add(conv, b))
74 | else:
75 | output = activation(conv)
76 |
77 |
78 | # resize by nearest neighbor
79 | if stride > 1:
80 | output_shape = output.get_shape().as_list()
81 | output = tf.image.resize_nearest_neighbor(output, [output_shape[1]/stride, output_shape[2]/stride])
82 |
83 | return output
84 |
85 |
86 | def new_deconv_layer(bottom, filter_shape, output_shape, activation=tf.identity, padding='SAME', stride=1, bias=True, name=None):
87 | """
88 | In order to alleviate the checkerboard pattern in the generated images,
89 | the downsample and upsample are performed by nearest-neighbor resizing.
90 | Here, the resizing is performed before convolution.
91 | """
92 | # resize by nearest neighbor
93 | if stride > 1:
94 | bottom = tf.image.resize_nearest_neighbor(bottom, [output_shape[1], output_shape[2]])
95 |
96 | new_stride = 1
97 | new_filter_shape = np.copy(filter_shape)
98 | new_filter_shape[2] = filter_shape[3]
99 | new_filter_shape[3] = filter_shape[2]
100 |
101 | with tf.variable_scope(name):
102 | W = tf.get_variable(
103 | "W",
104 | shape=new_filter_shape,
105 | initializer=tf.truncated_normal_initializer(0., 0.005))
106 | deconv = tf.nn.conv2d(bottom, W, [1,new_stride,new_stride,1], padding=padding)
107 | #deconv = tf.nn.conv2d_transpose( bottom, W, output_shape, [1,new_stride,new_stride,1], padding=padding)
108 |
109 | if bias == True:
110 | b = tf.get_variable(
111 | "b",
112 | shape=filter_shape[-2],
113 | initializer=tf.constant_initializer(0.))
114 | output = activation(tf.nn.bias_add(deconv, b))
115 | else:
116 | output = activation(deconv)
117 |
118 | return output
119 |
120 |
121 | def channel_wise_fc_layer(bottom, name, bias=True):
122 | """
123 | channel-wise fully connected layer
124 | """
125 | _, width, height, n_feat_map = bottom.get_shape().as_list()
126 | input_reshape = tf.reshape( bottom, [-1, width*height, n_feat_map] ) # order='C'
127 | input_transpose = tf.transpose( input_reshape, [2,0,1] ) # n_feat_map * batch * d
128 |
129 | with tf.variable_scope(name):
130 | W = tf.get_variable(
131 | "W",
132 | shape=[n_feat_map,width*height, width*height], # n_feat_map * d * d_filter
133 | initializer=tf.truncated_normal_initializer(0., 0.005))
134 | output = tf.batch_matmul(input_transpose, W) # n_feat_map * batch * d_filter
135 |
136 | if bias == True:
137 | b = tf.get_variable(
138 | "b",
139 | shape=width*height,
140 | initializer=tf.constant_initializer(0.))
141 | output = tf.nn.bias_add(output, b)
142 |
143 | output_transpose = tf.transpose(output, [1,2,0]) # batch * d_filter * n_feat_map
144 | output_reshape = tf.reshape( output_transpose, [-1, width, height, n_feat_map] )
145 | return output_reshape
146 |
147 |
148 |
149 | def bottleneck(input, is_train, n_reference, channel_compress_ratio=4, stride=1, bias=True, name=None):
150 | """
151 | building block for creating residual net
152 | """
153 | input_shape = input.get_shape().as_list()
154 |
155 | if stride is not 1:
156 | output_channel = input_shape[3] * 2
157 | else:
158 | output_channel = input_shape[3]
159 |
160 | bottleneck_channel = output_channel / channel_compress_ratio
161 |
162 | with tf.variable_scope(name):
163 | bn1 = tf.nn.elu(batchnorm(input, is_train, n_reference, name='bn1'))
164 | # shortcut
165 | if stride is not 1:
166 | shortcut = new_conv_layer(bn1, [1,1,input_shape[3],output_channel], stride=stride, bias=bias, name="conv_sc" )
167 | else:
168 | shortcut = input
169 |
170 | # bottleneck_channel
171 | conv1 = new_conv_layer(bn1, [1,1,input_shape[3],bottleneck_channel], stride=stride, bias=bias, name="conv1" )
172 | bn2 = tf.nn.elu(batchnorm(conv1, is_train, n_reference, name='bn2'))
173 | conv2 = new_conv_layer(bn2, [3,3,bottleneck_channel,bottleneck_channel], stride=1, bias=bias, name="conv2" )
174 | bn3 = tf.nn.elu(batchnorm(conv2, is_train, n_reference, name='bn3'))
175 | conv3 = new_conv_layer(bn3, [1,1,bottleneck_channel,output_channel], stride=1, bias=bias, name="conv3" )
176 |
177 | return shortcut+conv3
178 |
179 |
180 |
181 | def bottleneck_flexible(input, is_train, output_channel, n_reference, channel_compress_ratio=4, stride=1, bias=True, name=None):
182 |
183 | input_shape = input.get_shape().as_list()
184 |
185 | bottleneck_channel = output_channel / channel_compress_ratio
186 |
187 | with tf.variable_scope(name):
188 | bn1 = tf.nn.elu(batchnorm(input, is_train, n_reference, name='bn1'))
189 | # shortcut
190 | if stride is not 1:
191 | shortcut = new_conv_layer(bn1, [1,1,input_shape[3],output_channel], stride=stride, bias=bias, name="conv_sc" )
192 | else:
193 | shortcut = input
194 |
195 | # bottleneck_channel
196 | conv1 = new_conv_layer(bn1, [1,1,input_shape[3],bottleneck_channel], stride=stride, bias=bias, name="conv1" )
197 | bn2 = tf.nn.elu(batchnorm(conv1, is_train, n_reference, name='bn2'))
198 | conv2 = new_conv_layer(bn2, [3,3,bottleneck_channel,bottleneck_channel], stride=1, bias=bias, name="conv2" )
199 | bn3 = tf.nn.elu(batchnorm(conv2, is_train, n_reference, name='bn3'))
200 | conv3 = new_conv_layer(bn3, [1,1,bottleneck_channel,output_channel], stride=1, bias=bias, name="conv3" )
201 |
202 | return shortcut+conv3
203 |
204 |
205 |
206 | def add_bottleneck_module(input, is_train, nBlocks, n_reference, channel_compress_ratio=4, bias=True, name=None):
207 |
208 | with tf.variable_scope(name):
209 | # the first block reduce spatial dimension
210 | out = bottleneck(input, is_train, n_reference, channel_compress_ratio=channel_compress_ratio, stride=2, bias=bias, name='block0')
211 |
212 | for i in range(nBlocks-1):
213 | subname = 'block%d' % (i+1)
214 | out = bottleneck(out, is_train, n_reference, channel_compress_ratio=channel_compress_ratio, stride=1, bias=bias, name=subname)
215 | return out
216 |
217 |
--------------------------------------------------------------------------------
/projector/layers_nearest_2.py:
--------------------------------------------------------------------------------
1 | import tensorflow as tf
2 | import numpy as np
3 | from tensorflow.contrib.layers.python.layers import batch_norm as tf_batch_norm
4 | import tensorflow.contrib.slim as slim
5 |
6 | def new_fc_layer(bottom, output_size, name=None, bias=True):
7 | """
8 | fully connected layer
9 | """
10 | shape = bottom.get_shape().as_list()
11 | dim = np.prod( shape[1:] )
12 | x = tf.reshape( bottom, [-1, dim])
13 | input_size = dim
14 |
15 | with tf.variable_scope(name):
16 | w = tf.get_variable(
17 | "W",
18 | shape=[input_size, output_size],
19 | initializer=tf.truncated_normal_initializer(0., 0.005))
20 | if bias == True:
21 | b = tf.get_variable(
22 | "b",
23 | shape=[output_size],
24 | initializer=tf.constant_initializer(0.))
25 | fc = tf.nn.bias_add( tf.matmul(x, w), b)
26 | else:
27 | fc = tf.matmul(x, w)
28 |
29 | return (fc, w)
30 |
31 | def batchnorm(bottom, is_train, num_reference, epsilon=1e-3, decay=0.999, name=None):
32 | """ virtual batch normalization (poor man's version)
33 | the first half is the true batch, the second half is the reference batch.
34 | When num_reference = 0, it is just typical batch normalization.
35 | To use virtual batch normalization in test phase, "update_popmean.py" needed to be executed first
36 | (in order to store the mean and variance of the reference batch into pop_mean and pop_variance of batchnorm.)
37 | """
38 |
39 | batch_size = bottom.get_shape().as_list()[0]
40 | inst_size = batch_size - num_reference
41 | instance_weight = np.ones([batch_size])
42 |
43 | if inst_size > 0:
44 | reference_weight = 1.0 - (1.0 / ( num_reference + 1.0))
45 | instance_weight[0:inst_size] = 1.0 - reference_weight
46 | instance_weight[inst_size:] = reference_weight
47 | else:
48 | decay = 0.0
49 |
50 | return slim.batch_norm(bottom, activation_fn=None, is_training=is_train, decay=decay, scale=True, scope=name, batch_weights=instance_weight)
51 |
52 |
53 | def new_conv_layer(bottom, filter_shape, activation=tf.identity, padding='SAME', stride=1, bias=True, name=None):
54 | """
55 | In order to alleviate the checkerboard pattern in the generated images,
56 | the downsample and upsample are performed by nearest-neighbor resizing.
57 | Here, the resizing is performed before convolution. The corresponding filter size is also adjusted accordingly.
58 | """
59 |
60 | filter_shape = np.copy(filter_shape)
61 | # resize by nearest neighbor
62 | if stride > 1:
63 | bottom_shape = bottom.get_shape().as_list()
64 | bottom = tf.image.resize_nearest_neighbor(bottom, [bottom_shape[1]//stride, bottom_shape[2]//stride])
65 | filter_shape[0] = filter_shape[0] // stride
66 | filter_shape[1] = filter_shape[1] // stride
67 | if filter_shape[0] < 1:
68 | filter_shape[0] = 1
69 | if filter_shape[1] < 1:
70 | filter_shape[1] = 1
71 |
72 | new_stride = 1
73 |
74 | with tf.variable_scope(name):
75 | w = tf.get_variable(
76 | "W",
77 | shape=filter_shape,
78 | initializer=tf.truncated_normal_initializer(0., 0.005))
79 | conv = tf.nn.conv2d( bottom, w, [1,new_stride,new_stride,1], padding=padding)
80 |
81 | if bias == True:
82 | b = tf.get_variable(
83 | "b",
84 | shape=filter_shape[-1],
85 | initializer=tf.constant_initializer(0.))
86 | output = activation(tf.nn.bias_add(conv, b))
87 | else:
88 | output = activation(conv)
89 |
90 |
91 |
92 | return output
93 |
94 |
95 | def new_deconv_layer(bottom, filter_shape, output_shape, activation=tf.identity, padding='SAME', stride=1, bias=True, name=None):
96 | """
97 | In order to alleviate the checkerboard pattern in the generated images,
98 | the downsample and upsample are performed by nearest-neighbor resizing.
99 | Here, the resizing is performed before convolution.
100 | """
101 | # resize by nearest neighbor
102 | if stride > 1:
103 | bottom = tf.image.resize_nearest_neighbor(bottom, [output_shape[1], output_shape[2]])
104 |
105 | new_stride = 1
106 | new_filter_shape = np.copy(filter_shape)
107 | new_filter_shape[2] = filter_shape[3]
108 | new_filter_shape[3] = filter_shape[2]
109 |
110 | with tf.variable_scope(name):
111 | W = tf.get_variable(
112 | "W",
113 | shape=new_filter_shape,
114 | initializer=tf.truncated_normal_initializer(0., 0.005))
115 | deconv = tf.nn.conv2d(bottom, W, [1,new_stride,new_stride,1], padding=padding)
116 | #deconv = tf.nn.conv2d_transpose( bottom, W, output_shape, [1,new_stride,new_stride,1], padding=padding)
117 |
118 | if bias == True:
119 | b = tf.get_variable(
120 | "b",
121 | shape=filter_shape[-2],
122 | initializer=tf.constant_initializer(0.))
123 | output = activation(tf.nn.bias_add(deconv, b))
124 | else:
125 | output = activation(deconv)
126 |
127 | return output
128 |
129 |
130 | def channel_wise_fc_layer(bottom, name, bias=True):
131 | """
132 | channel-wise fully connected layer
133 | """
134 | _, width, height, n_feat_map = bottom.get_shape().as_list()
135 | input_reshape = tf.reshape( bottom, [-1, width*height, n_feat_map] ) # order='C'
136 | input_transpose = tf.transpose( input_reshape, [2,0,1] ) # n_feat_map * batch * d
137 |
138 | with tf.variable_scope(name):
139 | W = tf.get_variable(
140 | "W",
141 | shape=[n_feat_map,width*height, width*height], # n_feat_map * d * d_filter
142 | initializer=tf.truncated_normal_initializer(0., 0.005))
143 | output = tf.batch_matmul(input_transpose, W) # n_feat_map * batch * d_filter
144 |
145 | if bias == True:
146 | b = tf.get_variable(
147 | "b",
148 | shape=width*height,
149 | initializer=tf.constant_initializer(0.))
150 | output = tf.nn.bias_add(output, b)
151 |
152 | output_transpose = tf.transpose(output, [1,2,0]) # batch * d_filter * n_feat_map
153 | output_reshape = tf.reshape( output_transpose, [-1, width, height, n_feat_map] )
154 | return output_reshape
155 |
156 |
157 |
158 | def bottleneck(input, is_train, n_reference, channel_compress_ratio=4, stride=1, bias=True, name=None):
159 | """
160 | building block for creating residual net
161 | """
162 | input_shape = input.get_shape().as_list()
163 |
164 | if stride is not 1:
165 | output_channel = input_shape[3] * 2
166 | else:
167 | output_channel = input_shape[3]
168 |
169 | bottleneck_channel = output_channel / channel_compress_ratio
170 |
171 | with tf.variable_scope(name):
172 | bn1 = tf.nn.elu(batchnorm(input, is_train, n_reference, name='bn1'))
173 | # shortcut
174 | if stride is not 1:
175 | shortcut = new_conv_layer(bn1, [1,1,input_shape[3],output_channel], stride=stride, bias=bias, name="conv_sc" )
176 | else:
177 | shortcut = input
178 |
179 | # bottleneck_channel
180 | conv1 = new_conv_layer(bn1, [1,1,input_shape[3],bottleneck_channel], stride=stride, bias=bias, name="conv1" )
181 | bn2 = tf.nn.elu(batchnorm(conv1, is_train, n_reference, name='bn2'))
182 | conv2 = new_conv_layer(bn2, [3,3,bottleneck_channel,bottleneck_channel], stride=1, bias=bias, name="conv2" )
183 | bn3 = tf.nn.elu(batchnorm(conv2, is_train, n_reference, name='bn3'))
184 | conv3 = new_conv_layer(bn3, [1,1,bottleneck_channel,output_channel], stride=1, bias=bias, name="conv3" )
185 |
186 | return shortcut+conv3
187 |
188 |
189 |
190 | def bottleneck_flexible(input, is_train, output_channel, n_reference, channel_compress_ratio=4, stride=1, bias=True, name=None):
191 |
192 | input_shape = input.get_shape().as_list()
193 |
194 | bottleneck_channel = output_channel / channel_compress_ratio
195 |
196 | with tf.variable_scope(name):
197 | bn1 = tf.nn.elu(batchnorm(input, is_train, n_reference, name='bn1'))
198 | # shortcut
199 | if stride is not 1:
200 | shortcut = new_conv_layer(bn1, [1,1,input_shape[3],output_channel], stride=stride, bias=bias, name="conv_sc" )
201 | else:
202 | shortcut = input
203 |
204 | # bottleneck_channel
205 | conv1 = new_conv_layer(bn1, [1,1,input_shape[3],bottleneck_channel], stride=stride, bias=bias, name="conv1" )
206 | bn2 = tf.nn.elu(batchnorm(conv1, is_train, n_reference, name='bn2'))
207 | conv2 = new_conv_layer(bn2, [3,3,bottleneck_channel,bottleneck_channel], stride=1, bias=bias, name="conv2" )
208 | bn3 = tf.nn.elu(batchnorm(conv2, is_train, n_reference, name='bn3'))
209 | conv3 = new_conv_layer(bn3, [1,1,bottleneck_channel,output_channel], stride=1, bias=bias, name="conv3" )
210 |
211 | return shortcut+conv3
212 |
213 |
214 |
215 | def add_bottleneck_module(input, is_train, nBlocks, n_reference, channel_compress_ratio=4, bias=True, name=None):
216 |
217 | with tf.variable_scope(name):
218 | # the first block reduce spatial dimension
219 | out = bottleneck(input, is_train, n_reference, channel_compress_ratio=channel_compress_ratio, stride=2, bias=bias, name='block0')
220 |
221 | for i in range(nBlocks-1):
222 | subname = 'block%d' % (i+1)
223 | out = bottleneck(out, is_train, n_reference, channel_compress_ratio=channel_compress_ratio, stride=1, bias=bias, name=subname)
224 | return out
225 |
226 |
--------------------------------------------------------------------------------
/admm/paper_demo.py:
--------------------------------------------------------------------------------
1 | import sys
2 | sys.path.append("../projector")
3 | import main as model
4 | import tensorflow as tf
5 | import numpy as np
6 | import scipy as sp
7 | import scipy.io
8 | import math
9 | import load_celeb as load_data
10 | import os
11 | import timeit
12 | import matplotlib.pyplot as plt
13 | import add_noise
14 | import solver_paper as solver
15 | import solver_l1 as solver_l1
16 | from PIL import Image
17 | from PIL import ImageFont
18 | from PIL import ImageDraw
19 |
20 |
21 | def save_results(folder, infos, x, z, u):
22 | filename = '%s/infos.mat' % folder
23 | sp.io.savemat(filename, infos)
24 | filename = '%s/x.jpg' % folder
25 | sp.misc.imsave(filename, sp.misc.imresize((reshape_img(np.clip(x, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
26 | filename = '%s/z.jpg' % folder
27 | sp.misc.imsave(filename, sp.misc.imresize((reshape_img(np.clip(z, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
28 | filename = '%s/u.jpg' % folder
29 | sp.misc.imsave(filename, sp.misc.imresize((reshape_img(np.clip(u, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
30 |
31 |
32 | # index of test images
33 | idxs = np.random.randint(391854, size=1)
34 |
35 | # result folder
36 | clean_paper_results = 'clean_paper_results'
37 |
38 | # filename of the trained model. If using virtual batch normalization,
39 | # the popmean and popvariance need to be updated first via update_popmean.py!
40 | iter = 49999
41 | pretrained_folder = os.path.expanduser("../projector/model/imsize64_ratio0.010000_dis0.005000_latent0.000100_img0.001000_de1.000000_derate1.000000_dp1_gd1_softpos0.850000_wdcy_0.000000_seed0")
42 | pretrained_model_file = '%s/update/model_iter-%d' % (pretrained_folder, iter)
43 |
44 |
45 | for idx in idxs :
46 | print 'idx = %d --------' % idx
47 |
48 | np.random.seed(idx)
49 |
50 | img_size = (64,64,3)
51 |
52 | show_img_progress = False # whether the plot intermediate results (may slow down the process)
53 | run_ours = True # whether the run the proposed method
54 | run_l1 = False # whether the run the traditional wavelet sparsity method
55 |
56 | def load_image(filepath):
57 | img = sp.misc.imread(filepath)
58 | img = sp.misc.imresize(img, [64,64]).astype(float) / 255.0
59 | if len(img.shape) < 3:
60 | img = np.tile(img, [1,1,3])
61 | return img
62 |
63 |
64 | #def load_image(filepath):
65 | #img = sp.misc.imread(filepath)
66 | ## In our original code used to generate the results in the paper, we mistakenly
67 | ## resize the image directly to the input dimension via
68 | ## img = sp.misc.imresize(img, [img_size[0], img_size[1]]).astype(float) / 255.0
69 | ## The following is the corrected version
70 | #img_shape = img.shape
71 | #min_edge = min(img_shape[0], img_shape[1])
72 | #min_resize_ratio = float(img_size[0]) / float(min_edge)
73 | #max_resize_ratio = min_resize_ratio * 2.0
74 | #resize_ratio = np.random.rand() * (max_resize_ratio - min_resize_ratio) + min_resize_ratio
75 |
76 | #img = sp.misc.imresize(img, resize_ratio).astype(float) / 255.0
77 | #crop_loc_row = np.random.randint(img.shape[0]-img_size[0]+1)
78 | #crop_loc_col = np.random.randint(img.shape[1]-img_size[1]+1)
79 | #if len(img.shape) == 3:
80 | #img = img[crop_loc_row:crop_loc_row+img_size[0], crop_loc_col:crop_loc_col+img_size[1],:]
81 | #else:
82 | #img = img[crop_loc_row:crop_loc_row+img_size[0], crop_loc_col:crop_loc_col+img_size[1]]
83 | #if len(img.shape) < 3:
84 | #img = np.tile(img, [1,1,3])
85 | #return img
86 |
87 | def solve_denoising_dropping(ori_img, denoiser, reshape_img_fun, drop_prob=0.3,
88 | noise_mean=0, noise_std=0.1,
89 | alpha=0.3, lambda_l1=0.1, max_iter=100, solver_tol=1e-2):
90 | import inpaint as problem
91 | x_shape = ori_img.shape
92 | (A_fun, AT_fun, mask) = problem.setup(x_shape, drop_prob=drop_prob)
93 | y, noise = add_noise.exe(A_fun(ori_img), noise_mean=noise_mean, noise_std=noise_std)
94 |
95 | if show_img_progress:
96 | fig = plt.figure('denoise')
97 | plt.gcf().clear()
98 | fig.canvas.set_window_title('denoise')
99 | plt.subplot(1,2,1)
100 | plt.imshow(reshape_img_fun(ori_img), interpolation='nearest')
101 | plt.title('ori_img')
102 | plt.subplot(1,2,2)
103 | plt.imshow(reshape_img_fun(y), interpolation='nearest')
104 | plt.title('y')
105 | plt.pause(0.00001)
106 |
107 | info = {'ori_img': ori_img, 'y': y, 'noise': noise, 'mask': mask, 'drop_prob': drop_prob, 'noise_std': noise_std,
108 | 'alpha': alpha, 'max_iter': max_iter, 'solver_tol': solver_tol, 'lambda_l1': lambda_l1}
109 |
110 | # save the problem
111 | base_folder = '%s/denoise_ratio%.2f_std%.2f' % (result_folder, drop_prob, noise_std)
112 | if not os.path.exists(base_folder):
113 | os.makedirs(base_folder)
114 | filename = '%s/settings.mat' % base_folder
115 | sp.io.savemat(filename, info)
116 | filename = '%s/y.jpg' % base_folder
117 | sp.misc.imsave(filename, sp.misc.imresize((reshape_img(np.clip(y, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
118 | filename = '%s/ori_img.jpg' % base_folder
119 | sp.misc.imsave(filename, sp.misc.imresize((reshape_img(np.clip(ori_img, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
120 |
121 | if run_ours:
122 | # ours
123 | folder = '%s/ours_alpha%f' % (base_folder, alpha)
124 | if not os.path.exists(folder):
125 | os.makedirs(folder)
126 | (x, z, u, infos) = solver.solve(y, A_fun, AT_fun, denoiser, reshape_img_fun, folder,
127 | show_img_progress=show_img_progress, alpha=alpha,
128 | max_iter=max_iter, solver_tol=solver_tol)
129 | save_results(folder, infos, x, z, u)
130 |
131 | if run_l1:
132 | # wavelet l1
133 | folder = '%s/l1_lambdal1%f_alpha%f' % (base_folder, lambda_l1, alpha_l1)
134 | if not os.path.exists(folder):
135 | os.makedirs(folder)
136 | (x, z, u, infos) = solver_l1.solve(y, A_fun, AT_fun, lambda_l1, reshape_img_fun, folder,
137 | show_img_progress=show_img_progress, alpha=alpha_l1,
138 | max_iter=max_iter_l1, solver_tol=solver_tol_l1)
139 | save_results(folder, infos, x, z, u)
140 |
141 | z1 = reshape_img(np.clip(z, 0.0, 1.0))
142 | ori_img1 = reshape_img(np.clip(ori_img, 0.0, 1.0))
143 | psnr = 10*np.log10( 1.0 /np.linalg.norm(z1-ori_img1)**2*np.prod(z1.shape))
144 | img = Image.fromarray( sp.misc.imresize(np.uint8(z1*255), 4.0, interp='nearest' ) )
145 | draw = ImageDraw.Draw(img)
146 | #font = ImageFont.truetype(font='tnr.ttf', size=50)
147 | #draw.text((135, 200), "%.2f"%psnr, (255,255,255), font=font)
148 | filename = '%s/z.jpg' % folder
149 | img.save(filename)
150 |
151 | def solve_inpaint_center(ori_img, denoiser, reshape_img_fun, box_size=1,
152 | noise_mean=0, noise_std=0.,
153 | alpha=0.3, lambda_l1=0.1, max_iter=100, solver_tol=1e-2):
154 | import inpaint_center as problem
155 | x_shape = ori_img.shape
156 | (A_fun, AT_fun, mask) = problem.setup(x_shape, box_size=box_size)
157 | y, noise = add_noise.exe(A_fun(ori_img), noise_mean=noise_mean, noise_std=noise_std)
158 |
159 | if show_img_progress:
160 | fig = plt.figure('inpaint_center')
161 | plt.gcf().clear()
162 | fig.canvas.set_window_title('inpaint_center')
163 | plt.subplot(1,2,1)
164 | plt.imshow(reshape_img_fun(ori_img), interpolation='nearest')
165 | plt.title('ori_img')
166 | plt.subplot(1,2,2)
167 | plt.imshow(reshape_img_fun(y), interpolation='nearest')
168 | plt.title('y')
169 | plt.pause(0.00001)
170 |
171 | info = {'ori_img': ori_img, 'y': y, 'noise': noise, 'mask': mask, 'box_size': box_size, 'noise_std': noise_std,
172 | 'alpha': alpha, 'max_iter': max_iter, 'solver_tol': solver_tol, 'lambda_l1': lambda_l1}
173 |
174 | # save the problem
175 | base_folder = '%s/inpaintcenter_bs%d_std%.2f' % (result_folder, box_size, noise_std)
176 | if not os.path.exists(base_folder):
177 | os.makedirs(base_folder)
178 | filename = '%s/settings.mat' % base_folder
179 | sp.io.savemat(filename, info)
180 | filename = '%s/y.jpg' % base_folder
181 | sp.misc.imsave(filename, sp.misc.imresize((reshape_img(np.clip(y, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
182 | filename = '%s/ori_img.jpg' % base_folder
183 | sp.misc.imsave(filename, sp.misc.imresize((reshape_img(np.clip(ori_img, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
184 |
185 | if run_ours:
186 | # ours
187 | folder = '%s/ours_alpha%f' % (base_folder, alpha)
188 | if not os.path.exists(folder):
189 | os.makedirs(folder)
190 | (x, z, u, infos) = solver.solve(y, A_fun, AT_fun, denoiser, reshape_img_fun, folder,
191 | show_img_progress=show_img_progress, alpha=alpha,
192 | max_iter=max_iter, solver_tol=solver_tol)
193 | save_results(folder, infos, x, z, u)
194 |
195 | if run_l1:
196 | # wavelet l1
197 | folder = '%s/l1_lambdal1%f_alpha%f' % (base_folder, lambda_l1, alpha_l1)
198 | if not os.path.exists(folder):
199 | os.makedirs(folder)
200 | (x, z, u, infos) = solver_l1.solve(y, A_fun, AT_fun, lambda_l1, reshape_img_fun, folder,
201 | show_img_progress=show_img_progress, alpha=alpha_l1,
202 | max_iter=max_iter_l1, solver_tol=solver_tol_l1)
203 | save_results(folder, infos, x, z, u)
204 |
205 | z1 = reshape_img(np.clip(z, 0.0, 1.0))
206 | ori_img1 = reshape_img(np.clip(ori_img, 0.0, 1.0))
207 | psnr = 10*np.log10( 1.0 /np.linalg.norm(z1-ori_img1)**2*np.prod(z1.shape))
208 | img = Image.fromarray( sp.misc.imresize(np.uint8(z1*255), 4.0, interp='nearest' ) )
209 | draw = ImageDraw.Draw(img)
210 | #font = ImageFont.truetype(font='tnr.ttf', size=50)
211 | #draw.text((135, 200), "%.2f"%psnr, (255,255,255), font=font)
212 | filename = '%s/z.jpg' % folder
213 | img.save(filename)
214 |
215 | def solve_inpaint_block(ori_img, denoiser, reshape_img_fun, box_size=1, total_box=1,
216 | noise_mean=0, noise_std=0.,
217 | alpha=0.3, lambda_l1=0.1, max_iter=100, solver_tol=1e-2):
218 | import inpaint_block as problem
219 | x_shape = ori_img.shape
220 | (A_fun, AT_fun, mask) = problem.setup(x_shape, box_size=box_size, total_box=total_box)
221 | y, noise = add_noise.exe(A_fun(ori_img), noise_mean=noise_mean, noise_std=noise_std)
222 |
223 | if show_img_progress:
224 | fig = plt.figure('inpaint')
225 | plt.gcf().clear()
226 | fig.canvas.set_window_title('inpaint')
227 | plt.subplot(1,2,1)
228 | plt.imshow(reshape_img_fun(ori_img), interpolation='nearest')
229 | plt.title('ori_img')
230 | plt.subplot(1,2,2)
231 | plt.imshow(reshape_img_fun(y), interpolation='nearest')
232 | plt.title('y')
233 | plt.pause(0.00001)
234 |
235 |
236 | info = {'ori_img': ori_img, 'y': y, 'noise': noise, 'mask': mask, 'box_size': box_size,
237 | 'total_box': total_box, 'noise_std': noise_std,
238 | 'alpha': alpha, 'max_iter': max_iter, 'solver_tol': solver_tol, 'lambda_l1': lambda_l1}
239 |
240 |
241 | # save the problem
242 | base_folder = '%s/inpaint_bs%d_tb%d_std%.2f' % (result_folder, box_size, total_box, noise_std)
243 | if not os.path.exists(base_folder):
244 | os.makedirs(base_folder)
245 | filename = '%s/settings.mat' % base_folder
246 | sp.io.savemat(filename, info)
247 | filename = '%s/y.jpg' % base_folder
248 | sp.misc.imsave(filename, sp.misc.imresize((reshape_img(np.clip(y, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
249 | filename = '%s/ori_img.jpg' % base_folder
250 | sp.misc.imsave(filename, sp.misc.imresize((reshape_img(np.clip(ori_img, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
251 |
252 |
253 | if run_ours:
254 | # ours
255 | folder = '%s/ours_alpha%f' % (base_folder, alpha)
256 | if not os.path.exists(folder):
257 | os.makedirs(folder)
258 | (x, z, u, infos) = solver.solve(y, A_fun, AT_fun, denoiser, reshape_img_fun, folder,
259 | show_img_progress=show_img_progress, alpha=alpha,
260 | max_iter=max_iter, solver_tol=solver_tol)
261 | save_results(folder, infos, x, z, u)
262 |
263 | if run_l1:
264 | # wavelet l1
265 | folder = '%s/l1_lambdal1%f_alpha%f' % (base_folder, lambda_l1, alpha_l1)
266 | if not os.path.exists(folder):
267 | os.makedirs(folder)
268 | (x, z, u, infos) = solver_l1.solve(y, A_fun, AT_fun, lambda_l1, reshape_img_fun, folder,
269 | show_img_progress=show_img_progress, alpha=alpha_l1,
270 | max_iter=max_iter_l1, solver_tol=solver_tol_l1)
271 | save_results(folder, infos, x, z, u)
272 |
273 | z1 = reshape_img(np.clip(z, 0.0, 1.0))
274 | ori_img1 = reshape_img(np.clip(ori_img, 0.0, 1.0))
275 | psnr = 10*np.log10( 1.0 /np.linalg.norm(z1-ori_img1)**2*np.prod(z1.shape))
276 | img = Image.fromarray( sp.misc.imresize(np.uint8(z1*255), 4.0, interp='nearest' ) )
277 | draw = ImageDraw.Draw(img)
278 | #font = ImageFont.truetype(font='tnr.ttf', size=50)
279 | #draw.text((135, 200), "%.2f"%psnr, (255,255,255), font=font)
280 | filename = '%s/z.jpg' % folder
281 | img.save(filename)
282 |
283 |
284 | def solve_superres(ori_img, denoiser, reshape_img_fun, resize_ratio=0.5,
285 | noise_mean=0, noise_std=0.,
286 | alpha=0.3, lambda_l1=0.1, max_iter=100, solver_tol=1e-2):
287 | import superres as problem
288 | x_shape = ori_img.shape
289 | (A_fun, AT_fun) = problem.setup(x_shape, resize_ratio=resize_ratio)
290 | y, noise = add_noise.exe(A_fun(ori_img), noise_mean=noise_mean, noise_std=noise_std)
291 |
292 | bicubic_img = sp.misc.imresize(y[0], [ori_img.shape[1], ori_img.shape[2]], interp='bicubic')
293 | if show_img_progress:
294 | fig = plt.figure('superres')
295 | plt.gcf().clear()
296 | fig.canvas.set_window_title('superres')
297 | plt.subplot(1,3,1)
298 | plt.imshow(reshape_img_fun(ori_img), interpolation='nearest')
299 | plt.title('ori_img')
300 | plt.subplot(1,3,2)
301 | plt.imshow(reshape_img_fun(y), interpolation='nearest')
302 | plt.title('y')
303 | plt.subplot(1,3,3)
304 | plt.imshow(np.clip(bicubic_img,0,255), interpolation='nearest')
305 | plt.title('bicubic')
306 | plt.pause(0.00001)
307 |
308 | bicubic_img = bicubic_img.astype(float) / 255.0
309 | l2_dis = np.mean(np.square(ori_img[0] - bicubic_img))
310 |
311 | print 'bicubic err = %f' % (l2_dis)
312 |
313 |
314 | info = {'ori_img': ori_img, 'y': y, 'bicubic': bicubic_img, 'noise': noise, 'resize_ratio': resize_ratio,
315 | 'noise_std': noise_std,
316 | 'alpha': alpha, 'max_iter': max_iter, 'solver_tol': solver_tol, 'lambda_l1': lambda_l1}
317 |
318 | # save the problem
319 | base_folder = '%s/superres_ratio%.2f_std%.2f' % (result_folder, resize_ratio, noise_std)
320 | if not os.path.exists(base_folder):
321 | os.makedirs(base_folder)
322 | filename = '%s/settings.mat' % base_folder
323 | sp.io.savemat(filename, info)
324 | filename = '%s/y.jpg' % base_folder
325 | sp.misc.imsave(filename, sp.misc.imresize((reshape_img(np.clip(y, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
326 | filename = '%s/ori_img.jpg' % base_folder
327 | sp.misc.imsave(filename, sp.misc.imresize((reshape_img(np.clip(ori_img, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
328 | filename = '%s/bicubic_img.jpg' % base_folder
329 | sp.misc.imsave(filename, sp.misc.imresize((bicubic_img*255).astype(np.uint8), 4.0, interp='nearest'))
330 |
331 | if run_ours:
332 | # ours
333 | folder = '%s/ours_alpha%f' % (base_folder, alpha)
334 | if not os.path.exists(folder):
335 | os.makedirs(folder)
336 | (x, z, u, infos) = solver.solve(y, A_fun, AT_fun, denoiser, reshape_img_fun, folder,
337 | show_img_progress=show_img_progress, alpha=alpha,
338 | max_iter=max_iter, solver_tol=solver_tol)
339 | save_results(folder, infos, x, z, u)
340 |
341 | if run_l1:
342 | # wavelet l1
343 | folder = '%s/l1_lambdal1%f_alpha%f' % (base_folder, lambda_l1, alpha_l1)
344 | if not os.path.exists(folder):
345 | os.makedirs(folder)
346 | (x, z, u, infos) = solver_l1.solve(y, A_fun, AT_fun, lambda_l1, reshape_img_fun, folder,
347 | show_img_progress=show_img_progress, alpha=alpha_l1,
348 | max_iter=max_iter_l1, solver_tol=solver_tol_l1)
349 | save_results(folder, infos, x, z, u)
350 |
351 | z1 = reshape_img(np.clip(z, 0.0, 1.0))
352 | ori_img1 = reshape_img(np.clip(ori_img, 0.0, 1.0))
353 | psnr = 10*np.log10( 1.0 /np.linalg.norm(z1-ori_img1)**2*np.prod(z1.shape))
354 | img = Image.fromarray( sp.misc.imresize(np.uint8(z1*255), 4.0, interp='nearest' ) )
355 | draw = ImageDraw.Draw(img)
356 | #font = ImageFont.truetype(font='tnr.ttf', size=50)
357 | #draw.text((135, 200), "%.2f"%psnr, (255,255,255), font=font)
358 | filename = '%s/z.jpg' % folder
359 | img.save(filename)
360 |
361 | def solve_cs(ori_img, denoiser, reshape_img_fun, compress_ratio,
362 | noise_mean=0, noise_std=0.,
363 | alpha=0.3, lambda_l1=0.1, max_iter=100, solver_tol=1e-2):
364 | import cs as problem
365 | x_shape = ori_img.shape
366 | (A_fun, AT_fun, A) = problem.setup(x_shape, compress_ratio)
367 | y, noise = add_noise.exe(A_fun(ori_img), noise_mean=noise_mean, noise_std=noise_std)
368 |
369 | info = {'ori_img': ori_img, 'y': y, 'noise': noise, 'compress_ratio': compress_ratio,
370 | 'noise_std': noise_std,
371 | 'alpha': alpha, 'max_iter': max_iter, 'solver_tol': solver_tol, 'lambda_l1': lambda_l1}
372 |
373 | # save the problem
374 | base_folder = '%s/cs_ratio%.2f_std%.2f' % (result_folder, compress_ratio, noise_std)
375 | if not os.path.exists(base_folder):
376 | os.makedirs(base_folder)
377 | filename = '%s/settings.mat' % base_folder
378 | sp.io.savemat(filename, info)
379 | filename = '%s/ori_img.jpg' % base_folder
380 | sp.misc.imsave(filename, sp.misc.imresize((reshape_img(np.clip(ori_img, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
381 |
382 |
383 | if run_ours:
384 | # ours
385 | folder = '%s/ours_alpha%f' % (base_folder, alpha)
386 | if not os.path.exists(folder):
387 | os.makedirs(folder)
388 | (x, z, u, infos) = solver.solve(y, A_fun, AT_fun, denoiser, reshape_img_fun, folder,
389 | show_img_progress=show_img_progress, alpha=alpha,
390 | max_iter=max_iter, solver_tol=solver_tol)
391 | save_results(folder, infos, x, z, u)
392 |
393 | if run_l1:
394 | # wavelet l1
395 | folder = '%s/l1_lambdal1%f_alpha%f' % (base_folder, lambda_l1, alpha_l1)
396 | if not os.path.exists(folder):
397 | os.makedirs(folder)
398 | (x, z, u, infos) = solver_l1.solve(y, A_fun, AT_fun, lambda_l1, reshape_img_fun, folder,
399 | show_img_progress=show_img_progress, alpha=alpha_l1,
400 | max_iter=max_iter_l1, solver_tol=solver_tol_l1)
401 | save_results(folder, infos, x, z, u)
402 |
403 | z1 = reshape_img(np.clip(z, 0.0, 1.0))
404 | ori_img1 = reshape_img(np.clip(ori_img, 0.0, 1.0))
405 | psnr = 10*np.log10( 1.0 /np.linalg.norm(z1-ori_img1)**2*np.prod(z1.shape))
406 | img = Image.fromarray( sp.misc.imresize(np.uint8(z1*255), 4.0, interp='nearest' ) )
407 | draw = ImageDraw.Draw(img)
408 | #font = ImageFont.truetype(font='tnr.ttf', size=50)
409 | #draw.text((135, 200), "%.2f"%psnr, (255,255,255), font=font)
410 | filename = '%s/z.jpg' % folder
411 | img.save(filename)
412 |
413 | def reshape_img(img):
414 | return img[0]
415 |
416 |
417 | if run_ours:
418 | # setup the variables in the session
419 | n_reference = 0
420 | batch_size = n_reference + 1
421 | images_tf = tf.placeholder( tf.float32, [batch_size, img_size[0], img_size[1], img_size[2]], name="images")
422 | is_train = False
423 | proj, latent = model.build_projection_model(images_tf, is_train, n_reference, use_bias=True, reuse=None)
424 |
425 | with tf.variable_scope("PROJ") as scope:
426 | scope.reuse_variables()
427 |
428 | # load the dataset
429 |
430 |
431 | print 'loading data...'
432 | testset_filelist = load_data.load_testset_path_list()
433 | total_test = len(testset_filelist)
434 | print 'total test = %d' % total_test
435 |
436 | # We create a session to use the graph and restore the variables
437 | if run_ours:
438 | print 'loading model...'
439 | sess = tf.Session()
440 | sess.run(tf.global_variables_initializer())
441 | saver = tf.train.Saver(max_to_keep=100)
442 | saver.restore(sess, pretrained_model_file)
443 | #print(sess.run(tf.global_variables()))
444 | print 'finished reload.'
445 |
446 | # define denoiser
447 | def denoise(x):
448 | x_shape = x.shape
449 | x = np.reshape(x, [1, img_size[0], img_size[1], img_size[2]], order='F')
450 | x = (x - 0.5) * 2.0
451 |
452 | y = sess.run(proj, feed_dict={images_tf: x})
453 | y = (y / 2.0) + 0.5
454 | return np.reshape(y, x_shape)
455 |
456 |
457 | def denoise_batch(x):
458 | x_shape = x.shape
459 |
460 | ys = np.zeros(x_shape)
461 | for i in range(x_shape[0]):
462 | ys[i] = denoise(x[i])
463 |
464 | return ys
465 |
466 | img =load_image(testset_filelist[idx])
467 |
468 | ori_img = np.reshape(img, [1, img_size[0],img_size[1],img_size[2]], order='F')
469 |
470 | result_folder = '%s/%d' % (clean_paper_results,idx)
471 | if not os.path.exists(result_folder):
472 | os.makedirs(result_folder)
473 |
474 | if run_ours:
475 | direct_img = denoise(ori_img)
476 | if show_img_progress:
477 | plt.figure('original')
478 | img_plot = plt.imshow(reshape_img(ori_img))
479 | plt.pause(0.001)
480 |
481 | plt.figure('direct')
482 | img_plot = plt.imshow((reshape_img(np.clip(denoise(direct_img),0.0,1.0))*255).astype(np.uint8))
483 | plt.pause(0.001)
484 |
485 |
486 | filename = '%s/ori_img.jpg' % result_folder
487 | sp.misc.imsave(filename, sp.misc.imresize((reshape_img(np.clip(ori_img, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
488 |
489 | if run_ours:
490 | filename = '%s/direct_img.jpg' % result_folder
491 | sp.misc.imsave(filename, sp.misc.imresize((reshape_img(np.clip(direct_img, 0.0, 1.0))*255).astype(np.uint8), 4.0, interp='nearest'))
492 |
493 |
494 | ##############################################################################################
495 | ##### super resolution
496 | print 'super resolution'
497 |
498 | #set parameters
499 | alpha = 0.5 # 1.0
500 | max_iter = 30
501 | solver_tol = 2e-3
502 |
503 | alpha_l1 = 0.3
504 | lambda_l1 = 0.05
505 | max_iter_l1 = 1000
506 | solver_tol_l1 = 1e-4
507 |
508 | resize_ratio = 0.5
509 | noise_std = 0.0
510 | results = solve_superres(ori_img, denoise, reshape_img, resize_ratio=resize_ratio,
511 | noise_std=noise_std,
512 | alpha=alpha, lambda_l1=lambda_l1, max_iter=max_iter, solver_tol=solver_tol)
513 |
514 | #################################################################################################
515 | ##### compressive sensing
516 | print 'compressive sensing'
517 |
518 | #set parameters
519 | alpha = 0.3
520 | max_iter = 300
521 | solver_tol = 3e-3
522 |
523 | alpha_l1 = 0.3
524 | lambda_l1 = 0.05
525 | max_iter_l1 = 1000
526 | solver_tol_l1 = 1e-4
527 |
528 | compress_ratio = 0.1
529 | noise_std = 0.0
530 | results = solve_cs(ori_img, denoise, reshape_img, compress_ratio=compress_ratio,
531 | noise_std=noise_std,
532 | alpha=alpha, lambda_l1=lambda_l1, max_iter=max_iter, solver_tol=solver_tol)
533 |
534 | ############################################################################################
535 | #### denoising
536 |
537 | print 'denoising'
538 |
539 | # set parameter
540 | alpha = 0.3
541 | max_iter = 300
542 | solver_tol = 3e-3
543 |
544 | alpha_l1 = 0.3
545 | lambda_l1 = 0.05
546 | max_iter_l1 = 1000
547 | solver_tol_l1 = 1e-4
548 |
549 | drop_prob = 0.5
550 | noise_std = 0.1
551 |
552 | results = solve_denoising_dropping(ori_img, denoise, reshape_img, drop_prob=drop_prob,
553 | noise_mean=0, noise_std=noise_std,
554 | alpha=alpha, lambda_l1=lambda_l1, max_iter=max_iter, solver_tol=solver_tol)
555 |
556 | ##########################################################################################
557 | ## inpaint block
558 |
559 | print 'inpaint block'
560 |
561 | # set parameter
562 | alpha = 0.3
563 | max_iter = 300
564 | solver_tol = 1e-4
565 |
566 | alpha_l1 = 0.3
567 | lambda_l1 = 0.03
568 | max_iter_l1 = 1000
569 | solver_tol_l1 = 1e-4
570 |
571 | box_size = int(0.1 * ori_img.shape[1])
572 | noise_std = 0.0
573 | total_box = 10
574 | results = solve_inpaint_block(ori_img, denoise, reshape_img, box_size=box_size, total_box=total_box,
575 | noise_std=noise_std,
576 | alpha=alpha, lambda_l1=lambda_l1, max_iter=max_iter, solver_tol=solver_tol)
577 |
578 | ############################################################################################
579 | ### inpaint center
580 | print 'inpaint center'
581 |
582 | alpha = 0.2
583 | max_iter = 300
584 | solver_tol = 1e-5
585 | alpha_update_ratio = 1.0
586 |
587 | alpha_l1 = 0.3
588 | lambda_l1 = 0.05
589 | max_iter_l1 = 1000
590 | solver_tol_l1 = 1e-4
591 |
592 | box_size = int(0.3 * ori_img.shape[1])
593 | noise_std = 0.0
594 | results = solve_inpaint_center(ori_img, denoise, reshape_img, box_size=box_size,
595 | noise_std=noise_std,
596 | alpha=alpha, lambda_l1=lambda_l1, max_iter=max_iter, solver_tol=solver_tol)
597 |
598 | if run_ours:
599 | tf.reset_default_graph()
600 |
601 | raw_input("Press Enter to end...")
602 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/projector/main.py:
--------------------------------------------------------------------------------
1 | import tensorflow as tf
2 | import numpy as np
3 | import scipy as sp
4 | import scipy.io
5 | import scipy.misc
6 | import scipy.ndimage
7 | import layers_nearest_2 as layers
8 | import load_celeb as load_dataset
9 | import os
10 | import os.path
11 | import timeit
12 | from multiprocessing import Process, Queue
13 | import argparse
14 | from smooth_stream import SmoothStream
15 | from noise import add_noise
16 | import sys
17 |
18 |
19 | def build_classifier_model_imagespace(image, is_train, n_reference, reuse=None):
20 | """
21 | Build the graph for the classifier in the image space
22 | """
23 |
24 | channel_compress_ratio = 4
25 |
26 | with tf.variable_scope('DIS', reuse=reuse):
27 |
28 | with tf.variable_scope('IMG'):
29 | ## image space D
30 | # 1
31 | conv1 = layers.new_conv_layer(image, [4,4,3,64], stride=1, name="conv1" ) #64
32 |
33 | # 2
34 | nBlocks = 3
35 | module2 = layers.add_bottleneck_module(conv1, is_train, nBlocks, n_reference, channel_compress_ratio=channel_compress_ratio, name='module2') # 32
36 |
37 | # 3
38 | nBlocks = 4
39 | module3 = layers.add_bottleneck_module(module2, is_train, nBlocks, n_reference, channel_compress_ratio=channel_compress_ratio, name='module3') # 16
40 |
41 | # 4
42 | nBlocks = 6
43 | module4 = layers.add_bottleneck_module(module3, is_train, nBlocks, n_reference, channel_compress_ratio=channel_compress_ratio, name='module4') # 8
44 |
45 | # 5
46 | nBlocks = 3
47 | module5 = layers.add_bottleneck_module(module4, is_train, nBlocks, n_reference, channel_compress_ratio=channel_compress_ratio, name='module5') # 4
48 | bn_module5 = tf.nn.elu(layers.batchnorm(module5, is_train, n_reference, name='bn_module5'))
49 |
50 | (dis, last_w) = layers.new_fc_layer(bn_module5, output_size=1, name='dis')
51 |
52 | return dis[:,0], last_w
53 |
54 |
55 |
56 | def build_classifier_model_latentspace(latent, is_train, n_reference, reuse=None):
57 | """
58 | Build the graph for the classifier in the latent space
59 | """
60 |
61 | channel_compress_ratio = 4
62 |
63 | with tf.variable_scope('DIS', reuse=reuse):
64 |
65 | with tf.variable_scope('LATENT'):
66 |
67 | out = layers.bottleneck(latent, is_train, n_reference, channel_compress_ratio=channel_compress_ratio, stride=1, name='block0') # 8*8*4096
68 | out = layers.bottleneck(out, is_train, n_reference, channel_compress_ratio=channel_compress_ratio, stride=1, name='block1') # 8*8*4096
69 | out = layers.bottleneck(out, is_train, n_reference, channel_compress_ratio=channel_compress_ratio, stride=1, name='block2') # 8*8*4096
70 |
71 | output_channel = out.get_shape().as_list()[-1]
72 | out = layers.bottleneck_flexible(out, is_train, output_channel, n_reference, channel_compress_ratio=4, stride=2, name='block3') # 4*4*4096
73 | out = layers.bottleneck(out, is_train, n_reference, channel_compress_ratio=4, stride=1, name='block4') # 4*4*4096
74 | out = layers.bottleneck(out, is_train, n_reference, channel_compress_ratio=4, stride=1, name='block5') # 4*4*4096
75 |
76 | bn1 = tf.nn.elu(layers.batchnorm(out, is_train, n_reference, name='bn1'))
77 | (dis, last_w) = layers.new_fc_layer(bn1, output_size=1, name='dis')
78 |
79 | return dis[:,0], last_w
80 |
81 |
82 | def build_projection_model(images, is_train, n_reference, use_bias=True, reuse=None):
83 | """
84 | Build the graph for the projection network, which shares the architecture of a typical autoencoder.
85 | To improve contextual awareness, we add a channel-wise fully-connected layer followed by a 2-by-2
86 | convolution layer at the middle.
87 | """
88 | channel_compress_ratio = 4
89 | dim_latent = 1024
90 |
91 | with tf.variable_scope('PROJ', reuse=reuse):
92 |
93 | with tf.variable_scope('ENCODE'):
94 | conv0 = layers.new_conv_layer(images, [4,4,3,64], stride=1, bias=use_bias, name="conv0" ) #64
95 | bn0 = tf.nn.elu(layers.batchnorm(conv0, is_train, n_reference, name='bn0'))
96 | conv1 = layers.new_conv_layer(bn0, [4,4,64,128], stride=1, bias=use_bias, name="conv1" ) #64
97 | bn1 = tf.nn.elu(layers.batchnorm(conv1, is_train, n_reference, name='bn1'))
98 | conv2 = layers.new_conv_layer(bn1, [4,4,128,256], stride=2, bias=use_bias, name="conv2") #32
99 | bn2 = tf.nn.elu(layers.batchnorm(conv2, is_train, n_reference, name='bn2'))
100 | conv3 = layers.new_conv_layer(bn2, [4,4,256,512], stride=2, bias=use_bias, name="conv3") #16
101 | bn3 = tf.nn.elu(layers.batchnorm(conv3, is_train, n_reference, name='bn3'))
102 | conv4 = layers.new_conv_layer(bn3, [4,4,512,dim_latent], stride=2, bias=use_bias, name="conv4") #8
103 | bn4 = tf.nn.elu(layers.batchnorm(conv4, is_train, n_reference, name='bn4'))
104 | fc5 = layers.channel_wise_fc_layer(bn4, 'fc5', bias=False)
105 | fc5_conv = layers.new_conv_layer(fc5, [2,2,dim_latent, dim_latent], stride=1, bias=use_bias, name="conv_fc")
106 | latent = tf.nn.elu(layers.batchnorm(fc5_conv, is_train, n_reference, name='latent'))
107 |
108 |
109 | deconv3 = layers.new_deconv_layer( latent, [4,4,512,dim_latent], conv3.get_shape().as_list(), stride=2, bias=use_bias, name="deconv3")
110 | debn3 = tf.nn.elu(layers.batchnorm(deconv3, is_train, n_reference, name='debn3'))
111 | deconv2 = layers.new_deconv_layer( debn3, [4,4,256,512], conv2.get_shape().as_list(), stride=2, bias=use_bias, name="deconv2")
112 | debn2 = tf.nn.elu(layers.batchnorm(deconv2, is_train, n_reference, name='debn2'))
113 | deconv1 = layers.new_deconv_layer( debn2, [4,4,128,256], conv1.get_shape().as_list(), stride=2, bias=use_bias, name="deconv1")
114 | debn1 = tf.nn.elu(layers.batchnorm(deconv1, is_train, n_reference, name='debn1'))
115 | deconv0 = layers.new_deconv_layer( debn1, [4,4,64,128], conv0.get_shape().as_list(), stride=1, bias=use_bias, name="deconv0")
116 | debn0 = tf.nn.elu(layers.batchnorm(deconv0, is_train, n_reference, name='debn0'))
117 | proj_ori = layers.new_deconv_layer( debn0, [4,4,3,64], images.get_shape().as_list(), stride=1, bias=use_bias, name="recon")
118 | proj = proj_ori
119 |
120 | return proj, latent
121 |
122 |
123 |
124 | if __name__ == '__main__':
125 |
126 | ### parse arguments
127 | parser = argparse.ArgumentParser()
128 | parser.add_argument('--base_folder', default=None, help='Where to store samples and models')
129 | parser.add_argument('--batch_size', type=int, default=64, help='input batch size')
130 | parser.add_argument('--img_size', type=int, default=64, help='the height / width of the input image to network')
131 | parser.add_argument('--n_reference', type=int, default=32, help='the size of reference batch')
132 | parser.add_argument('--Dperiod', type=int, default=1, help='number of continuous D update')
133 | parser.add_argument('--Gperiod', type=int, default=1, help='number of continuous G update')
134 |
135 | parser.add_argument('--n_epochs', type=int, default=100, help='number of epochs to train for')
136 | parser.add_argument('--pretrained_iter', type=int, default=0, help='iter of the pretrained model, if 0 then not using')
137 | parser.add_argument('--random_seed', type=int, default=0, help='random seed')
138 |
139 | parser.add_argument('--learning_rate_val_proj', type=float, default=0.002, help='learning rate, default=0.002')
140 | parser.add_argument('--learning_rate_val_dis', type=float, default=0.0002, help='learning rate, default=0.0002')
141 | parser.add_argument('--weight_decay_rate', type=float, default=0.00001, help='weight decay rate, default=0.00000')
142 | parser.add_argument('--clamp_weight', type=int, default=1)
143 | parser.add_argument('--clamp_lower', type=float, default=-0.01)
144 | parser.add_argument('--clamp_upper', type=float, default=0.01)
145 |
146 | parser.add_argument('--use_spatially_varying_uniform_on_top', type=int, default=1, help='Whether to multiply the gaussian noise with a uniform noise map to avoid overfitting')
147 |
148 | parser.add_argument('--continuous_noise', type=int, default=1, help='whether to use continuous noise_std ')
149 | parser.add_argument('--noise_std', type=float, default=1.2, help='std of the added noise, default = 1.2')
150 |
151 | parser.add_argument('--uniform_noise_max', type=float, default=3.464, help='The range of the uniform noise, default = 3.464 to make overall std remain unchange')
152 | parser.add_argument('--min_spatially_continuous_noise_factor', type=float, default=0.01, help='The lower the value, the higher the possibility the varying of the noise be more continuous')
153 | parser.add_argument('--max_spatially_continuous_noise_factor', type=float, default=0.5, help='The upper the value, the higher the possibility the varying of the noise be more continuous')
154 | parser.add_argument('--adam_beta1_d', type=float, default=0.9, help='beta1 of adam for the critic, default = 0.9')
155 | parser.add_argument('--adam_beta2_d', type=float, default=0.999, help='beta2 of adam for the critic, default = 0.999')
156 | parser.add_argument('--adam_eps_d', type=float, default=1e-8, help='eps of adam for the critic, default = 1e-8')
157 | parser.add_argument('--adam_beta1_g', type=float, default=0.9, help='beta1 of adam for the projector, default = 0.9')
158 | parser.add_argument('--adam_beta2_g', type=float, default=0.999, help='beta2 of adam for the projector, default = 0.999')
159 | parser.add_argument('--adam_eps_g', type=float, default=1e-5, help='eps of adam for the projector, default = 1e-8')
160 |
161 | parser.add_argument('--use_tensorboard', type=int, default=1, help='whether to use tensorboard')
162 | parser.add_argument('--tensorboard_period', type=int, default=1, help='how often to write to tensorboard')
163 | parser.add_argument('--output_img', type=int, default=0, help='whether to output images, (also act as the number of images to output)')
164 | parser.add_argument('--output_img_period', type=int, default=100, help='how often to output images')
165 |
166 | parser.add_argument('--clip_input', type=int, default=0, help='clip the input to the network')
167 | parser.add_argument('--clip_input_bound', type=float, default=2.0, help='the maximum of input')
168 |
169 | parser.add_argument('--lambda_ratio', type=float, default=1e-2, help='the weight ratio in the objective function of true images to fake images, default 1e-2')
170 | parser.add_argument('--lambda_l2', type=float, default=5e-3, help='lambda of l2 loss, default = 5e-3')
171 | parser.add_argument('--lambda_latent', type=float, default=1e-4, help='lambda of latent adv loss, default = 1e-4')
172 | parser.add_argument('--lambda_img', type=float, default=1e-3, help='lambda of img adv loss, default = 1e-3')
173 | parser.add_argument('--lambda_de', type=float, default=1.0, help='lambda of the denoising autoencoder, default = 1.0')
174 | parser.add_argument('--de_decay_rate', type=float, default=1.0, help='the rate lambda_de decays, default = 1.0')
175 |
176 | parser.add_argument('--one_sided_label_smooth', type=float, default=0.85, help='the positive label for one-sided, default = 0.85')
177 |
178 | opt = parser.parse_args()
179 | print(opt)
180 |
181 | ### parameters ###
182 | n_epochs = int(opt.n_epochs)
183 | learning_rate_val_dis = float(opt.learning_rate_val_dis)
184 | learning_rate_val_proj = float(opt.learning_rate_val_proj)
185 | learning_rate_val_proj_max = learning_rate_val_proj
186 | learning_rate_val_proj_current = learning_rate_val_proj
187 | weight_decay_rate = float(opt.weight_decay_rate)
188 | batch_size = int(opt.batch_size)
189 |
190 | std = float(opt.noise_std)
191 | continuous_noise = int(opt.continuous_noise)
192 |
193 | use_spatially_varying_uniform_on_top = int(opt.use_spatially_varying_uniform_on_top)
194 | uniform_noise_max = float(opt.uniform_noise_max)
195 | min_spatially_continuous_noise_factor = float(opt.min_spatially_continuous_noise_factor)
196 | max_spatially_continuous_noise_factor = float(opt.max_spatially_continuous_noise_factor)
197 |
198 |
199 | img_size = int(opt.img_size)
200 | Dperiod = int(opt.Dperiod)
201 | Gperiod = int(opt.Gperiod)
202 |
203 | clamp_weight = int(opt.clamp_weight)
204 | clamp_lower = float(opt.clamp_lower)
205 | clamp_upper = float(opt.clamp_upper)
206 |
207 | random_seed = int(opt.random_seed)
208 |
209 | adam_beta1_d = float(opt.adam_beta1_d)
210 | adam_beta2_d = float(opt.adam_beta2_d)
211 | adam_eps_d = float(opt.adam_eps_d)
212 |
213 | adam_beta1_g = float(opt.adam_beta1_g)
214 | adam_beta2_g = float(opt.adam_beta2_g)
215 | adam_eps_g = float(opt.adam_eps_g)
216 |
217 | use_tensorboard = int(opt.use_tensorboard)
218 | tensorboard_period = int(opt.tensorboard_period)
219 | output_img = int(opt.output_img)
220 | output_img_period = int(opt.output_img_period)
221 |
222 | clip_input = int(opt.clip_input)
223 | clip_input_bound = float(opt.clip_input_bound)
224 |
225 | lambda_ratio = float(opt.lambda_ratio)
226 | lambda_l2 = float(opt.lambda_l2)
227 | lambda_latent = float(opt.lambda_latent)
228 | lambda_img = float(opt.lambda_img)
229 | lambda_de = float(opt.lambda_de)
230 | de_decay_rate = float(opt.de_decay_rate)
231 |
232 | one_sided_label_smooth = float(opt.one_sided_label_smooth)
233 |
234 | n_reference = int(opt.n_reference)
235 | inst_size = batch_size - n_reference
236 |
237 |
238 | base_folder = opt.base_folder
239 |
240 | if base_folder == None:
241 | base_folder = 'model'
242 |
243 | base_folder = '%s/imsize%d_ratio%f_dis%f_latent%f_img%f_de%f_derate%f_dp%d_gd%d_softpos%f_wdcy_%f_seed%d' % (
244 | base_folder, img_size, lambda_ratio, lambda_l2, lambda_latent, lambda_img,
245 | lambda_de, de_decay_rate,
246 | Dperiod, Gperiod,
247 | one_sided_label_smooth,
248 | weight_decay_rate,
249 | random_seed
250 | )
251 |
252 | model_path = '%s/model' % (base_folder)
253 | if not os.path.exists(model_path):
254 | os.makedirs(model_path)
255 |
256 | epoch_path = '%s/epoch' % (base_folder)
257 | if not os.path.exists(epoch_path):
258 | os.makedirs(epoch_path)
259 |
260 | init_path = '%s/init' % (base_folder)
261 | if not os.path.exists(init_path):
262 | os.makedirs(init_path)
263 |
264 | img_path = '%s/image' % (base_folder)
265 | if not os.path.exists(img_path):
266 | os.makedirs(img_path)
267 |
268 | logs_base = '/tmp/tensorflow_logs'
269 | logs_path = '%s/%s' % (logs_base, base_folder)
270 |
271 | # write configurations to a file
272 | filename = '%s/configurations.txt' % (base_folder)
273 | f = open( filename, 'a' )
274 | f.write( repr(opt) + '\n' )
275 | f.close()
276 |
277 | pretrained_iter = int(opt.pretrained_iter)
278 | use_pretrain = pretrained_iter > 0
279 | pretrained_model_file = '%s/model_iter-%d' % (model_path, pretrained_iter)
280 |
281 | tf.set_random_seed(random_seed)
282 |
283 |
284 | ### load the dataset ###
285 |
286 | def read_file_cpu(trainset, queue, batch_size, num_prepare, rseed=None):
287 | local_random = np.random.RandomState(rseed)
288 |
289 | n_train = len(trainset)
290 | trainset_index = local_random.permutation(n_train)
291 | idx = 0
292 | while True:
293 | # read in data if the queue is too short
294 | while queue.full() == False:
295 | batch = np.zeros([batch_size, img_size, img_size, 3])
296 | noisy_batch = np.zeros([batch_size, img_size, img_size, 3])
297 | for i in range(batch_size):
298 | image_path = trainset[trainset_index[idx+i]]
299 | img = sp.misc.imread(image_path)
300 | # In our original code used to generate the results in the paper, we directly
301 | # resize the image directly to the input dimension via (for both ms-celeb-1m and imagenet)
302 | img = sp.misc.imresize(img, [img_size, img_size]).astype(float) / 255.0
303 |
304 | # The following code crops random-sized patches (may be useful for imagenet)
305 | #img_shape = img.shape
306 | #min_edge = min(img_shape[0], img_shape[1])
307 | #min_resize_ratio = float(img_size) / float(min_edge)
308 | #max_resize_ratio = min_resize_ratio * 2.0
309 | #resize_ratio = local_random.rand() * (max_resize_ratio - min_resize_ratio) + min_resize_ratio
310 |
311 | #img = sp.misc.imresize(img, resize_ratio).astype(float) / 255.0
312 | #crop_loc_row = local_random.randint(img.shape[0]-img_size+1)
313 | #crop_loc_col = local_random.randint(img.shape[1]-img_size+1)
314 | #if len(img.shape) == 3:
315 | #img = img[crop_loc_row:crop_loc_row+img_size, crop_loc_col:crop_loc_col+img_size,:]
316 | #else:
317 | #img = img[crop_loc_row:crop_loc_row+img_size, crop_loc_col:crop_loc_col+img_size]
318 |
319 | if np.prod(img.shape) == 0:
320 | img = np.zeros([img_size, img_size, 3])
321 |
322 | if len(img.shape) < 3:
323 | img = np.expand_dims(img, axis=2)
324 | img = np.tile(img, [1,1,3])
325 |
326 | ## random flip
327 | #flip_prob = local_random.rand()
328 | #if flip_prob < 0.5:
329 | #img = img[-1:None:-1,:,:]
330 |
331 | #flip_prob = local_random.rand()
332 | #if flip_prob < 0.5:
333 | #img = img[:,-1:None:-1,:]
334 |
335 | # add noise to img
336 | noisy_img = add_noise(img, local_random,
337 | std=std,
338 | uniform_max=uniform_noise_max,
339 | min_spatially_continuous_noise_factor=min_spatially_continuous_noise_factor,
340 | max_spatially_continuous_noise_factor=max_spatially_continuous_noise_factor,
341 | continuous_noise=continuous_noise,
342 | use_spatially_varying_uniform_on_top=use_spatially_varying_uniform_on_top,
343 | clip_input=clip_input, clip_input_bound=clip_input_bound
344 | )
345 |
346 | batch[i] = img
347 | noisy_batch[i] = noisy_img
348 |
349 | batch *= 2.0
350 | batch -= 1.0
351 | noisy_batch *= 2.0
352 | noisy_batch -= 1.0
353 |
354 | if clip_input > 0:
355 | batch = np.clip(batch, a_min=-clip_input_bound, a_max=clip_input_bound)
356 | noisy_batch = np.clip(noisy_batch, a_min=-clip_input_bound, a_max=clip_input_bound)
357 |
358 | queue.put([batch, noisy_batch]) # block until free slot is available
359 |
360 | idx += batch_size
361 | if idx > n_train: #reset when last batch is smaller than batch_size or reaching the last batch
362 | trainset_index = local_random.permutation(n_train)
363 | idx = 0
364 |
365 | def create_train_procs(trainset, train_queue, n_thread, num_prepare, train_procs):
366 | """
367 | create threads to read the images from hard drive and perturb them
368 | """
369 | for n_read in range(n_thread):
370 | seed = np.random.randint(1e8)
371 | instance_size = batch_size - n_reference
372 | if instance_size < 1:
373 | print 'ERROR: batch_size < n_reference + 1'
374 | train_proc = Process(target=read_file_cpu, args=(trainset, train_queue, instance_size, num_prepare, seed))
375 | train_proc.daemon = True
376 | train_proc.start()
377 | train_procs.append(train_proc)
378 |
379 | def terminate_train_procs(train_procs):
380 | """
381 | terminate the threads to force garbage collection and free memory
382 | """
383 | for procs in train_procs:
384 | procs.terminate()
385 |
386 |
387 | trainset = load_dataset.load_trainset_path_list()
388 | total_train = len(trainset)
389 | print 'total train = %d' % (total_train)
390 |
391 |
392 | print "create reference batch..."
393 | n_thread = 1
394 | num_prepare = 1
395 | reference_queue = Queue(num_prepare)
396 | ref_seed = 1085 # the random seed particularly for creating the reference batch
397 | ref_proc = Process(target=read_file_cpu, args=(trainset, reference_queue, n_reference, num_prepare, ref_seed))
398 | ref_proc.daemon = True
399 | ref_proc.start()
400 |
401 | _, ref_batch = reference_queue.get()
402 |
403 | ref_proc.terminate()
404 | del ref_proc
405 | del reference_queue
406 |
407 | # save reference to a mat file
408 | ref_file = '%s/ref_batch_%d.mat' % (base_folder, n_reference)
409 | sp.io.savemat(ref_file, {'ref_batch': ref_batch})
410 | print 'ref_batch saved.'
411 |
412 | def np_combine_batch(inst,ref):
413 | out = np.concatenate([inst,ref], axis=0)
414 | return out
415 | def get_inst(batch):
416 | return batch[0:inst_size]
417 |
418 |
419 | print "loading data..."
420 |
421 | n_thread = 16
422 | num_prepare = 20
423 | print 'total train = %d' % (total_train)
424 | train_queue = Queue(num_prepare+1)
425 | train_procs = []
426 | create_train_procs(trainset, train_queue, n_thread, num_prepare, train_procs)
427 |
428 |
429 | ### set up the graph
430 | # images
431 | images_tf = tf.placeholder( tf.float32, [batch_size, img_size, img_size, 3], name="images_tf")
432 | noisy_image_tf = tf.placeholder( tf.float32, [batch_size, img_size, img_size, 3], name="noisy_image_tf")
433 |
434 | # lambdas
435 | lambda_ratio_tf = tf.placeholder( tf.float32, [], name='lambda_ratio_tf')
436 | lambda_l2_tf = tf.placeholder( tf.float32, [], name='lambda_l2_tf')
437 | lambda_latent_tf = tf.placeholder( tf.float32, [], name='lambda_latent_tf')
438 | lambda_img_tf = tf.placeholder( tf.float32, [], name='lambda_img')
439 | lambda_de_tf = tf.placeholder( tf.float32, [], name='lambda_de')
440 |
441 | is_train = True
442 | learning_rate_dis = tf.placeholder( tf.float32, [], name='learning_rate_dis')
443 | learning_rate_proj = tf.placeholder( tf.float32, [], name='learning_rate_proj')
444 | adam_beta1_d_tf = tf.placeholder( tf.float32, [], name='adam_beta1_d_tf')
445 | adam_beta1_g_tf = tf.placeholder( tf.float32, [], name='adam_beta1_g_tf')
446 |
447 |
448 | images_dataset = images_tf
449 |
450 | # build autoencoder
451 | projection_x_all, latent_x_all = build_projection_model(images_dataset, is_train, n_reference)
452 | projection_x = get_inst(projection_x_all)
453 | latent_x = get_inst(latent_x_all)
454 |
455 | projection_z_all, latent_z_all = build_projection_model(noisy_image_tf, is_train, n_reference, reuse=True)
456 | projection_z = get_inst(projection_z_all)
457 | latent_z = get_inst(latent_z_all)
458 |
459 | # build the discriminator
460 | # image space
461 | adversarial_truex_all, _ = build_classifier_model_imagespace(images_dataset, is_train, n_reference)
462 | adversarial_truex = get_inst(adversarial_truex_all)
463 |
464 | adversarial_projx_all, _ = build_classifier_model_imagespace(projection_x, is_train, n_reference, reuse=True)
465 | adversarial_projx = get_inst(adversarial_projx_all)
466 |
467 | adversarial_projz_all, _ = build_classifier_model_imagespace(projection_z, is_train, n_reference, reuse=True)
468 | adversarial_projz = get_inst(adversarial_projz_all)
469 |
470 | # latent space
471 | if lambda_latent > 0:
472 | adversarial_latentx_all, _ = build_classifier_model_latentspace(latent_x, is_train, n_reference)
473 | adversarial_latentz_all, _ = build_classifier_model_latentspace(latent_z, is_train, n_reference, reuse=True)
474 | else:
475 | adversarial_latentx_all = tf.zeros([batch_size])
476 | adversarial_latentz_all = tf.zeros([batch_size])
477 |
478 | adversarial_latentx = get_inst(adversarial_latentx_all)
479 | adversarial_latentz = get_inst(adversarial_latentz_all)
480 |
481 |
482 | # update_op for batch_norm moving average
483 | update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
484 | if update_ops:
485 | updates = tf.group(*update_ops)
486 | else:
487 | print 'something is wrong!'
488 |
489 | # if we are using virtual batch normalization, we do not need to calculate the population mean and variance
490 | if n_reference > 0:
491 | updates = tf.zeros([1])
492 |
493 | # set up the loss for D
494 | pos_labels = tf.ones([inst_size],1)
495 | soft_pos_labels = pos_labels * one_sided_label_smooth
496 | neg_labels = tf.zeros([tf.shape(adversarial_latentz)[0]],1)
497 |
498 | loss_adv_D_pos_latent = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(adversarial_latentx, soft_pos_labels))
499 | loss_adv_D_neg_latent = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(adversarial_latentz, neg_labels))
500 |
501 | loss_adv_D_latent = lambda_ratio_tf*loss_adv_D_pos_latent + (1-lambda_ratio_tf)*loss_adv_D_neg_latent
502 |
503 | loss_adv_D_pos_img = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(adversarial_truex, soft_pos_labels))
504 | loss_adv_D_neg_img = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(adversarial_projx, neg_labels))
505 | loss_adv_D_neg_imgz = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(adversarial_projz, neg_labels))
506 |
507 | loss_adv_D_img = (loss_adv_D_pos_img + lambda_ratio_tf*loss_adv_D_neg_img + (1-lambda_ratio_tf)*loss_adv_D_neg_imgz ) * 0.5 # currently not using loss_adv_D_neg_imgz
508 |
509 | est_labels_latent = tf.to_float(tf.concat(0,
510 | [tf.greater_equal(adversarial_latentx,0.0),
511 | tf.less(adversarial_latentz,0.0),
512 | ] ))
513 | accuracy_latent = tf.reduce_mean(est_labels_latent, name='accuracy_latent')
514 |
515 | est_labels_img = tf.to_float(tf.concat(0,
516 | [tf.greater_equal(adversarial_truex,0.0),
517 | tf.less(adversarial_projx,0.0),
518 | ] ))
519 | accuracy_img = tf.reduce_mean(est_labels_img, name='accuracy_img')
520 |
521 |
522 | # set up the loss for autoencoder
523 | loss_proj = tf.reduce_mean(tf.square(projection_z - get_inst(noisy_image_tf) ) )
524 | loss_recon = tf.reduce_mean(tf.square(projection_x - get_inst(images_dataset) ))
525 | loss_recon_z = tf.reduce_mean(tf.square(projection_z - get_inst(images_dataset) ))
526 |
527 | labels_G = pos_labels # flip label when training G
528 |
529 |
530 | # latent
531 | loss_adv_G_latent = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(adversarial_latentz, labels_G))
532 |
533 | # imagespace
534 | loss_adv_G_imgx = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(adversarial_projx, labels_G))
535 | loss_adv_G_imgz = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(adversarial_projz, labels_G))
536 | loss_adv_G_img = lambda_ratio_tf*loss_adv_G_imgx + (1-lambda_ratio_tf)*loss_adv_G_imgz
537 |
538 | loss_adv_G = lambda_latent_tf * loss_adv_G_latent + lambda_img_tf * loss_adv_G_img
539 |
540 | loss_adv_D = lambda_latent_tf * loss_adv_D_latent + lambda_img*loss_adv_D_img
541 | loss_G = loss_adv_G + lambda_l2_tf * (lambda_ratio_tf * loss_recon + (1-lambda_ratio_tf)*loss_proj )
542 | # train with a denoising autoencoder weight first
543 | loss_G += lambda_de_tf * loss_recon_z
544 |
545 | var_D = filter( lambda x: x.name.startswith('DIS'), tf.trainable_variables())
546 | W_D = filter(lambda x: x.name.endswith('W:0'), var_D)
547 |
548 | var_G = filter( lambda x: x.name.startswith('PROJ'), tf.trainable_variables())
549 | W_G = filter(lambda x: x.name.endswith('W:0'), var_G)
550 |
551 | var_E = filter( lambda x: 'ENCODE' in x.name, tf.trainable_variables())
552 | W_E = filter(lambda x: x.name.endswith('W:0'), var_E)
553 |
554 | if weight_decay_rate > 0:
555 | loss_G += weight_decay_rate * tf.reduce_mean(tf.pack( map(lambda x: tf.nn.l2_loss(x), W_G)))
556 | loss_adv_D += weight_decay_rate * tf.reduce_mean(tf.pack( map(lambda x: tf.nn.l2_loss(x), W_D)))
557 |
558 | config_proto = tf.ConfigProto()
559 | config_proto.gpu_options.allow_growth=True
560 |
561 | sess = tf.Session(config=config_proto)
562 |
563 | optimizer_G = tf.train.AdamOptimizer( learning_rate=learning_rate_proj, beta1=adam_beta1_g_tf, beta2=adam_beta2_g, epsilon=adam_eps_g)
564 | grads_vars_G = optimizer_G.compute_gradients( loss_G, var_list=var_G )
565 | grads_vars_G_clipped = map(lambda gv: [tf.clip_by_value(gv[0], -10., 10.), gv[1]], grads_vars_G)
566 | train_op_G = optimizer_G.apply_gradients( grads_vars_G_clipped )
567 |
568 | optimizer_D = tf.train.AdamOptimizer( learning_rate=learning_rate_dis, beta1=adam_beta1_d_tf, beta2=adam_beta2_d, epsilon=adam_eps_d)
569 | grads_vars_D = optimizer_D.compute_gradients( loss_adv_D, var_list=var_D )
570 | grads_vars_D_clipped = map(lambda gv: [tf.clip_by_value(gv[0], -10., 10.), gv[1]], grads_vars_D)
571 | train_op_D = optimizer_D.apply_gradients( grads_vars_D_clipped )
572 |
573 | D_var_clip_ops = map(lambda v: tf.assign(v, tf.clip_by_value(v, clamp_lower, clamp_upper)), W_D)
574 | E_var_clip_ops = map(lambda v: tf.assign(v, tf.clip_by_value(v, clamp_lower, clamp_upper)), W_E)
575 |
576 |
577 | # setup the saver
578 | saver = tf.train.Saver(max_to_keep=16)
579 | saver_epoch = tf.train.Saver(max_to_keep=100)
580 |
581 | # setup the image saver
582 | if output_img > 0:
583 | num_output_img = min(5, batch_size)
584 | output_ori_imgs_op = (images_tf[0:num_output_img] * 127.5 ) + 127.5
585 | output_noisy_imgs_op = (noisy_image_tf[0:num_output_img] * 127.5 ) + 127.5
586 | output_project_imgs_op = (projection_z[0:num_output_img] * 127.5 ) + 127.5
587 | output_reconstruct_imgs_op = (projection_x[0:num_output_img] * 127.5 ) + 127.5
588 |
589 | if use_tensorboard > 0:
590 | # create a summary to monitor cost tensor
591 | tf.summary.scalar("accuracy_latent", accuracy_latent, collections=['dis'])
592 | tf.summary.scalar("accuracy_img", accuracy_img, collections=['dis'])
593 | tf.summary.scalar("loss_adv_D", loss_adv_D, collections=['dis'])
594 | tf.summary.scalar("loss_adv_D_pos_latent", loss_adv_D_pos_latent, collections=['dis'])
595 | tf.summary.scalar("loss_adv_D_neg_latent", loss_adv_D_neg_latent, collections=['dis'])
596 | tf.summary.scalar("loss_adv_D_latent", loss_adv_D_latent, collections=['dis'])
597 | tf.summary.scalar("loss_adv_D_pos_img", loss_adv_D_pos_img, collections=['dis'])
598 | tf.summary.scalar("loss_adv_D_neg_img", loss_adv_D_neg_img, collections=['dis'])
599 | tf.summary.scalar("loss_adv_D_neg_imgz", loss_adv_D_neg_imgz, collections=['dis'])
600 | tf.summary.scalar("loss_adv_D_img", loss_adv_D_img, collections=['dis'])
601 |
602 | tf.summary.scalar("loss_G", loss_G, collections=['proj'])
603 | tf.summary.scalar("loss_adv_G", loss_adv_G, collections=['proj'])
604 | tf.summary.scalar("loss_adv_G_latent", loss_adv_G_latent, collections=['proj'])
605 | tf.summary.scalar("loss_adv_G_imgx", loss_adv_G_imgx, collections=['proj'])
606 | tf.summary.scalar("loss_recon_z", loss_recon_z, collections=['proj'])
607 | tf.summary.scalar("loss_recon", loss_recon, collections=['proj'])
608 | tf.summary.scalar("loss_proj", loss_proj, collections=['proj'])
609 | tf.summary.scalar("lambda_ratio", lambda_ratio_tf, collections=['proj'])
610 | tf.summary.scalar("lambda_l2", lambda_l2_tf, collections=['proj'])
611 | tf.summary.scalar("lambda_latent", lambda_latent_tf, collections=['proj'])
612 | tf.summary.scalar("lambda_img", lambda_img_tf, collections=['proj'])
613 | tf.summary.scalar("lambda_de", lambda_de_tf, collections=['proj'])
614 | tf.summary.scalar("adam_beta1_g", adam_beta1_g_tf, collections=['proj'])
615 | tf.summary.scalar("adam_beta1_d", adam_beta1_d_tf, collections=['proj'])
616 | tf.summary.scalar("learning_rate_proj", learning_rate_proj, collections=['proj'])
617 | tf.summary.scalar("learning_rate_dis", learning_rate_dis, collections=['proj'])
618 | tf.summary.image("original_image", images_tf, max_outputs=5, collections=['proj'])
619 | tf.summary.image("noisy_image", noisy_image_tf, max_outputs=5, collections=['proj'])
620 | tf.summary.image("projected_z", projection_z, max_outputs=5, collections=['proj'])
621 | tf.summary.image("reconstructed_x", projection_x, max_outputs=5, collections=['proj'])
622 |
623 | # merge all summaries into a single op
624 | summary_G = tf.summary.merge_all(key='proj')
625 | summary_D = tf.summary.merge_all(key='dis')
626 |
627 | # initialization
628 | sess.run(tf.global_variables_initializer(), feed_dict={
629 | learning_rate_dis: learning_rate_val_dis,
630 | adam_beta1_d_tf: adam_beta1_d,
631 | learning_rate_proj: learning_rate_val_proj,
632 | lambda_ratio_tf: lambda_ratio,
633 | lambda_l2_tf: lambda_l2,
634 | lambda_latent_tf: lambda_latent,
635 | lambda_img_tf: lambda_img,
636 | lambda_de_tf: lambda_de,
637 | adam_beta1_g_tf: adam_beta1_g,
638 | })
639 | sess.run(tf.local_variables_initializer(), feed_dict={
640 | learning_rate_dis: learning_rate_val_dis,
641 | adam_beta1_d_tf: adam_beta1_d,
642 | learning_rate_proj: learning_rate_val_proj,
643 | lambda_ratio_tf: lambda_ratio,
644 | lambda_l2_tf: lambda_l2,
645 | lambda_latent_tf: lambda_latent,
646 | lambda_img_tf: lambda_img,
647 | lambda_de_tf: lambda_de,
648 | adam_beta1_g_tf: adam_beta1_g,
649 | })
650 |
651 |
652 | print 'reload previously trained model'
653 | if use_pretrain == True:
654 | print 'reloading %s...' % pretrained_model_file
655 | saver.restore( sess, pretrained_model_file )
656 |
657 | if use_tensorboard > 0:
658 | # op to write logs to Tensorboard
659 | summary_writer = tf.summary.FileWriter(logs_path, graph=tf.get_default_graph())
660 | print "Run the command line:\n --> tensorboard --logdir=%s\n" % logs_base
661 | print "Then open http://0.0.0.0:6006/ into your web browser"
662 |
663 |
664 | # continue the iteration number
665 | if use_pretrain == True:
666 | iters = pretrained_iter + 1
667 | else:
668 | iters = 0
669 |
670 | start_epoch = iters // (total_train // batch_size)
671 |
672 |
673 | print 'start training'
674 | start_time = timeit.default_timer()
675 |
676 | iters_in_epoch = total_train // batch_size
677 | epoch = 0
678 |
679 | loss_dis_avg = SmoothStream(window_size=100)
680 | acc_latent_avg = SmoothStream(window_size=100)
681 | acc_img_avg = SmoothStream(window_size=100)
682 | loss_recon_avg = SmoothStream(window_size=100)
683 | loss_recon_z_avg = SmoothStream(window_size=100)
684 |
685 | update_D_left = Dperiod
686 | update_G_left = Gperiod
687 |
688 | loss_G_val = 0
689 | loss_proj_val = 0
690 | loss_recon_val = 0
691 | loss_recon_z_val = 0
692 | loss_adv_G_val = 0
693 | loss_D_val = 0
694 | acc_latent_val = 0
695 | acc_img_val = 0
696 |
697 |
698 | print 'alternative training starts....'
699 |
700 | while True:
701 | inst_batch, inst_noisy_batch = train_queue.get()
702 |
703 | batch = np_combine_batch(inst_batch,ref_batch)
704 | noisy_batch = np_combine_batch(inst_noisy_batch,ref_batch)
705 |
706 | # adjust learning rate
707 | learning_rate_val_proj_current = 2e-1 / lambda_de
708 | learning_rate_val_proj_current = min(learning_rate_val_proj, learning_rate_val_proj_current)
709 |
710 |
711 | if update_G_left > 0:
712 |
713 | sys.stdout.write('G: ')
714 |
715 | # update G
716 | _, loss_G_val, loss_proj_val, loss_recon_val, loss_recon_z_val, loss_adv_G_val, _ = sess.run(
717 | [train_op_G, loss_G, loss_proj, loss_recon, loss_recon_z, loss_adv_G, updates],
718 | feed_dict={
719 | images_tf: batch,
720 | noisy_image_tf: noisy_batch,
721 | learning_rate_dis: learning_rate_val_dis,
722 | adam_beta1_d_tf: adam_beta1_d,
723 | learning_rate_proj: learning_rate_val_proj_current,
724 | lambda_ratio_tf: lambda_ratio,
725 | lambda_l2_tf: lambda_l2,
726 | lambda_latent_tf: lambda_latent,
727 | lambda_img_tf: lambda_img,
728 | lambda_de_tf: lambda_de,
729 | adam_beta1_g_tf: adam_beta1_g,
730 | })
731 |
732 | update_G_left -= 1
733 | loss_recon_avg.insert(loss_recon_val)
734 | loss_recon_z_avg.insert(loss_recon_z_val)
735 |
736 |
737 | if update_G_left <= 0 and update_D_left > 0:
738 |
739 | sys.stdout.write('D: ')
740 |
741 | # update D
742 | _, loss_D_val, acc_latent_val, acc_img_val, _ = sess.run(
743 | [train_op_D, loss_adv_D, accuracy_latent, accuracy_img, updates],
744 | feed_dict={
745 | images_tf: batch,
746 | noisy_image_tf: noisy_batch,
747 | learning_rate_dis: learning_rate_val_dis,
748 | adam_beta1_d_tf: adam_beta1_d,
749 | learning_rate_proj: learning_rate_val_proj_current,
750 | lambda_ratio_tf: lambda_ratio,
751 | lambda_l2_tf: lambda_l2,
752 | lambda_latent_tf: lambda_latent,
753 | lambda_img_tf: lambda_img,
754 | lambda_de_tf: lambda_de,
755 | adam_beta1_g_tf: adam_beta1_g,
756 | })
757 |
758 | if clamp_weight > 0:
759 | # clip the variables of the discriminator
760 | _,_ = sess.run([D_var_clip_ops, E_var_clip_ops])
761 |
762 | update_D_left -= 1
763 |
764 | loss_dis_avg.insert(loss_D_val)
765 | acc_latent_avg.insert(acc_latent_val)
766 | acc_img_avg.insert(acc_img_val)
767 |
768 | print "Iter %d (%.2fm): l_gen=%.3e l_proj=%.3e l_recon=%.3e (%.3e) l_recon_z=%.3e (%.3e) l_adv_gen=%.3e l_dis=%.3e (%.3e) acc_img=%.3e (%.3e) acc_latent=%.3e (%.3e) lrp=%.3e lrd=%.3e qsize=%d" % (
769 | iters, (timeit.default_timer()-start_time)/60., loss_G_val, loss_proj_val, loss_recon_val,
770 | loss_recon_avg.get_moving_avg(), loss_recon_z_val, loss_recon_z_avg.get_moving_avg(), loss_adv_G_val, loss_D_val, loss_dis_avg.get_moving_avg(),
771 | acc_img_val, acc_img_avg.get_moving_avg(),
772 | acc_latent_val, acc_latent_avg.get_moving_avg(),
773 | learning_rate_val_proj, learning_rate_val_dis, train_queue.qsize())
774 |
775 |
776 | # reset update_D_left and update_G_left when they are zeros
777 | if update_G_left <= 0 and update_D_left <= 0:
778 | update_G_left = Gperiod
779 | update_D_left = Dperiod
780 |
781 | if (iters + 1) % 2000 == 0:
782 | saver.save(sess, model_path + '/model_iter', global_step=iters)
783 |
784 |
785 | # output to tensorboard
786 | if use_tensorboard >0 and (iters % tensorboard_period == 0):
787 |
788 | summary_d_vals, summary_g_vals = sess.run(
789 | [summary_D, summary_G],
790 | feed_dict={
791 | images_tf: batch,
792 | noisy_image_tf: noisy_batch,
793 | learning_rate_dis: learning_rate_val_dis,
794 | learning_rate_proj: learning_rate_val_proj_current,
795 | lambda_ratio_tf: lambda_ratio,
796 | lambda_l2_tf: lambda_l2,
797 | lambda_latent_tf: lambda_latent,
798 | lambda_img_tf: lambda_img,
799 | lambda_de_tf: lambda_de,
800 | adam_beta1_g_tf: adam_beta1_g,
801 | adam_beta1_d_tf: adam_beta1_d
802 | })
803 |
804 | summary_writer.add_summary(summary_g_vals, iters)
805 | summary_writer.add_summary(summary_d_vals, iters)
806 |
807 | # save some images
808 | if output_img > 0 and (iters + 1) % output_img_period == 0:
809 | output_ori_img_val, output_noisy_img_val, output_project_img_val, output_reconstruct_imgs_val = sess.run(
810 | [output_ori_imgs_op, output_noisy_imgs_op, output_project_imgs_op, output_reconstruct_imgs_op],
811 | feed_dict={
812 | images_tf: batch,
813 | noisy_image_tf: noisy_batch,
814 | }
815 | )
816 | output_folder = '%s/iter_%d' %(img_path, iters)
817 | if not os.path.exists(output_folder):
818 | os.makedirs(output_folder)
819 | for i in range(output_ori_img_val.shape[0]):
820 | filename = '%s/%d_ori.jpg' % (output_folder, i)
821 | sp.misc.imsave(filename, output_ori_img_val[i].astype('uint8'))
822 | filename = '%s/%d_noisy.jpg' % (output_folder, i)
823 | sp.misc.imsave(filename, output_noisy_img_val[i].astype('uint8'))
824 | filename = '%s/%d_proj.jpg' % (output_folder, i)
825 | sp.misc.imsave(filename, output_project_img_val[i].astype('uint8'))
826 | filename = '%s/%d_recon.jpg' % (output_folder, i)
827 | sp.misc.imsave(filename, output_reconstruct_imgs_val[i].astype('uint8'))
828 |
829 | iters += 1
830 |
831 | lambda_de *= de_decay_rate
832 |
833 |
834 | if iters % iters_in_epoch == 0:
835 | epoch += 1
836 | saver_epoch.save(sess, epoch_path + '/model_epoch', global_step=epoch)
837 | learning_rate_val_dis *= 0.95
838 | learning_rate_val_proj *= 0.95
839 | if epoch > n_epochs:
840 | break
841 |
842 | # recreate new train_proc (force garbage colection)
843 | if iters % 2000 == 0:
844 | terminate_train_procs(train_procs)
845 | del train_procs
846 | del train_queue
847 | train_queue = Queue(num_prepare+1)
848 | train_procs = []
849 | create_train_procs(trainset, train_queue, n_thread, num_prepare, train_procs)
850 |
851 | sess.close()
852 |
--------------------------------------------------------------------------------