-
Notifications
You must be signed in to change notification settings - Fork 144
/
train_xor.py
196 lines (176 loc) · 4.99 KB
/
train_xor.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
import os
import subprocess
from irregular_sampled_datasets import XORData
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import tensorflow as tf
import numpy as np
import argparse
from tf_cfc import CfcCell, MixedCfcCell, LTCCell
import time
import sys
def eval(config, index_arg, verbose=0):
data = XORData(time_major=False, event_based=True, pad_size=32)
if config.get("use_ltc"):
cell = LTCCell(units=config["size"], ode_unfolds=6)
elif config["use_mixed"]:
cell = MixedCfcCell(units=config["size"], hparams=config)
else:
cell = CfcCell(units=config["size"], hparams=config)
pixel_input = tf.keras.Input(shape=(data.pad_size, 1), name="input")
time_input = tf.keras.Input(shape=(data.pad_size, 1), name="time")
mask_input = tf.keras.Input(shape=(data.pad_size,), dtype=tf.bool, name="mask")
rnn = tf.keras.layers.RNN(cell, time_major=False, return_sequences=False)
dense_layer = tf.keras.layers.Dense(1)
output_states = rnn((pixel_input, time_input), mask=mask_input)
y = dense_layer(output_states)
model = tf.keras.Model(inputs=[pixel_input, time_input, mask_input], outputs=[y])
base_lr = config["base_lr"]
decay_lr = config["decay_lr"]
# end_lr = config["end_lr"]
train_steps = data.train_events.shape[0] // config["batch_size"]
learning_rate_fn = tf.keras.optimizers.schedules.ExponentialDecay(
base_lr, train_steps, decay_lr
)
opt = (
tf.keras.optimizers.Adam
if config["optimizer"] == "adam"
else tf.keras.optimizers.RMSprop
)
optimizer = opt(learning_rate_fn, clipnorm=config["clipnorm"])
model.compile(
optimizer=optimizer,
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
metrics=[tf.keras.metrics.BinaryAccuracy(threshold=0.0)],
)
# model.summary()
# Fit model
hist = model.fit(
x=(data.train_events, data.train_elapsed, data.train_mask),
y=data.train_y,
batch_size=config["batch_size"],
epochs=config["epochs"],
verbose=0,
)
# Evaluate model after training
_, best_test_acc = model.evaluate(
x=(data.test_events, data.test_elapsed, data.test_mask),
y=data.test_y,
verbose=2,
)
return best_test_acc
# Accuracy: 99.72 +- 0.08
BEST_MIXED = {
"clipnorm": 10,
"optimizer": "rmsprop",
"batch_size": 128,
"size": 64,
"epochs": 200,
"base_lr": 0.005,
"decay_lr": 0.95,
"backbone_activation": "relu",
"backbone_dr": 0.0,
"forget_bias": 0.6,
"backbone_units": 128,
"backbone_layers": 1,
"weight_decay": 2e-06,
"use_mixed": True,
}
# Accuracy: 99.42% +- 0.42
# DENSE: 97.34\% $\pm$ 1.85
BEST_DEFAULT = {
"clipnorm": 1,
"optimizer": "rmsprop",
"batch_size": 128,
"size": 192,
"epochs": 200,
"base_lr": 0.05,
"decay_lr": 0.95,
"backbone_activation": "relu",
"backbone_dr": 0.0,
"forget_bias": 1.2,
"backbone_units": 128,
"backbone_layers": 1,
"weight_decay": 3e-06,
"use_mixed": False,
}
# 96.29% +- 1.61
BEST_NO_GATE = {
"clipnorm": 10,
"optimizer": "rmsprop",
"batch_size": 128,
"size": 128,
"epochs": 200,
"base_lr": 0.005,
"decay_lr": 0.95,
"backbone_activation": "silu",
"backbone_dr": 0.3,
"forget_bias": 4.7,
"backbone_units": 192,
"backbone_layers": 1,
"weight_decay": 5e-06,
"use_mixed": False,
"no_gate": True,
}
# 85.42\% $\pm$ 2.84
BEST_MINIMAL = {
"clipnorm": 5,
"optimizer": "adam",
"batch_size": 256,
"size": 64,
"epochs": 200,
"base_lr": 0.005,
"decay_lr": 0.9,
"backbone_activation": "silu",
"backbone_dr": 0.0,
"forget_bias": 1.2,
"backbone_units": 64,
"backbone_layers": 1,
"weight_decay": 3e-05,
"use_mixed": False,
"no_gate": False,
"minimal": True,
}
# 49.11\% $\pm$ 0.00
LTC_TEST = {
"clipnorm": 5,
"optimizer": "adam",
"batch_size": 256,
"size": 64,
"epochs": 200,
"base_lr": 0.005,
"decay_lr": 0.9,
"backbone_activation": "silu",
"backbone_dr": 0.0,
"forget_bias": 1.2,
"backbone_units": 64,
"backbone_layers": 1,
"weight_decay": 3e-05,
"use_mixed": False,
"no_gate": False,
"minimal": False,
"use_ltc": True,
}
def score(config):
acc = []
for i in range(3):
acc.append(100 * eval(config, i))
print(
f"Accuracy [n={len(acc)}]: {np.mean(acc):0.2f}\\% $\\pm$ {np.std(acc):0.2f}"
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--use_mixed", action="store_true")
parser.add_argument("--no_gate", action="store_true")
parser.add_argument("--minimal", action="store_true")
parser.add_argument("--use_ltc", action="store_true")
args = parser.parse_args()
if args.minimal:
score(BEST_MINIMAL)
elif args.no_gate:
score(BEST_NO_GATE)
elif args.use_ltc:
score(LTC_TEST)
elif args.use_mixed:
score(BEST_MIXED)
else:
score(BEST_DEFAULT)