错误:Output tensors to a Model must be the output of a TensorFlow `Layer`

使用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博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值