-
Notifications
You must be signed in to change notification settings - Fork 1
/
run_3parts.py
201 lines (174 loc) · 8.08 KB
/
run_3parts.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""
Trains an HGAN, and visulizes results
Author(s): Wei Chen ([email protected])
"""
import argparse
import os.path
import json
import numpy as np
from importlib import import_module
from shape_plot import plot_samples, plot_grid
from metrics.diversity import ci_rdiv
from metrics.mmd import ci_mmd
from metrics.precision import ci_prc
from metrics.consistency import ci_cons
from utils import ElapsedTimer
if __name__ == "__main__":
# Arguments
parser = argparse.ArgumentParser(description='Train')
parser.add_argument('mode', type=str, default='startover', help='startover, continue, or evaluate')
parser.add_argument('data', type=str, default='AHH', help='AHH, SEoEi, SEiEo, or SCC')
parser.add_argument('--sample_size', type=int, default=10000, help='sample size')
parser.add_argument('--save_interval', type=int, default=500, help='save interval')
args = parser.parse_args()
assert args.mode in ['startover', 'continue', 'evaluate']
assert args.data in ['AHH', 'SEoEi', 'SEiEo', 'SCC']
print('##################################################################')
print('Data: {}'.format(args.data))
model_name = 'hgan'
print('Model: {}'.format(model_name))
print('Sample size: {}'.format(args.sample_size))
# Set hyper-parameters
if args.data == 'AHH':
data_fname = 'results/AHH/AHH.npy'
latent_dim = [3, 3, 2]
noise_dim = [10, 0, 0]
n_points = [64, 64, 64]
dependency = [[], [0], [0,1]]
bezier_degree = [31, None, None]
bounds = (0.0, 1.0)
train_steps = 100000
batch_size = 32
elif args.data == 'SEoEi':
data_fname = 'results/SEoEi/SEoEi.npy'
latent_dim = [2, 2, 2]
noise_dim = [10, 0, 0]
n_points = [64, 64, 64]
dependency = [[], [0], [1]]
bezier_degree = [31, None, None]
bounds = (0.0, 1.0)
train_steps = 100000
batch_size = 32
elif args.data == 'SEiEo':
data_fname = 'results/SEiEo/SEiEo.npy'
latent_dim = [2, 2, 2]
noise_dim = [10, 0, 0]
n_points = [64, 64, 64]
dependency = [[], [0], [0,1]]
bezier_degree = [31, None, None]
bounds = (0.0, 1.0)
train_steps = 100000
batch_size = 32
elif args.data == 'SCC':
data_fname = 'results/SCC/SCC.npy'
latent_dim = [2, 2, 2]
noise_dim = [10, 0, 0]
n_points = [64, 64, 64]
dependency = [[], [0], [0]]
bezier_degree = [31, None, None]
bounds = (0.0, 1.0)
train_steps = 100000
batch_size = 32
# Read dataset
X = np.load(data_fname)
ind = np.random.choice(X.shape[0], size=args.sample_size, replace=False)
X = X[ind]
# Split training and test data
test_split = 0.8
N = X.shape[0]
split = int(N*test_split)
X_train = X[:split]
X_test = X[split:]
X0_test = X_test[:,:n_points[0]]
X1_test = X_test[:,n_points[0]:n_points[0]+n_points[1]]
X2_test = X_test[:,-n_points[2]:]
X_test_list = [X0_test, X1_test, X2_test]
results_dir = 'results/{}/{}/{}'.format(args.data, model_name, args.sample_size)
if not os.path.exists(results_dir):
os.makedirs(results_dir)
# Train
h = import_module('{}.{}'.format(args.data, model_name))
model = h.Model(latent_dim, noise_dim, n_points, bezier_degree)
if args.mode == 'startover':
timer = ElapsedTimer()
model.train(X_train, batch_size=batch_size, train_steps=train_steps, save_interval=args.save_interval, save_dir=results_dir)
elapsed_time = timer.elapsed_time()
runtime_mesg = 'Wall clock time for training: %s' % elapsed_time
print(runtime_mesg)
runtime_file = open('{}/runtime.txt'.format(results_dir), 'w')
runtime_file.write('%s\n' % runtime_mesg)
runtime_file.close()
else:
model.restore(save_dir=results_dir)
print('Plotting training samples ...')
samples_list = []
n_points_c = np.cumsum([0,] + n_points)
for i in range(len(n_points)):
samples_list.append(np.squeeze(X)[:25, n_points_c[i]:n_points_c[i+1]])
plot_samples(None, samples_list, scatter=False, alpha=.7, c='k', fname='%s/samples' % args.data)
print('Plotting synthesized x0 ...')
plot_grid(5, gen_func=model.synthesize_x0, d=latent_dim[0], scale=.95,
scatter=False, alpha=.7, c='k', fname='{}/x0'.format(results_dir))
X1, X0 = model.synthesize_x1(1)
print('Plotting synthesized x1 ...')
synthesize_x1 = lambda x: model.synthesize_x1(x, [X0])
plot_grid(5, gen_func=synthesize_x1, d=latent_dim[1], scale=.95,
scatter=False, alpha=.7, c='k', fname='{}/x1'.format(results_dir))
print('Plotting synthesized x2 ...')
if model_name == 'hgan_cat':
synthesize_x2_0 = lambda x: model.synthesize_x2(x, 0, [X0, X1])
synthesize_x2_1 = lambda x: model.synthesize_x2(x, 1, [X0, X1])
plot_grid(5, gen_func=synthesize_x2_0, proba_func=None, d=latent_dim[2], scale=.95,
scatter=False, alpha=.7, c='k', fname='{}/x2_0'.format(results_dir))
plot_grid(5, gen_func=synthesize_x2_1, proba_func=None, d=latent_dim[2], scale=.95,
scatter=False, alpha=.7, c='k', fname='{}/x2_1'.format(results_dir))
else:
synthesize_x2 = lambda x: model.synthesize_x2(x, [X0, X1])
plot_grid(5, gen_func=synthesize_x2, d=latent_dim[2], scale=.95,
scatter=False, alpha=.7, c='k', fname='{}/x2'.format(results_dir))
print('Plotting synthesized assemblies ...')
assemblies = model.synthesize_assemblies(25)
assemblies_list = []
for i in range(len(n_points)):
assemblies_list.append(assemblies[:25, n_points_c[i]:n_points_c[i+1]])
plot_samples(None, assemblies_list, scatter=False, alpha=.7, c='k', fname='{}/assemblies'.format(results_dir))
n_runs = 10
feasibility_func = import_module('{}.feasibility'.format(args.data)).check_feasibility
prc_mean, prc_err = ci_prc(n_runs, model.synthesize_assemblies, feasibility_func, n_points)
print('Precision for assembly: %.3f +/- %.3f' % (prc_mean, prc_err))
mmd_mean, mmd_err = ci_mmd(n_runs, model.synthesize_assemblies, X_test)
rdiv_mean, rdiv_err = ci_rdiv(n_runs, X_test, model.synthesize_assemblies)
if args.data == 'SCC':
basis = 'polar'
else:
basis = 'cartesian'
cons0_mean, cons0_err = ci_cons(n_runs, model.synthesize_x0, latent_dim[0], bounds, basis='cartesian')
cons1_mean, cons1_err = ci_cons(n_runs, model.synthesize_x1, latent_dim[1], bounds, basis=basis)
cons2_mean, cons2_err = ci_cons(n_runs, model.synthesize_x2, latent_dim[2], bounds, basis=basis)
res = {'CSS': [prc_mean, prc_err],
'MMD': [mmd_mean, mmd_err],
'R-Div': [rdiv_mean, rdiv_err],
'LSC_A': [cons0_mean, cons0_err],
'LSC_B': [cons1_mean, cons1_err],
'LSC_C': [cons2_mean, cons2_err]}
json.dump(res, open('{}/results.json'.format(results_dir), 'w'))
results_mesg_0 = 'Precision for assembly: %.3f +/- %.3f' % (prc_mean, prc_err)
results_mesg_1 = 'Maximum mean discrepancy for assembly: %.4f +/- %.4f' % (mmd_mean, mmd_err)
results_mesg_2 = 'Relative diversity for assembly: %.3f +/- %.3f' % (rdiv_mean, rdiv_err)
results_mesg_3 = 'Consistency for latent space 0: %.3f +/- %.3f' % (cons0_mean, cons0_err)
results_mesg_4 = 'Consistency for latent space 1: %.3f +/- %.3f' % (cons1_mean, cons1_err)
results_mesg_5 = 'Consistency for latent space 2: %.3f +/- %.3f' % (cons2_mean, cons2_err)
results_file = open('{}/results.txt'.format(results_dir), 'w')
print(results_mesg_0)
results_file.write('%s\n' % results_mesg_0)
print(results_mesg_1)
results_file.write('%s\n' % results_mesg_1)
print(results_mesg_2)
results_file.write('%s\n' % results_mesg_2)
print(results_mesg_3)
results_file.write('%s\n' % results_mesg_3)
print(results_mesg_4)
results_file.write('%s\n' % results_mesg_4)
print(results_mesg_5)
results_file.write('%s\n' % results_mesg_5)
results_file.close()