使用多个输入将功能连接到Keras函数API时出错

2024-06-09 22:05:36 发布

您现在位置:Python中文网/ 问答频道 /正文

在哪里插入从训练集中提取的特征以在模型中使用?我是否只需要连接层。连接([])? 我已经计算了标题和文档的语义相似度。我想将该功能作为模型中的输入

信息:

embedded_sequences_head: Tensor w/shape (None, 15, 300) #Glove300D
embedded_sequences_body: Tensor w/shape (None, 150, 300) # Glove 300D
sequence_input_head: Tensor w/shape (None, 15)
sequence_input_body: Tensor w/shape (None, 150)
sequence_input_body: Tensor w/shape (None, 26784)
headline_pad: ndarray w/shape (26784, 15), dtype=int32
art_body_pad: ndarray w/shape (26784, 150), dtype=int32
y_train_cat: ndarray w/shape (26784, 4), dtype=float32
semantic_x_tr = np.array(x_train['semantic_sim_70'].to_list()) # ndarray (26784,)

型号

semantic_feat = Input(shape=(len(semantic_x_tr),), name ="semantic")
x1  = Conv1D( FILTERS, kernel_size = KERNEL, strides = STRIDE, padding='valid', activation = 'relu')(embedded_sequences_head)
x11 = GlobalMaxPooling1D()(x1)
x2  = Conv1D( FILTERS, kernel_size = KERNEL, strides = STRIDE, padding='valid', activation = 'relu')(embedded_sequences_body)
x22 = GlobalMaxPooling1D()(x2)
x = concatenate([x11,x22, semantic_feat], axis=1)
x = Dense(UNITS, activation="relu")(x)
x = Dropout(0.5)(x)
preds = Dense(4, activation="softmax", name = 'predic')(x)

列车型号

model = Model(inputs = [sequence_input_head, sequence_input_body, semantic_feat], outputs = [preds],)

history = model.fit({'headline':headline_pad, 'articleBody':art_body_pad, 'semantic': semantic_x_tr},
                    {'predic':y_train_cat},
                    epochs=100,
                    batch_size= BATCH__SIZE,
                    shuffle= True,
                    validation_data = ([headline_padded_validation, art_body_padded_validation, semantic_x_val], y_val_cat),
                    callbacks = [es]
                    )

模型块编译时似乎没有错误,但当我运行训练模型代码块时,它会返回警告和错误:

WARNING: tensorflow:Model was constructed with shape (None, 26784) for input Tensor("semantic_6:0", shape=(None, 26784), dtype=float32), but it was called on an input with incompatible shape (None, 1).

ValueError: Input 0 of layer dense_16 is incompatible with the layer: expected axis -1 of input shape to have value 26804 but received input with shape [None, 21]

2020年9月25日更新


我相信这个问题是由于我在x=concatenate()函数中的语法错误造成的

x = tf.keras.layers.Concatenate(axis=1)([x11, x22, semantic_feat])

Tags: 模型noneinputbodyheadsemanticembeddedtensor