我用此代码保存了训练有素的模型,但由于该层不在keras.layer中,所以无法加载它,这是我的代码,在此先感谢您的宝贵帮助!
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
train_data, validation_data, test_data = tfds.load(
name="imdb_reviews",
split=[
tfds.Split.TRAIN.subsplit(tfds.percent[:60]),
tfds.Split.TRAIN.subsplit(tfds.percent[60:]),
'test'
],
as_supervised=True)
train_examples_batch, train_labels_batch = next(iter(train_data.batch(10)))
# to use for more accuracy... : google/tf2-preview/nnlm-en-dim128/1
embedding = "https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1"
hub_layer = hub.KerasLayer(embedding, input_shape=[],
dtype=tf.string, trainable=True)
hub_layer(train_examples_batch[:3])
model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1))
model.summary()
model.compile(optimizer='adam',
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
history = model.fit(train_data.shuffle(10000).batch(512),
epochs=20,
validation_data=validation_data.batch(512),
verbose=1)
results = model.evaluate(test_data.batch(512), verbose=1)
for name, value in zip(model.metrics_names, results):
print("%s: %.3f" % (name, value))
# serialize model to JSON
model_json = model.to_json()
with open("my_model.json", "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("w_model.h5")
当我尝试加载它时,我遇到了一个问题,原因是它无法识别由tensorflow数据集创建的图层“ hub_layer”。希望您知道如何处理。
答案 0 :(得分:0)
这里的问题是模型保存文件不包含该层的代码。您可以使用custom_objects解决此问题,并将字典传递给该参数。
这里的窍门是复制无法识别的名称,将其放入字典中的字符串作为键,并提供该层作为其值
例如
import tensorflow_hub as hub
layer_dict = {
"hub_layer":hub.KerasLayer
}
model = model_from_json('model_file',custom_objects=layer_dict)