简体   繁体   中英

How to save keras model along with other data and load them altogether?

I have the following code to train a keras neural network

from keras import Sequential
from keras.layers import Dense
from keras.models import load_model

import numpy as np

class Model:
    def __init__(self, data=None):
        self.data = data
        self.metrics = []
        self.model = self.__build_model()

    def __build_model(self):
        model = Sequential()
        model.add(Dense(4, activation='relu', input_shape=(3,)))
        model.add(Dense(1, activation='relu'))
        model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
        return model

    def train(self, epochs):
        self.model.fit(self.data[:, :-1], self.data[:,-1], epochs=epochs)
        return self

    def test(self, data):
        self.metrics = self.model.evaluate(data[:, :-1], data[:, -1])
        return self

    def predict(self, input):
        return self.model.predict(input)

    def save(self, path):
        self.model.save(path)
        # I would like to save self.metrics at the same time

    def load(self, path):
        self.model = load_model(path)


if __name__ == '__main__':
    train_data = np.random.rand(1000, 4)
    test_data = np.random.rand(100, 4)
    print("TRAINING, TESTING & SAVING..")
    model = Model(train_data)\
                .train(epochs=5)\
                .test(test_data)\
                .save('./model.h5')

    print('LOADING model & PREDICTING..')
    test_sample = np.random.rand(1, 3)
    model = Model()
    model.load('./model.h5')
    # I can then do like:
    test_output = model.predict(test_sample)
    print(test_output)

    # And want to get metrics which i had saved with it like:
    metrics = model.metrics
    print(metrics)

As you can see it saves the model to a h5 file, but only the keras model not anything else. How can I save other data a the same time like the metrics and then be able to load them too while loading the keras model.

Thanks !

You can use any serialization framework to do that.

import hickle

def save(self, path):
      self.model.save(path)
      hkl.dump(self.metrics, 'metrics.hkl', mode='w')

def load(self, path):
      self.model = load_model(path)
      self.metrics = hkl.load('metrics.hkl')

You can also save it as a single file, just make a list or another object out of the metrics and the model object. I would suggest to save them separately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM