-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
63 lines (52 loc) · 2.4 KB
/
train.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
import os
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
class CNN(object):
def __init__(self):
model = models.Sequential()
# 32 kernel, kernel_size: 3 * 3, input_size: 28*28*1
model.add(layers.Conv2D(
32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D(2, 2))
# input_shape: 13 * 13 * 32
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D(2, 2))
# input_shape: 5 * 5 * 64
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
# input_shape: 3 * 3 * 64
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
model.summary()
self.model = model
class DataSource(object):
def __init__(self):
# mnist datasets storage path
data_path = os.path.abspath(
os.path.dirname(__file__)) + '/data/mnist.npz'
(train_images, train_labels), (test_images,
test_labels) = datasets.mnist.load_data(path=data_path)
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))
train_images, test_images = train_images / 255.0, test_images / 255.0
self.train_images, self.test_images = train_images, test_images
self.train_labels, self.test_labels = train_labels, test_labels
class Train:
def __init__(self):
self.cnn = CNN()
self.data = DataSource()
def train(self):
check_path = 'model/cp-{epoch: 04d}.ckpt'
save_model_cb = tf.keras.callbacks.ModelCheckpoint(
check_path, save_weights_only=True, verbose=1, period=1)
self.cnn.model.compile(
optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
self.cnn.model.fit(self.data.train_images, self.data.train_labels,
epochs=5, callbacks=[save_model_cb])
test_loss, test_acc = self.cnn.model.evaluate(
self.data.test_images, self.data.test_labels)
print('accuracy: %.4f, the size of tested images is %d' %
(test_acc, len(self.data.test_images)))
if __name__ == '__main__':
app = Train()
app.train()