-
Notifications
You must be signed in to change notification settings - Fork 4
/
cifar-10-efficientnetv2s.py
194 lines (156 loc) · 6.2 KB
/
cifar-10-efficientnetv2s.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
# Inport required packages
import tensorflow as tf
import tensorflow_hub as hub
import pandas as pd
import numpy as np
import imageio.v3 as iio
# from multiprocessing import Pool # , Process
from cerebros.simplecerebrosrandomsearch.simple_cerebros_random_search\
import SimpleCerebrosRandomSearch
import pendulum
from cerebros.units.units import DenseUnit
from cerebros.denseautomlstructuralcomponent.dense_automl_structural_component\
import zero_7_exp_decay, zero_95_exp_decay, simple_sigmoid
from ast import literal_eval
# Cerebros hyperparameters
activation = "relu"
predecessor_level_connection_affinity_factor_first = 1.78444
predecessor_level_connection_affinity_factor_main = 0.23595
max_consecutive_lateral_connections = 2
p_lateral_connection = 30.8812
num_lateral_connection_tries_per_unit = 1
learning_rate = 0.000113248
epochs = 7
batch_size = 7
maximum_levels = 3
maximum_units_per_level = 11
maximum_neurons_per_unit = 2
### Global configurables:
# Shape of images you are training with
INPUT_SHAPES = [(32, 32, 3)] # resize from ]
# Sise of images that the base embedding expects
RESIZE_TO = (384, 384, 3)
# Number of casses or output predictions
OUTPUT_SHAPES = [10]
### Read in the data set and make it useable
ciphar10_metadata = pd.read_csv("cifar10-mini/file_metadata.csv")
ciphar10_train = ciphar10_metadata.query("data_set == 'train'")
ciphar10_test = ciphar10_metadata.query("data_set == 'test'")
def make_dataset(dataset):
images = []
labels = []
for i in np.arange(ciphar10_metadata.shape[0]):
imfile = ciphar10_metadata.loc[i]['file_name']
# Debug delete
# print(f"$$$$: attempting file: {imfile}")
img = iio.imread(imfile)
images.append(np.array(img))
labels.append(int(ciphar10_metadata.loc[i]['label']))
data_tensor = tf.constant(images)
labels_tensor = tf.constant(labels)
labels_tensor_ohe = tf.one_hot(indices=labels_tensor,
depth=10)
print(f"labels_tensor_ohe shape: {labels_tensor_ohe.shape}")
print(f"data_tensor shape: {data_tensor.shape}")
return data_tensor, labels_tensor_ohe
selected_x_train, selected_y_train_ohe =\
make_dataset(ciphar10_train)
training_x = [selected_x_train]
train_labels = [selected_y_train_ohe]
selected_x_test, selected_y_test_ohe = make_dataset(ciphar10_test)
test_x = [selected_x_test]
test_labels = [selected_y_test_ohe]
#
mod_with_fc_raw = tf.keras.applications.EfficientNetV2S(
include_top=True,
weights="imagenet",
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
classifier_activation="softmax",
include_preprocessing=True,
)
# Make the deepest conv2d layer trainable, leave everything else
# as not trainable
for layer in mod_with_fc_raw.layers:
layer.trainable = False
# Last conv2d layer. This we want to train .
mod_with_fc_raw.layers[-6].trainable = True
# Create the final base model
# (remove the final Dense and BatchNormalization layers ...)
efficient_net_b_7_transferable_base_model =\
tf.keras.Model(inputs=mod_with_fc_raw.layers[0].input,
outputs=mod_with_fc_raw.layers[-3].output)
image_input_0 = tf.keras.layers.Input(shape=INPUT_SHAPES[0])
resizing = tf.keras.layers.Resizing(
height=RESIZE_TO[0],
width=RESIZE_TO[1],
interpolation='bilinear',
crop_to_aspect_ratio=False)
resized = resizing(image_input_0)
embedded = efficient_net_b_7_transferable_base_model(resized)
embedding_model = tf.keras.Model(image_input_0,
embedded)
# embedding_model.save('test')
## Final training task
TIME = pendulum.now(tz='America/New_York').__str__()[:16]\
.replace('T', '_')\
.replace(':', '_')\
.replace('-', '_')
PROJECT_NAME = f'{TIME}_cerebros_auto_ml_test'
meta_trial_number = str(int(np.random.random() * 10 ** 12))
cerebros_automl = SimpleCerebrosRandomSearch(
unit_type=DenseUnit,
input_shapes=INPUT_SHAPES,
output_shapes=OUTPUT_SHAPES,
training_data=training_x,
labels=train_labels,
validation_split=0.35,
direction='maximize',
metric_to_rank_by="val_top_1_categorical_accuracy",
minimum_levels=2,
maximum_levels=maximum_levels,
minimum_units_per_level=1,
maximum_units_per_level=maximum_units_per_level,
minimum_neurons_per_unit=1,
maximum_neurons_per_unit=maximum_neurons_per_unit,
activation=activation,
final_activation='softmax',
number_of_architecture_moities_to_try=2,
number_of_tries_per_architecture_moity=1,
minimum_skip_connection_depth=1,
maximum_skip_connection_depth=7,
predecessor_level_connection_affinity_factor_first=predecessor_level_connection_affinity_factor_first,
predecessor_level_connection_affinity_factor_first_rounding_rule='ceil',
predecessor_level_connection_affinity_factor_main=predecessor_level_connection_affinity_factor_main,
predecessor_level_connection_affinity_factor_main_rounding_rule='ceil',
predecessor_level_connection_affinity_factor_decay_main=zero_7_exp_decay,
seed=8675309,
max_consecutive_lateral_connections=max_consecutive_lateral_connections,
gate_after_n_lateral_connections=3,
gate_activation_function=simple_sigmoid,
p_lateral_connection=p_lateral_connection,
p_lateral_connection_decay=zero_95_exp_decay,
num_lateral_connection_tries_per_unit=num_lateral_connection_tries_per_unit,
learning_rate=learning_rate,
loss=tf.keras.losses.CategoricalCrossentropy(),
metrics=[tf.keras.metrics.TopKCategoricalAccuracy(
k=1, name='top_1_categorical_accuracy')
],
epochs=epochs,
project_name=f"{PROJECT_NAME}_meta_{meta_trial_number}",
# use_multiprocessing_for_multiple_neural_networks=False, # pull this param
model_graphs='model_graphs',
batch_size=batch_size,
meta_trial_number=meta_trial_number,
base_models=[embedding_model])
val_top_1_categorical_accuracy =\
cerebros_automl.run_random_search()
print(f"best val_top_1_categorical_accuracy is: {val_top_1_categorical_accuracy}")
best_model = cerebros_automl.get_best_model()
test_results = best_model.evaluate(test_x, test_labels)
print(f"test set results: {test_results}")
# test_x = [selected_x_test]
# test_labels = [selected_y_test_ohe]
# Test the best model: