Add save, evaluate and predict functionality for example
* Add save, evaluate and predict funcationality for example, and included string labels for predict.
* Modifications to style based on code review
Modifications to style based on code review and removed dependency.
* Resolving pep-8 issues.
* Pulling saving weights example.
@@ -15,10 +15,17 @@ from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
+import os
+import pickle
+import numpy as np
+
batch_size = 32
num_classes = 10
epochs = 200
data_augmentation = True
+num_predictions = 20
+save_dir = os.path.join(os.getcwd(), 'saved_models')
+model_name = 'keras_cifar10_trained_model.h5'
# The data, shuffled and split between train and test sets:
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
@@ -99,3 +106,42 @@ else:
steps_per_epoch=x_train.shape[0] // batch_size,
epochs=epochs,
validation_data=(x_test, y_test))
+
+# Save model and weights
+if not os.path.isdir(save_dir):
+ os.makedirs(save_dir)
+model_path = os.path.join(save_dir, model_name)
+model.save(model_path)
+print('Saved trained model at %s ' % model_path)
+
+# Load label names to use in prediction results
+label_list_path = 'datasets/cifar-10-batches-py/batches.meta'
+
+
+keras_dir = os.path.expanduser(os.path.join('~', '.keras'))
+datadir_base = os.path.expanduser(keras_dir)
+if not os.access(datadir_base, os.W_OK):
+ datadir_base = os.path.join('/tmp', '.keras')
+label_list_path = os.path.join(datadir_base, label_list_path)
+
+with open(label_list_path, mode='rb') as f:
+ labels = pickle.load(f)
+
+# Evaluate model with test data set and share sample prediction results
+evaluation = model.evaluate_generator(datagen.flow(x_test, y_test,
+ batch_size=batch_size),
+ steps=x_test.shape[0] // batch_size)
+
+print('Model Accuracy = %.2f' % (evaluation[1]))
+
+predict_gen = model.predict_generator(datagen.flow(x_test, y_test,
+ batch_size=batch_size),
+ steps=x_test.shape[0] // batch_size)
+
+for predict_index, predicted_y in enumerate(predict_gen):
+ actual_label = labels['label_names'][np.argmax(y_test[predict_index])]
+ predicted_label = labels['label_names'][np.argmax(predicted_y)]
+ print('Actual Label = %s vs. Predicted Label = %s' % (actual_label,
+ predicted_label))
+ if predict_index == num_predictions:
+ break
