neural_architecture_search   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 94
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 66
dl 0
loc 94
rs 10
c 0
b 0
f 0
wmc 4

4 Functions

Rating   Name   Duplication   Size   Complexity  
A conv1() 0 5 1
A conv3() 0 2 1
A conv2() 0 4 1
A cnn() 0 36 1
1
import numpy as np
2
from keras.models import Sequential
3
from keras.layers import (
4
    Dense,
5
    Conv2D,
6
    MaxPooling2D,
7
    Flatten,
8
    Activation,
9
    Dropout,
10
)
11
from keras.datasets import cifar10
12
from keras.utils import to_categorical
13
14
from hyperactive import Hyperactive
15
16
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
17
18
y_train = to_categorical(y_train, 10)
19
y_test = to_categorical(y_test, 10)
20
21
# to make the example quick
22
X_train = X_train[0:1000]
23
y_train = y_train[0:1000]
24
25
X_test = X_test[0:1000]
26
y_test = y_test[0:1000]
27
28
29
def conv1(nn):
30
    nn.add(Conv2D(32, (3, 3)))
31
    nn.add(Activation("relu"))
32
    nn.add(MaxPooling2D(pool_size=(2, 2)))
33
    return nn
34
35
36
def conv2(nn):
37
    nn.add(Conv2D(32, (3, 3)))
38
    nn.add(Activation("relu"))
39
    return nn
40
41
42
def conv3(nn):
43
    return nn
44
45
46
def cnn(opt):
47
    nn = Sequential()
48
    nn.add(
49
        Conv2D(
50
            opt["filters.0"],
51
            (3, 3),
52
            padding="same",
53
            input_shape=X_train.shape[1:],
54
        )
55
    )
56
    nn.add(Activation("relu"))
57
    nn.add(Conv2D(opt["filters.0"], (3, 3)))
58
    nn.add(Activation("relu"))
59
    nn.add(MaxPooling2D(pool_size=(2, 2)))
60
    nn.add(Dropout(0.25))
61
62
    nn.add(Conv2D(opt["filters.0"], (3, 3), padding="same"))
63
    nn.add(Activation("relu"))
64
    nn = opt["conv_layer.0"](nn)
65
    nn.add(Dropout(0.25))
66
67
    nn.add(Flatten())
68
    nn.add(Dense(opt["neurons.0"]))
69
    nn.add(Activation("relu"))
70
    nn.add(Dropout(0.5))
71
    nn.add(Dense(10))
72
    nn.add(Activation("softmax"))
73
74
    nn.compile(
75
        optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"]
76
    )
77
    nn.fit(X_train, y_train, epochs=5, batch_size=256)
78
79
    _, score = nn.evaluate(x=X_test, y=y_test)
80
81
    return score
82
83
84
search_space = {
85
    "conv_layer.0": [conv1, conv2, conv3],
86
    "filters.0": [16, 32, 64, 128],
87
    "neurons.0": list(range(100, 1000, 100)),
88
}
89
90
91
hyper = Hyperactive()
92
hyper.add_search(cnn, search_space, n_iter=5)
93
hyper.run()
94