In [1]:
from __future__ import division, print_function
from keras.callbacks import ModelCheckpoint, TensorBoard
from keras.models import Sequential, load_model
from keras.layers.core import Dense, Dropout, Flatten
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.utils import np_utils
from sklearn.metrics import accuracy_score, confusion_matrix
import numpy as np
import matplotlib.pyplot as plt
import os
%matplotlib inline
In [2]:
DATA_DIR = "../../data"
TRAIN_FILE = os.path.join(DATA_DIR, "mnist_train.csv")
TEST_FILE = os.path.join(DATA_DIR, "mnist_test.csv")
BEST_MODEL = os.path.join(DATA_DIR, "keras-mnist-cnn-best.h5")
FINAL_MODEL = os.path.join(DATA_DIR, "keras-mnist-cnn-final.h5")
TENSORBOARD_LOGS_DIR = os.path.join(DATA_DIR, "keras-mnist-cnn-tensorboard")
BATCH_SIZE = 128
NUM_CLASSES = 10
NUM_EPOCHS = 5
In [3]:
def parse_file(filename):
xdata, ydata = [], []
fin = open(filename, "rb")
i = 0
for line in fin:
if i % 10000 == 0:
print("{:s}: {:d} lines read".format(
os.path.basename(filename), i))
cols = line.strip().split(",")
ydata.append(int(cols[0]))
x1d = np.array([float(x) / 255.0 for x in cols[1:]])
x3d = np.reshape(x1d, (28, 28, 1))
xdata.append(x3d)
i += 1
print("{:s}: {:d} lines read".format(os.path.basename(filename), i))
fin.close()
Y = np_utils.to_categorical(np.array(ydata), num_classes=NUM_CLASSES)
X = np.array(xdata)
return X, Y
Xtrain, Ytrain = parse_file(TRAIN_FILE)
Xtest, Ytest = parse_file(TEST_FILE)
print(Xtrain.shape, Ytrain.shape, Xtest.shape, Ytest.shape)
Model defined is identical to that in Keras example mnist_cnn.py.
In [4]:
model = Sequential()
model.add(Conv2D(32, (3, 3), activation="relu", input_shape=(28, 28, 1)))
model.add(Conv2D(64, (3, 3), activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(NUM_CLASSES, activation="softmax"))
In [5]:
model.compile(optimizer="adam", loss="categorical_crossentropy",
metrics=["accuracy"])
In [6]:
model.summary()
The Tensorboard callback, if enabled will write out the training logs to the directory given by TENSORBOARD_LOGS_DIR, and you can now start the tensorboard server using the following command:
tensorboard --logdir=/path/to/TENSORBOARD_LOGS_DIR
The tensorboard application can be accessed from the browser at http://localhost:6060
In [7]:
checkpoint = ModelCheckpoint(filepath=BEST_MODEL, save_best_only=True)
tensorboard = TensorBoard(log_dir=TENSORBOARD_LOGS_DIR,
histogram_freq=1,
batch_size=BATCH_SIZE,
write_graph=True,
write_grads=True,
write_images=True,
embeddings_freq=0,
embeddings_layer_names=None,
embeddings_metadata=None)
history = model.fit(Xtrain, Ytrain, batch_size=BATCH_SIZE,
epochs=NUM_EPOCHS,
validation_split=0.1,
callbacks=[checkpoint, tensorboard])
In [8]:
model.save(FINAL_MODEL, overwrite=True)
In [9]:
plt.subplot(211)
plt.title("Accuracy")
plt.plot(history.history["acc"], color="r", label="Train")
plt.plot(history.history["val_acc"], color="b", label="Validation")
plt.legend(loc="best")
plt.subplot(212)
plt.title("Loss")
plt.plot(history.history["loss"], color="r", label="Train")
plt.plot(history.history["val_loss"], color="b", label="Validation")
plt.legend(loc="best")
plt.tight_layout()
plt.show()
In [10]:
def evaluate_model(model, model_name):
print("==== eval {:s} model on test set ====".format(model_name))
Ytest_ = model.predict(Xtest)
ytest = np.argmax(Ytest, axis=1)
ytest_ = np.argmax(Ytest_, axis=1)
acc = accuracy_score(ytest, ytest_)
cm = confusion_matrix(ytest, ytest_)
print("Accuracy: {:.4f}".format(acc))
print("Confusion Matrix")
print(cm)
evaluate_model(model, "best")
model = load_model(BEST_MODEL)
evaluate_model(model, "final")
In [ ]: