-
Notifications
You must be signed in to change notification settings - Fork 12
/
gradual_shift_better.py
298 lines (251 loc) · 12.8 KB
/
gradual_shift_better.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import utils
import models
import datasets
import numpy as np
import tensorflow as tf
from tensorflow.keras import metrics
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
import pickle
def compile_model(model, loss='ce'):
loss = models.get_loss(loss, model.output_shape[1])
model.compile(optimizer='adam',
loss=[loss],
metrics=[metrics.sparse_categorical_accuracy])
def train_model_source(model, split_data, epochs=1000):
model.fit(split_data.src_train_x, split_data.src_train_y, epochs=epochs, verbose=False)
print("Source accuracy:")
_, src_acc = model.evaluate(split_data.src_val_x, split_data.src_val_y)
print("Target accuracy:")
_, target_acc = model.evaluate(split_data.target_val_x, split_data.target_val_y)
return src_acc, target_acc
def run_experiment(
dataset_func, n_classes, input_shape, save_file, model_func=models.simple_softmax_conv_model,
interval=2000, epochs=10, loss='ce', soft=False, conf_q=0.1, num_runs=20, num_repeats=None):
(src_tr_x, src_tr_y, src_val_x, src_val_y, inter_x, inter_y, dir_inter_x, dir_inter_y,
trg_val_x, trg_val_y, trg_test_x, trg_test_y) = dataset_func()
if soft:
src_tr_y = to_categorical(src_tr_y)
src_val_y = to_categorical(src_val_y)
trg_eval_y = to_categorical(trg_eval_y)
dir_inter_y = to_categorical(dir_inter_y)
inter_y = to_categorical(inter_y)
trg_test_y = to_categorical(trg_test_y)
if num_repeats is None:
num_repeats = int(inter_x.shape[0] / interval)
def new_model():
model = model_func(n_classes, input_shape=input_shape)
compile_model(model, loss)
return model
def student_func(teacher):
return teacher
def run(seed):
utils.rand_seed(seed)
trg_eval_x = trg_val_x
trg_eval_y = trg_val_y
# Train source model.
source_model = new_model()
source_model.fit(src_tr_x, src_tr_y, epochs=epochs, verbose=False)
_, src_acc = source_model.evaluate(src_val_x, src_val_y)
_, target_acc = source_model.evaluate(trg_eval_x, trg_eval_y)
# Gradual self-training.
print("\n\n Gradual self-training:")
teacher = new_model()
teacher.set_weights(source_model.get_weights())
gradual_accuracies, student = utils.gradual_self_train(
student_func, teacher, inter_x, inter_y, interval, epochs=epochs, soft=soft,
confidence_q=conf_q)
_, acc = student.evaluate(trg_eval_x, trg_eval_y)
gradual_accuracies.append(acc)
# Train to target.
print("\n\n Direct boostrap to target:")
teacher = new_model()
teacher.set_weights(source_model.get_weights())
target_accuracies, _ = utils.self_train(
student_func, teacher, dir_inter_x, epochs=epochs, target_x=trg_eval_x,
target_y=trg_eval_y, repeats=num_repeats, soft=soft, confidence_q=conf_q)
print("\n\n Direct boostrap to all unsup data:")
teacher = new_model()
teacher.set_weights(source_model.get_weights())
all_accuracies, _ = utils.self_train(
student_func, teacher, inter_x, epochs=epochs, target_x=trg_eval_x,
target_y=trg_eval_y, repeats=num_repeats, soft=soft, confidence_q=conf_q)
return src_acc, target_acc, gradual_accuracies, target_accuracies, all_accuracies
results = []
for i in range(num_runs):
results.append(run(i))
print('Saving to ' + save_file)
pickle.dump(results, open(save_file, "wb"))
def experiment_results(save_name):
results = pickle.load(open(save_name, "rb"))
src_accs, target_accs = [], []
final_graduals, final_targets, final_alls = [], [], []
best_targets, best_alls = [], []
for src_acc, target_acc, gradual_accuracies, target_accuracies, all_accuracies in results:
src_accs.append(100 * src_acc)
target_accs.append(100 * target_acc)
final_graduals.append(100 * gradual_accuracies[-1])
final_targets.append(100 * target_accuracies[-1])
final_alls.append(100 * all_accuracies[-1])
best_targets.append(100 * np.max(target_accuracies))
best_alls.append(100 * np.max(all_accuracies))
num_runs = len(src_accs)
mult = 1.645 # For 90% confidence intervals
print("\nNon-adaptive accuracy on source (%): ", np.mean(src_accs),
mult * np.std(src_accs) / np.sqrt(num_runs))
print("Non-adaptive accuracy on target (%): ", np.mean(target_accs),
mult * np.std(target_accs) / np.sqrt(num_runs))
print("Gradual self-train accuracy (%): ", np.mean(final_graduals),
mult * np.std(final_graduals) / np.sqrt(num_runs))
print("Target self-train accuracy (%): ", np.mean(final_targets),
mult * np.std(final_targets) / np.sqrt(num_runs))
print("All self-train accuracy (%): ", np.mean(final_alls),
mult * np.std(final_alls) / np.sqrt(num_runs))
print("Best of Target self-train accuracies (%): ", np.mean(best_targets),
mult * np.std(best_targets) / np.sqrt(num_runs))
print("Best of All self-train accuracies (%): ", np.mean(best_alls),
mult * np.std(best_alls) / np.sqrt(num_runs))
def rotated_mnist_60_conv_experiment():
run_experiment(
dataset_func=datasets.rotated_mnist_60_data_func, n_classes=10, input_shape=(28, 28, 1),
save_file='saved_files/rot_mnist_60_conv.dat',
model_func=models.simple_softmax_conv_model, interval=2000, epochs=10, loss='ce',
soft=False, conf_q=0.1, num_runs=5)
def portraits_conv_experiment():
run_experiment(
dataset_func=datasets.portraits_data_func, n_classes=2, input_shape=(32, 32, 1),
save_file='saved_files/portraits.dat',
model_func=models.simple_softmax_conv_model, interval=2000, epochs=20, loss='ce',
soft=False, conf_q=0.1, num_runs=5)
def gaussian_linear_experiment():
d = 100
run_experiment(
dataset_func=lambda: datasets.gaussian_data_func(d), n_classes=2, input_shape=(d,),
save_file='saved_files/gaussian.dat',
model_func=models.linear_softmax_model, interval=500, epochs=100, loss='ce',
soft=False, conf_q=0.1, num_runs=5)
# Ablations below.
def rotated_mnist_60_conv_experiment_noconf():
run_experiment(
dataset_func=datasets.rotated_mnist_60_data_func, n_classes=10, input_shape=(28, 28, 1),
save_file='saved_files/rot_mnist_60_conv_noconf.dat',
model_func=models.simple_softmax_conv_model, interval=2000, epochs=10, loss='ce',
soft=False, conf_q=0.0, num_runs=5)
def portraits_conv_experiment_noconf():
run_experiment(
dataset_func=datasets.portraits_data_func, n_classes=2, input_shape=(32, 32, 1),
save_file='saved_files/portraits_noconf.dat',
model_func=models.simple_softmax_conv_model, interval=2000, epochs=20, loss='ce',
soft=False, conf_q=0.0, num_runs=5)
def gaussian_linear_experiment_noconf():
d = 100
run_experiment(
dataset_func=lambda: datasets.gaussian_data_func(d), n_classes=2, input_shape=(d,),
save_file='saved_files/gaussian_noconf.dat',
model_func=models.linear_softmax_model, interval=500, epochs=100, loss='ce',
soft=False, conf_q=0.0, num_runs=5)
def portraits_64_conv_experiment():
run_experiment(
dataset_func=datasets.portraits_64_data_func, n_classes=2, input_shape=(64, 64, 1),
save_file='saved_files/portraits_64.dat',
model_func=models.simple_softmax_conv_model, interval=2000, epochs=20, loss='ce',
soft=False, conf_q=0.1, num_runs=5)
def dialing_ratios_mnist_experiment():
run_experiment(
dataset_func=datasets.rotated_mnist_60_dialing_ratios_data_func,
n_classes=10, input_shape=(28, 28, 1),
save_file='saved_files/dialing_rot_mnist_60_conv.dat',
model_func=models.simple_softmax_conv_model, interval=2000, epochs=10, loss='ce',
soft=False, conf_q=0.1, num_runs=5)
def portraits_conv_experiment_more():
run_experiment(
dataset_func=datasets.portraits_data_func_more, n_classes=2, input_shape=(32, 32, 1),
save_file='saved_files/portraits_more.dat',
model_func=models.simple_softmax_conv_model, interval=2000, epochs=20, loss='ce',
soft=False, conf_q=0.1, num_runs=5)
def rotated_mnist_60_conv_experiment_smaller_interval():
run_experiment(
dataset_func=datasets.rotated_mnist_60_data_func, n_classes=10, input_shape=(28, 28, 1),
save_file='saved_files/rot_mnist_60_conv_smaller_interval.dat',
model_func=models.simple_softmax_conv_model, interval=1000, epochs=10, loss='ce',
soft=False, conf_q=0.1, num_runs=5, num_repeats=7)
def portraits_conv_experiment_smaller_interval():
run_experiment(
dataset_func=datasets.portraits_data_func, n_classes=2, input_shape=(32, 32, 1),
save_file='saved_files/portraits_smaller_interval.dat',
model_func=models.simple_softmax_conv_model, interval=1000, epochs=20, loss='ce',
soft=False, conf_q=0.1, num_runs=5, num_repeats=7)
def gaussian_linear_experiment_smaller_interval():
d = 100
run_experiment(
dataset_func=lambda: datasets.gaussian_data_func(d), n_classes=2, input_shape=(d,),
save_file='saved_files/gaussian_smaller_interval.dat',
model_func=models.linear_softmax_model, interval=250, epochs=100, loss='ce',
soft=False, conf_q=0.1, num_runs=5, num_repeats=7)
def rotated_mnist_60_conv_experiment_more_epochs():
run_experiment(
dataset_func=datasets.rotated_mnist_60_data_func, n_classes=10, input_shape=(28, 28, 1),
save_file='saved_files/rot_mnist_60_conv_more_epochs.dat',
model_func=models.simple_softmax_conv_model, interval=2000, epochs=15, loss='ce',
soft=False, conf_q=0.1, num_runs=5)
def portraits_conv_experiment_more_epochs():
run_experiment(
dataset_func=datasets.portraits_data_func, n_classes=2, input_shape=(32, 32, 1),
save_file='saved_files/portraits_more_epochs.dat',
model_func=models.simple_softmax_conv_model, interval=2000, epochs=30, loss='ce',
soft=False, conf_q=0.1, num_runs=5)
def gaussian_linear_experiment_more_epochs():
d = 100
run_experiment(
dataset_func=lambda: datasets.gaussian_data_func(d), n_classes=2, input_shape=(d,),
save_file='saved_files/gaussian_more_epochs.dat',
model_func=models.linear_softmax_model, interval=500, epochs=150, loss='ce',
soft=False, conf_q=0.1, num_runs=5)
if __name__ == "__main__":
# Main paper experiments.
portraits_conv_experiment()
print("Portraits conv experiment")
experiment_results('saved_files/portraits.dat')
rotated_mnist_60_conv_experiment()
print("Rot MNIST conv experiment")
experiment_results('saved_files/rot_mnist_60_conv.dat')
gaussian_linear_experiment()
print("Gaussian linear experiment")
experiment_results('saved_files/gaussian.dat')
print("Dialing MNIST ratios conv experiment")
dialing_ratios_mnist_experiment()
experiment_results('saved_files/dialing_rot_mnist_60_conv.dat')
# Without confidence thresholding.
portraits_conv_experiment_noconf()
print("Portraits conv experiment no confidence thresholding")
experiment_results('saved_files/portraits_noconf.dat')
rotated_mnist_60_conv_experiment_noconf()
print("Rot MNIST conv experiment no confidence thresholding")
experiment_results('saved_files/rot_mnist_60_conv_noconf.dat')
gaussian_linear_experiment_noconf()
print("Gaussian linear experiment no confidence thresholding")
experiment_results('saved_files/gaussian_noconf.dat')
# Try predicting for next set of data points on portraits.
portraits_conv_experiment_more()
print("Portraits next datapoints conv experiment")
experiment_results('saved_files/portraits_more.dat')
# Try smaller window sizes.
portraits_conv_experiment_smaller_interval()
print("Portraits conv experiment smaller window")
experiment_results('saved_files/portraits_smaller_interval.dat')
rotated_mnist_60_conv_experiment_smaller_interval()
print("Rot MNIST conv experiment smaller window")
experiment_results('saved_files/rot_mnist_60_conv_smaller_interval.dat')
gaussian_linear_experiment_smaller_interval()
print("Gaussian linear experiment smaller window")
experiment_results('saved_files/gaussian_smaller_interval.dat')
# Try training more epochs.
portraits_conv_experiment_more_epochs()
print("Portraits conv experiment train longer")
experiment_results('saved_files/portraits_more_epochs.dat')
rotated_mnist_60_conv_experiment_more_epochs()
print("Rot MNIST conv experiment train longer")
experiment_results('saved_files/rot_mnist_60_conv_more_epochs.dat')
gaussian_linear_experiment_more_epochs()
print("Gaussian linear experiment train longer")
experiment_results('saved_files/gaussian_more_epochs.dat')