【发布时间】:2022-01-11 01:04:50
【问题描述】:
将我的代码从 TF1 调整到 TF2.6 我遇到了麻烦。 我正在尝试向 inception resnet 添加一些自定义层,保存模型,然后加载并运行它。
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Model
from tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
import tensorflow as tf
import numpy as np
from PIL import Image
export_path = "./save_test"
# Get model without top and add two layers
base_model = InceptionResNetV2(weights='imagenet', input_tensor=None, include_top=False)
out = base_model.output
out = GlobalAveragePooling2D()(out)
predictions = Dense(7, activation='softmax', name="output")(out)
# Make new model using inputs from base model and custom outputs
model = Model(inputs=base_model.input, outputs=[predictions])
# save model
tf.saved_model.save(model, export_path)
# load model and run
with tf.compat.v1.Session(graph=tf.Graph()) as sess:
tf.compat.v1.saved_model.loader.load(sess, ['serve'], export_path)
graph = tf.compat.v1.get_default_graph()
img = Image.new('RGB', (299, 299))
x = tf.keras.preprocessing.image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = x[..., :3]
x /= 255.0
x = (x - 0.5) * 2.0
y_pred = sess.run('output/Softmax:0', feed_dict={'serving_default_input_1:0': x})
错误:
KeyError: "The name 'output/Softmax:0' refers to a Tensor which does not exist. The operation, 'output/Softmax', does not exist in the graph."
我不明白的:
predictions.name 是 'output/Softmax:0',但是
graph.get_tensor_by_name('output/Softmax:0') 告诉我它不存在!
注意:我知道我可以使用 TF2 的 tf.keras.models.save 和 tf.keras.models.load_model 保存和加载,然后使用 model(x) 运行模型。但是,在我的应用程序中,我在内存中有多个模型,并且我发现推理时间比使用 session 对象的 TF1 代码要长得多。因此,我想在兼容模式下将 TF1 方法与 session 对象一起使用。
保存时如何控制输入/输出的名称?我错过了什么?
【问题讨论】:
标签: python tensorflow machine-learning keras tensorflow2.0