Currently I have a project which will train on a data set. This is great! However I need to be able to export the trained data to work in production. Given I have a Keras model named model this appears to be rather simple:

def export_trained_model(model, file_name):
    model.save_weights(file_name)

Almost too simple! I am hoping I did not miss anything there. Next up is loading the model again. Using this technique the model needs to be created in the exact same way, otherwise the behavior is undefined. The following function will load a the weights back:

def import_trained_model( file_name, model ):
    model.load_weights( file_name )

Should be simple enough. If I have it wrong at least I have a single file to modify to fix it!

Due to the awesomeness which is Keras I did not have load any of the images for training. However now I have the big question of how to ask the model what labels should be applied to an image! Turns out ths process is fairly simple:

from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img

def label_image(model, image_name):
    img = load_img(image_name, target_size=(256,256))

    image_data_raw = img_to_array(img)
    image_data_shaped = image_data_raw.reshape((1,) + image_data_raw.shape)

    classes = model.predict(image_data_shaped)
    return classes

The classes will be an array with the confidence of a match for each label your model is trained on. From here you could select the label with the highest index or reject all labels if there isn’t a clear winner.