ValueError:未知层:KerasLayer

时间:2020-04-22 20:25:09

标签: python tensorflow keras

我有以下代码:

from keras.models import model_from_json

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

这是上面代码中使用的json文件:

{"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"}

但是我从最后一行得到以下错误:

ValueError: Unknown layer: KerasLayer

这可能是什么原因?

1 个答案:

答案 0 :(得分:4)

即使在“评论”部分中,也要在本(回答)部分中提及答案,以造福社区。

添加import语句:import tensorflow_hub as hub,然后在custom_objects={'KerasLayer': hub.KerasLayer}语句中使用带有model_from_json()的自定义层已解决了该错误。

完整的工作代码如下所示:

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})