-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathcontroller.py
184 lines (167 loc) · 7.72 KB
/
controller.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
import os
import numpy as np
np.set_printoptions(precision=10)
from keras import optimizers
from keras.layers import Dense, LSTM
from keras.models import Model
from keras.engine.input_layer import Input
import tensorflow as tf
from tensorflow.keras.utils import to_categorical
from keras.preprocessing.sequence import pad_sequences
from mlp_generator import MLPSearchSpace
from CONSTANTS import *
class Controller(MLPSearchSpace):
def __init__(self):
self.max_len = MAX_ARCHITECTURE_LENGTH
self.controller_lstm_dim = CONTROLLER_LSTM_DIM
self.controller_optimizer = CONTROLLER_OPTIMIZER
self.controller_lr = CONTROLLER_LEARNING_RATE
self.controller_decay = CONTROLLER_DECAY
self.controller_momentum = CONTROLLER_MOMENTUM
self.use_predictor = CONTROLLER_USE_PREDICTOR
self.controller_weights = 'LOGS/controller_weights.h5'
self.seq_data = []
super().__init__(TARGET_CLASSES)
self.controller_classes = len(self.vocab) + 1
self.eps = 0.5
def sample_architecture_sequences(self, model, number_of_samples):
final_layer_id = len(self.vocab)
dropout_id = final_layer_id - 1
vocab_idx = [0] + list(self.vocab.keys())
samples = []
print("GENERATING ARCHITECTURE SAMPLES...")
print('------------------------------------------------------')
while len(samples) < number_of_samples:
seed = [0]
# initial with 'start' token
sequence = pad_sequences([seed],
maxlen=self.max_len,
padding='post',
value=0)
sequence = sequence.reshape(1, self.max_len, 1)
sequence = to_categorical(sequence, self.controller_classes)
if self.use_predictor:
(probab, _) = model.predict(sequence)
else:
probab = model.predict(sequence)
probab = probab[0]
while len(seed) < self.max_len:
next = np.random.choice(vocab_idx, size=1,
p=probab[len(seed)])[0]
if next == 0:
continue
if next == dropout_id and len(seed) == 1:
continue
if next == final_layer_id and len(seed) == 1:
continue
if next == final_layer_id:
seed.append(next)
break
if not next == 1:
seed.append(next)
if len(seed) == self.max_len and seed[-1] != final_layer_id:
seed.append(final_layer_id)
# # search unexplored architecture
# # use epsilon-greedy
# p = np.random.random()
# if (seed not in self.seq_data):
# samples.append(seed[1:])
# self.seq_data.append(seed)
# elif (p < self.eps):
# samples.append(seed[1:])
samples.append(seed[1:])
for idx in range(self.max_len):
probab_percent = probab[idx] * 100.0
print(
"Controller prob {}: mean: {:.10f}, std: {:.10f}, top5:{}".
format(idx, tf.math.reduce_mean(probab_percent),
tf.math.reduce_std(probab_percent),
tf.math.top_k(probab_percent, 5).indices.numpy()))
return samples
def control_model(self, controller_input_shape, controller_batch_size):
main_input = Input(shape=controller_input_shape, name='main_input')
x = LSTM(self.controller_lstm_dim, return_sequences=True)(main_input)
main_output = Dense(self.controller_classes,
activation='softmax',
name='main_output')(x)
model = Model(inputs=[main_input], outputs=[main_output])
return model
def train_control_model(self, model, x_data, y_data, loss_func,
controller_batch_size, nb_epochs):
if self.controller_optimizer == 'sgd':
optim = optimizers.SGD(lr=self.controller_lr,
decay=self.controller_decay,
momentum=self.controller_momentum,
clipnorm=1.0)
else:
optim = getattr(optimizers, self.controller_optimizer)(
lr=self.controller_lr,
decay=self.controller_decay,
clipnorm=1.0)
model.compile(optimizer=optim, loss={'main_output': loss_func})
if os.path.exists(self.controller_weights):
model.load_weights(self.controller_weights)
print("TRAINING CONTROLLER...")
model.fit({'main_input': x_data}, {'main_output': y_data},
epochs=nb_epochs,
batch_size=controller_batch_size,
verbose=0)
model.save_weights(self.controller_weights)
def hybrid_control_model(self, controller_input_shape,
controller_batch_size):
main_input = Input(shape=controller_input_shape, name='main_input')
x = LSTM(self.controller_lstm_dim, return_sequences=True)(main_input)
predictor_output = Dense(1,
activation='sigmoid',
name='predictor_output')(x)
main_output = Dense(self.controller_classes,
activation='softmax',
name='main_output')(x)
model = Model(inputs=[main_input],
outputs=[main_output, predictor_output])
return model
def train_hybrid_model(self, model, x_data, y_data, pred_target, loss_func,
controller_batch_size, nb_epochs):
if self.controller_optimizer == 'sgd':
optim = optimizers.SGD(lr=self.controller_lr,
decay=self.controller_decay,
momentum=self.controller_momentum,
clipnorm=1.0)
else:
optim = getattr(optimizers, self.controller_optimizer)(
lr=self.controller_lr,
decay=self.controller_decay,
clipnorm=1.0)
model.compile(optimizer=optim,
loss={
'main_output': loss_func,
'predictor_output': 'mse'
},
loss_weights={
'main_output': 1,
'predictor_output': 1
})
if os.path.exists(self.controller_weights):
model.load_weights(self.controller_weights)
print("TRAINING CONTROLLER...")
model.fit({'main_input': x_data}, {
'main_output': y_data,
'predictor_output': pred_target
},
epochs=nb_epochs,
batch_size=controller_batch_size,
verbose=0)
model.save_weights(self.controller_weights)
def get_predicted_accuracies_hybrid_model(self, model, seqs):
pred_accuracies = []
for seq in seqs:
control_sequences = pad_sequences([seq],
maxlen=self.max_len + 1,
padding='pre',
value=0)
xc = control_sequences[:, :-1].reshape(len(control_sequences),
self.max_len, 1)
xc = to_categorical(xc, self.controller_classes)
_, pred_accuracy = model.predict(xc)
pred_accuracies.append(pred_accuracy[0][-1])
return pred_accuracies