-
Notifications
You must be signed in to change notification settings - Fork 42
/
keras_example.py
86 lines (64 loc) · 1.88 KB
/
keras_example.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
import tensorflow as tf
from keras.models import Sequential
from keras.layers import (
Dense,
Conv2D,
MaxPooling2D,
Flatten,
Dropout,
Activation,
)
from keras.datasets import cifar10
from keras.utils import to_categorical
from hyperactive import Hyperactive
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
config.log_device_placement = True
sess = tf.compat.v1.Session(config=config)
tf.compat.v1.keras.backend.set_session(sess)
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
# to make the example quick
X_train = X_train[0:1000]
y_train = y_train[0:1000]
X_test = X_test[0:1000]
y_test = y_test[0:1000]
def cnn(opt):
nn = Sequential()
nn.add(
Conv2D(
opt["filter.0"],
(3, 3),
padding="same",
input_shape=X_train.shape[1:],
)
)
nn.add(Activation("relu"))
nn.add(Conv2D(opt["filter.0"], (3, 3)))
nn.add(Activation("relu"))
nn.add(MaxPooling2D(pool_size=(2, 2)))
nn.add(Dropout(0.25))
nn.add(Conv2D(opt["filter.0"], (3, 3), padding="same"))
nn.add(Activation("relu"))
nn.add(Conv2D(opt["filter.0"], (3, 3)))
nn.add(Activation("relu"))
nn.add(MaxPooling2D(pool_size=(2, 2)))
nn.add(Dropout(0.25))
nn.add(Flatten())
nn.add(Dense(opt["layer.0"]))
nn.add(Activation("relu"))
nn.add(Dropout(0.5))
nn.add(Dense(10))
nn.add(Activation("softmax"))
nn.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])
nn.fit(X_train, y_train, epochs=20, batch_size=512)
_, score = nn.evaluate(x=X_test, y=y_test)
return score
search_space = {
"filter.0": [16, 32, 64, 128],
"layer.0": list(range(100, 1000, 100)),
}
hyper = Hyperactive()
hyper.add_search(cnn, search_space, n_iter=5)
hyper.run()