Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError: Unknown layer: KerasLayer

I have the following code:

from keras.models import model_from_json

with open('modelS.json', 'r') as f: 
  json = f.read() 
loaded_model = model_from_json(json)

Here is the json file used in the above code:

{"class_name": "Sequential", "config": {"name": "sequential", "layers": [{"class_name": "KerasLayer", "config": {"name": "keras_layer", "trainable": true, "batch_input_shape": [null], "dtype": "string", "handle": "https://tfhub.dev/google/tf2-preview/nnlm-en-dim128/1"}}, {"class_name": "Dense", "config": {"name": "dense", "trainable": true, "dtype": "float32", "units": 16, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Dense", "config": {"name": "dense_1", "trainable": true, "dtype": "float32", "units": 16, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Dense", "config": {"name": "dense_2", "trainable": true, "dtype": "float32", "units": 1, "activation": "sigmoid", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}], "build_input_shape": [null]}, "keras_version": "2.3.0-tf", "backend": "tensorflow"}

But I get the following error from the last line:

ValueError: Unknown layer: KerasLayer.

What could be the reason for this?


1 Answers

Mentioning the Answer in this (Answer) Section even though it is present in the Comments Section, for the benefit of the community.

Adding the import statement: import tensorflow_hub as hub and then using a custom layer with custom_objects={'KerasLayer': hub.KerasLayer} in the model_from_json() statement has resolved the error.

Complete working code is shown below:

from tensorflow.keras.models import model_from_json

import tensorflow_hub as hub

with open('models.json', 'r') as f: 
  json = f.read() 
loaded_model = model_from_json(json, custom_objects={'KerasLayer': hub.KerasLayer})