-
Notifications
You must be signed in to change notification settings - Fork 2
/
cnnnas.py
184 lines (164 loc) · 8.35 KB
/
cnnnas.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
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 22 14:41:33 2022
@author: AnshumaanChauhan
"""
import CNNCONSTANTS
import pickle
import keras.backend as K
from tensorflow.keras.utils import to_categorical
from keras.preprocessing.sequence import pad_sequences
import tensorflow as tf
from NASutils import *
from CNNCONSTANTS import *
from DQNController import DQNAgent
from CNNGenerator import CNNGenerator
class CNNNAS(DQNAgent):
def __init__(self, x, y):
self.x = x
self.y = y
self.target_classes = TARGET_CLASSES
self.controller_sampling_epochs = CONTROLLER_SAMPLING_EPOCHS
self.samples_per_controller_epoch = SAMPLES_PER_CONTROLLER_EPOCH
self.controller_train_epochs = CONTROLLER_TRAINING_EPOCHS
self.architecture_train_epochs = ARCHITECTURE_TRAINING_EPOCHS
self.controller_loss_alpha = CONTROLLER_LOSS_ALPHA
self.data = []
self.nas_data_log = 'LOGS2/nas_data.pkl'
clean_log()
super().__init__()
self.CNNGenerator = CNNGenerator()
self.controller_batch_size = len(self.data)
self.controller_input_shape = (1, MAX_ARCHITECTURE_LENGTH - 1)
if self.use_predictor:
self.controller_model = self.create_hybrid_model(self.controller_input_shape, self.controller_batch_size)
self.target_model= self.create_hybrid_model(self.controller_input_shape, self.controller_batch_size)
else:
self.controller_model = self.create_control_model(self.controller_input_shape, self.controller_batch_size)
self.target_model= self.create_control_model(self.controller_input_shape, self.controller_batch_size)
def create_architecture(self, sequence):
if self.target_classes == 2:
self.CNNGenerator.loss_func = 'binary_crossentropy'
model = self.CNNGenerator.create_model(sequence, np.shape(self.x[0]))
#models = self.CNNGenerator.compile_model(model)
if model==None:
return model
models = self.CNNGenerator.compile_model(model)
return models
def train_architecture(self, model):
x, y = unison_shuffled_copies(self.x, self.y)
#Check how to train models on different number of epochs
history_of_models = self.CNNGenerator.train_model(model, x, y, self.architecture_train_epochs)
return history_of_models
def append_model_metrics(self, sequence, history, pred_accuracy=None):
if len(history.history['val_accuracy']) == 1:
if pred_accuracy:
self.data.append([sequence,
history.history['val_accuracy'][0],
pred_accuracy])
print('predicted accuracy: ',pred_accuracy)
else:
self.data.append([sequence,
history.history['val_accuracy'][0]])
print('validation accuracy: ', history.history['val_accuracy'][0])
else:
val_acc = np.ma.average(history.history['val_accuracy'],
weights=np.arange(1, len(history.history['val_accuracy']) + 1),
axis=-1)
if pred_accuracy:
self.data.append([sequence,
val_acc,
pred_accuracy])
else:
self.data.append([sequence,
val_acc])
print('validation accuracy: ', val_acc)
def prepare_controller_data(self, sequences):
#Adds 0 at the end if the sequence length is shorter than Max length architecture
controller_sequences = pad_sequences(sequences, maxlen=self.max_len, padding='post')
#Have all the layers except the final softmax layer
xc = controller_sequences[:, :-1].reshape(len(controller_sequences), 1, self.max_len - 1)
#Final layer
yc = to_categorical(controller_sequences[:, -1], self.controller_classes)
#Getting val accuracy of the sequences
val_acc_target = [item[1] for item in self.data]
return xc, yc, val_acc_target
def get_discounted_reward(self, rewards):
discounted_r = np.zeros_like(rewards, dtype=np.float32)
for t in range(len(rewards)):
running_add = 0.
exp = 0.
for r in rewards[t:]:
running_add += self.controller_loss_alpha**exp * r
exp += 1
discounted_r[t] = running_add
discounted_r = (discounted_r - discounted_r.mean()) / discounted_r.std()
return discounted_r
def custom_loss(self, target, output):
baseline = 0.5
reward = np.array([item[1] - baseline for item in self.data[-self.samples_per_controller_epoch:]]).reshape(
self.samples_per_controller_epoch, 1)
discounted_reward = self.get_discounted_reward(reward)
loss = - K.log(output) * discounted_reward[:, None]
return loss
def train_controller(self, model, x, y, val_accuracy, pred_accuracy=None):
if self.use_predictor:
self.train_hybrid_model(model,
self.target_model,
x,
y,
val_accuracy,
pred_accuracy,
self.custom_loss,
len(self.data),
self.controller_train_epochs)
else:
self.train_control_model(model,
self.target_model,
x,
y,
val_accuracy,
self.custom_loss,
len(self.data),
self.controller_train_epochs)
def search(self):
for controller_epoch in range(self.controller_sampling_epochs):
print('------------------------------------------------------------------')
print(' CONTROLLER EPOCH: {}'.format(controller_epoch))
print('------------------------------------------------------------------')
sequences = self.sample_architecture_sequences(self.controller_model, self.samples_per_controller_epoch)
if self.use_predictor:
pred_accuracies = self.get_predicted_accuracies_hybrid_model(self.controller_model, sequences)
#print("At start print acc: ",pred_accuracies)
for i, sequence in enumerate(sequences):
print('Architecture: ', self.decode_sequence(sequence))
model = self.create_architecture(sequence)
if model==None:
if self.use_predictor:
self.data.append([sequence, -10.0, pred_accuracies[i]])
print('validation accuracy: ', -10.0)
else:
self.data.append([sequence, -10.0])
print('validation accuracy: ', -10.0)
continue
history = self.train_architecture(model)
if self.use_predictor:
self.append_model_metrics(sequence, history, pred_accuracies[i])
else:
self.append_model_metrics(sequence, history)
print('------------------------------------------------------')
xc, yc, val_acc_target = self.prepare_controller_data(sequences)
if self.use_predictor:
self.train_controller(self.controller_model,
xc,
yc,
val_acc_target[-self.samples_per_controller_epoch:], pred_accuracies)
else:
self.train_controller(self.controller_model,
xc,
yc,
val_acc_target[-self.samples_per_controller_epoch:])
with open(self.nas_data_log, 'wb') as f:
pickle.dump(self.data, f)
log_event()
return self.data