Keras: 'KerasRegressor' object has no attribute 'to_json'

Created on 3 Jun 2017  路  3Comments  路  Source: keras-team/keras

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
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'

Any ideas?

tensorflow

Most helpful comment

You need to call the to_json method on a Model instance:

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

All 3 comments

You can save the model using a ModelCheckpoint in your callbacks, and adding the callback list to the fit call.

checkpoint = ModelCheckpoint("./snapshots/trained_model.hdf5", monitor='val_loss', verbose=1, save_best_only=False)
callbacks_list = [checkpoint]

And then in your fit call
history = estimator.fit(train_images, train_labels, callbacks=callbacks_list)

You need to call the to_json method on a Model instance:

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

Closing this issue since solution provided above works. Feel free to reopen if the issue still persists. Thanks!

Was this page helpful?
0 / 5 - 0 ratings