嵌入和串联-Tensorflow Keras

我正在尝试复制神经网络。神经网络的体系结构是LSTM Model。 第一输入是作为大小为2 ^ 18的二进制向量的散列词,该散列词使用嵌入层嵌入可训练的500维分布式表示中。

字数与每个批处理元素不同。在词被嵌入并应用了辍学之后,我需要与特征向量连接,特征向量每个词具有24个特征。

问题在于,嵌入后的第一个输入具有不同维的特征向量。嵌入词的维数为(None,None,18,500),特征vetors的维数为(None,None,24)。第一个None元素是批处理大小,第二个None是每个批处理元素的字数。

如何将嵌入词与特征向量连接起来?

下面是我的代码:

        inputs = Input(shape=(None,18,),dtype=np.int16,name="Inp1")
        embbed_input = Embedding(input_dim=1,output_dim=500,input_length=18)
        aux = embbed_input(inputs)
        aux = Dropout(rate=self.dropout_rate)(aux)
        inputs_feat = Input(shape=(None,24,dtype=np.float32,name="Inp2")
        aux = concatenate([aux,inputs_feat],axis=2) #ValueError here 
        aux = Dense(units=600,activation="relu")(aux)
        aux = Dense(units=600,activation="relu")(aux)
        aux = Bidirectional(LSTM(units=400,return_sequences=True))(aux)
        aux = Dropout(rate=self.dropout_rate)(aux)
        aux = Dense(units=600,activation="relu")(aux)
        aux = Dense(units=29,activation="sigmoid")(aux)


        ValueError: A 'concatenate' layer require inputs with matching shapes except for the concat axis. Got inputs shapes: [(None,None,500),(None,24)]
linwen86 回答:嵌入和串联-Tensorflow Keras

由于单步输入包含18个用于嵌入层的输入,因此我们可能需要重新调整嵌入层的输出形状以平整最后两个维度。

    # import Reshape layer
    from tf.keras.layers import Reshape

    inputs = Input(shape=(None,18,),dtype=np.int16,name="Inp1")
    embbed_input = Embedding(input_dim=1,output_dim=500,input_length=18)
    aux = embbed_input(inputs)
    # Note: it is generally not a great idea to add dropout just after the embedding layer
    aux = Dropout(rate=self.dropout_rate)(aux)
    # before the concatenate layer,reshape it to (None,None,500*18)
    aux = Reshape(target_shape=(-1,-1,500*18))(aux)
    inputs_feat = Input(shape=(None,24,dtype=np.float32,name="Inp2")
    aux = concatenate([aux,inputs_feat],axis=2) # no need to specify axis when it is the final dimension
    aux = Dense(units=600,activation="relu")(aux)
    aux = Dense(units=600,activation="relu")(aux)
    aux = Bidirectional(LSTM(units=400,return_sequences=True))(aux)
    aux = Dropout(rate=self.dropout_rate)(aux)
    aux = Dense(units=600,activation="relu")(aux)
    aux = Dense(units=29,activation="sigmoid")(aux)
本文链接:https://www.f2er.com/2502406.html

大家都在问