keras_example.cnn()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 36
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 29
nop 1
dl 0
loc 36
rs 9.184
c 0
b 0
f 0
1
import tensorflow as tf
2
from keras.models import Sequential
3
from keras.layers import (
4
    Dense,
5
    Conv2D,
6
    MaxPooling2D,
7
    Flatten,
8
    Dropout,
9
    Activation,
10
)
11
from keras.datasets import cifar10
12
from keras.utils import to_categorical
13
14
from hyperactive import Hyperactive
15
16
17
config = tf.compat.v1.ConfigProto()
18
config.gpu_options.allow_growth = True
19
config.log_device_placement = True
20
21
sess = tf.compat.v1.Session(config=config)
22
tf.compat.v1.keras.backend.set_session(sess)
23
24
25
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
26
27
y_train = to_categorical(y_train, 10)
28
y_test = to_categorical(y_test, 10)
29
30
31
# to make the example quick
32
X_train = X_train[0:1000]
33
y_train = y_train[0:1000]
34
35
36
X_test = X_test[0:1000]
37
y_test = y_test[0:1000]
38
39
40
def cnn(opt):
41
    nn = Sequential()
42
    nn.add(
43
        Conv2D(
44
            opt["filter.0"],
45
            (3, 3),
46
            padding="same",
47
            input_shape=X_train.shape[1:],
48
        )
49
    )
50
    nn.add(Activation("relu"))
51
    nn.add(Conv2D(opt["filter.0"], (3, 3)))
52
    nn.add(Activation("relu"))
53
    nn.add(MaxPooling2D(pool_size=(2, 2)))
54
    nn.add(Dropout(0.25))
55
56
    nn.add(Conv2D(opt["filter.0"], (3, 3), padding="same"))
57
    nn.add(Activation("relu"))
58
    nn.add(Conv2D(opt["filter.0"], (3, 3)))
59
    nn.add(Activation("relu"))
60
    nn.add(MaxPooling2D(pool_size=(2, 2)))
61
    nn.add(Dropout(0.25))
62
63
    nn.add(Flatten())
64
    nn.add(Dense(opt["layer.0"]))
65
    nn.add(Activation("relu"))
66
    nn.add(Dropout(0.5))
67
    nn.add(Dense(10))
68
    nn.add(Activation("softmax"))
69
70
    nn.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])
71
    nn.fit(X_train, y_train, epochs=20, batch_size=512)
72
73
    _, score = nn.evaluate(x=X_test, y=y_test)
74
75
    return score
76
77
78
search_space = {
79
    "filter.0": [16, 32, 64, 128],
80
    "layer.0": list(range(100, 1000, 100)),
81
}
82
83
84
hyper = Hyperactive()
85
hyper.add_search(cnn, search_space, n_iter=5)
86
hyper.run()
87