我在使用Keras的函数式API(使用TensorFlow后端)训练一个文本情感分类模型,该模型具有多个输出层。模型的输入是一个由Keras预处理API的hashing_trick()函数生成的哈希值的Numpy数组,目标是一个包含二进制独热标签的Numpy数组列表,符合Keras关于训练多输出模型的规范(请参见fit()的文档:https://keras.io/models/model/)。
以下是模型的代码,除了大部分预处理步骤外:
textual_features = hashing_utility(filtered_words) # Numpy数组,包含哈希值(训练数据)
label_list = [] # 将最终包含一个二进制独热标签的Numpy数组列表
for index in range(one_hot_labels.shape[0]):
label_list.append(one_hot_labels[index])
weighted_loss_value = (1/(len(filtered_words))) # 每个输出层的损失的权重相同
weighted_loss_values = []
for index in range (one_hot_labels.shape[0]):
weighted_loss_values.append(weighted_loss_value)
text_input = Input(shape = (1,))
intermediate_layer = Dense(64, activation = 'relu')(text_input)
hidden_bottleneck_layer = Dense(32, activation = 'relu')(intermediate_layer)
keras.regularizers.l2(0.1)
output_layers = []
for index in range(len(filtered_words)):
output_layers.append(Dense(2, activation = 'sigmoid')(hidden_bottleneck_layer))
model = Model(inputs = text_input, outputs = output_layers)
model.compile(optimizer = 'RMSprop', loss = 'binary_crossentropy', metrics = ['accuracy'], loss_weights = weighted_loss_values)
model.fit(textual_features, label_list, epochs = 50)
以下是训练此模型时产生的错误跟踪的要点:
ValueError: 检查目标时出错:期望dense_3的形状为(2,),但得到的数组形状为(1,)
回答:
您的numpy数组
(输入和输出)应该包含批次维度。如果您的标签当前形状为(2,)
,您可以按以下方式重塑它们以包含批次维度:
label_array = label_array.reshape(1, -1)