首页 > 解决方案 > ValueError:未知层:KerasLayer

问题描述

我有以下代码:

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.

这可能是什么原因?

标签: pythontensorflowkeras

解决方案


为了社区的利益,在此(答案)部分提及答案,即使它出现在评论部分。

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

推荐阅读