使用tf.keras.models.Model()构建模型时遇到错误:
Output tensors to a Model must be the output of a TensorFlow `Layer`
出错环境是Tensorflow 1.x 在Tensorflow 2中正常,这里出错的原因是因为代码中混用了keras或tf.keras和tf的一些函数(层)。
比如:
inputs = keras.layers.Input(shape=(256,))
embed1 = keras.layers.Embedding(10000, 32)(inputs)
# embed = keras.layers.Reshape(-1,256, 32, 1)(embed1)
print(embed1[0])
embed = tf.reshape(embed1, [-1, 256, 32, 1])
print(embed[0])
l_conv1 = keras.layers.Conv2D(filters=3, kernel_size=(2, 32), activation='relu')(embed) #现长度 = 1+(原长度-卷积核大小+2*填充层大小) /步长 卷积核的形状(fsz,embedding_size)
l_pool1 = keras.layers.MaxPooling2D(pool_size=(255, 1))(l_conv1) # 这里面最大的不同 池化层核的大小与卷积完的数据长度一样
l_pool11 = keras.layers.Flatten()(l_pool1)
"""
省略若干行
"""
pred = keras.layers.Dense(units=1, activation='sigmoid')(output)
model = keras.models.Model(inputs=inputs, outputs=pred)
这里的tf.reshape是乱入的,需要使用keras.layers的一些操作实现。(对于tf2没问题)
解决方法1是使用keras.layers.Reshape
embed = keras.layers.Reshape([-1, 256, 32, 1])(embed1)
解决方法2是使用keras的Lambda
def reshapes(embed1):
embed = tf.reshape(embed1, [-1, 256, 32, 1])
return embed
embed = keras.layers.Lambda(reshapes)(embed1)
参考:tf.keras遇见的坑:Output tensors to a Model must be the output of a TensorFlow `Layer`_wpf的博客-CSDN博客