1

I'm unable to save the model trained using KerasRegressor wrapper...

model = KerasRegressor(build_fn=base_model, epochs=1, batch_size=10, verbose=1)
model.fit(X,Y)

model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)
    model.save_weights("model.h5", overwrite=True)
    logger.info("Saved model to disk")

Here's my import:

from keras.wrappers.scikit_learn import KerasRegressor
from keras.layers import Dense, Activation
from keras.models import Sequential
from keras.models import model_from_json

# multi gpu
import tensorflow as tf
from keras import backend as K
from keras.models import Model
from keras.layers import Input
from keras.layers.core import Lambda
from keras.layers.merge import Concatenate

And the error I got is the following:

Traceback (most recent call last):
  File "train-model.py", line 175, in <module>
  File "train-model.py", line 114, in main
    model.save_weights("model.h5", overwrite=True)
AttributeError: 'KerasRegressor' object has no attribute 'to_json'

I build the model in using a function that returns a model:

def base_model():
    global N, M

    model = Sequential()
    model.add(Dense(512, input_dim=M, kernel_initializer='normal', activation='relu'))
    model.add(Dense(128, kernel_initializer='normal', activation='relu'))
    model.add(Dense(1, kernel_initializer='normal', activation='linear'))

    model.compile(loss='mean_squared_error', optimizer='rmsprop')

    # model = to_multi_gpu(model)

    return model

Any ideas?

Progeny
  • 672
  • 1
  • 11
  • 25
  • You first need to access the under lying model over which the kerasregressor wrapper is used, and then call save on it. Use `model.model.tojson()` and `model.model.save_weights()` – Vivek Kumar Jun 04 '17 at 01:55

1 Answers1

0

Here is a code to use:
model = KerasRegressor(build_fn=base_model, epochs=1, batch_size=10, verbose=1)
model.fit(X,Y)
def save_model_to_json(my_model):
json_model = my_model.model.to_json()
with open("model.json", "w") as json_file:
json_file.write(json_model)
my_model.model.save_weights("model.h5")
save_model_to_json(model)
#two files will be generated, model.json, which is your model and model.h5 which is #the file that has the weights of your model\

Theodoros
  • 1
  • 1