python - 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
.
这可能是什么原因?
解决方案
为了社区的利益,在此(答案)部分提及答案,即使它出现在评论部分。
添加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})
推荐阅读
- c++ - why do i get an empty line as the first output?
- java - Java Stream过滤相同的字段但不同的标准
- c# - 由 HttpClientFactory 创建的长寿 HttpClient
- android - Can nested NavHosts both be the default nav host (defaultNavHost="true")?
- r - Kendall Correlation P-Value
- java - 适用于 Windows 的 JDK/JRE 安装
- pine-script - M15 中的图形,H4 中的指标
- android - 收到通知时运行 Sqlite 代码 Xamarin Forms
- python - mapping values from one dataframe to another dataframe
- java - 通过继承和类型参数化存储库访问 JPA 方法