tf.keras遇见的坑:Output tensors to a Model must be the output of a TensorFlow `Layer`

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

再编写TEXT-CNN模型时,代码报错,以下为报错代码:

convs = []
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)    #一般为卷积网络最近全连接的前一层,用于将数据压缩成一维
convs.append(l_pool11)
l_conv2 = keras.layers.Conv2D(filters=3, kernel_size=(3, 32), activation='relu')(embed)
l_pool2 = keras.layers.MaxPooling2D(pool_size=(254, 1))(l_conv2)
l_pool22 = keras.layers.Flatten()(l_pool2)
convs.append(l_pool22)
l_conv3 = keras.layers.Conv2D(filters=3, kernel_size=(4, 32), activation='relu')(embed)
l_pool3 = keras.layers.MaxPooling2D(pool_size=(253, 1))(l_conv3)
l_pool33 = keras.layers.Flatten()(l_pool2)
convs.append(l_pool33)
merge = keras.layers.concatenate(convs, axis=1)

out = keras.layers.Dropout(0.5)(merge)

output = keras.layers.Dense(32, activation='relu')(out)

pred = keras.layers.Dense(units=1, activation='sigmoid')(output)

model = keras.models.Model(inputs=inputs, outputs=pred)
# adam = optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)
model.summary()
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=['accuracy'])

经过网上查找,找到了问题所在:在使用keras编程模式是,中间插入了tf.reshape()方法便遇到此问题。 

解决办法:对于遇到相同问题的任何人,可以使用keras的Lambda层来包装张量流操作,这是我所做的:

embed1 = keras.layers.Embedding(10000, 32)(inputs)

# embed = keras.layers.Reshape(-1,256, 32, 1)(embed1)
# embed = tf.reshape(embed1, [-1, 256, 32, 1])
def reshapes(embed1):
    embed = tf.reshape(embed1, [-1, 256, 32, 1])
    return embed
embed = keras.layers.Lambda(reshapes)(embed1)

 

你可能感兴趣的:(desultory_issue)