我正在尝试使用预训练的模型,添加一些新层和操作,并在tensorflow
中执行培训课程。因此,我陷入了tf.keras.applications.*
名称空间,并开始使用一些实现的模型。
加载基本模型后,我添加了这样的新层:
x = base_model.output
# this line seems to cause my error
x = tf.reshape(x, [-1, 1])
# using this line solves the issue
# tf.keras.layers.Flatten()(x) #
x = tf.keras.layers.Dense(1024, activation="relu")(x)
x = tf.keras.layers.Dense(5, activation="softmax")(x)
现在,当我从张量x
创建新的tf.keras.models.Model(...)
时,我会收到此错误消息:
Output tensors to a Model must be the output of a TensorFlow `Layer`
(thus holding past layer metadata).
Found: Tensor("dense_27/Softmax:0", shape=(?, 3), dtype=float32)
我猜是由于在tf.keras
型号内使用tf.*
操作而引起的。在这种情况下,我可以轻松地使用keras替代品,但是现在我开始想知道是否存在解决方案操作的方法,无论如何都可以使用张量操作。还是我完全局限于使用tf.keras.layer.*
操作?
如评论中所述,您需要将TF操作包装在Lambda
层(或任何自定义层(,以便Keras可以找到用于构建Model
对象的所需元数据。
x = base_model.output
x = tf.keras.layers.Lambda(lambda x: tf.reshape(x, [-1, 1]))(x)
x = tf.keras.layers.Dense(1024, activation="relu")(x)
x = tf.keras.layers.Dense(5, activation="softmax")(x)
可能值得注意的是,在尝试保存和加载此模型时,会有一个错误,抱怨未定义名称tf
。
model = tf.keras.Model(base_model.input, x)
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam')
model.save('1.h5')
m = tf.keras.models.load_model('1.h5')
# NameError: name 'tf' is not defined
这是因为在模型加载过程中,tf
未在重新构造Lambda
层的范围内导入。它可以通过提供custom_objects
词典来解决load_model
。
m = tf.keras.models.load_model('1.h5', custom_objects={'tf': tf})