首页 > 解决方案 > 嵌入层 Keras 后无法添加 CNN 层

问题描述

我有 7 个分类特征并且我试图在嵌入层之后添加一个 CNN 层

我的第一层是输入层第二层是嵌入层第三层我想添加一个 Conv2D 层

我已经在 Conv_2D 中尝试过 input_shape=(7,36,1) 但这没有用

input2 = Input(shape=(7,))
embedding2 = Embedding(76474, 36)(input2)

# 76474 is the number of datapoints (rows)
# 36 is the output dim of embedding Layer

cnn1 = Conv2D(64, (3, 3), activation='relu')(embedding2)
flat2 = Flatten()(cnn1)

但我收到了这个错误

 Input 0 of layer conv2d is incompatible with the layer: expected 
 ndim=4, found ndim=3. Full shape received: [None, 7, 36]

标签: python-3.xkerasdeep-learningconv-neural-network

解决方案


嵌入层的输出是 3D,即(samples, seq_length, features)features = 36嵌入空间的维数,seq_length = 7是序列长度。一个Conv2D层需要一个图像,它通常表示为一个 4D 张量(samples, width, height, channels)

只有Conv1D一层才有意义,因为它还需要 3D 形状的数据,通常是(samples, width, channels),然后您需要决定是要跨序列长度还是跨特征维度进行卷积。这是你需要试验的东西,最终是决定嵌入输出中哪个是“空间维度”


推荐阅读