检查目标时出错:预期density_3的形状为(2,),但数组的形状为(1,)


问题内容

我正在使用Keras的Functional
API(使用TensorFlow后端)训练具有多个输出层的文本情感分类模型。该模型的输入是由所述Keras预处理API的hashing_trick()函数产生的散列值的numpy的阵列,并且使用一个
列表
二元一热标签作为其目标的numpy的阵列,按照Keras规范训练具有多个输出的模型(请参见fit()的文档:https//keras.io/models/model/)。

这是模型,没有大多数预处理步骤:

    textual_features = hashing_utility(filtered_words) # Numpy array of hashed values(training data)

    label_list = [] # Will eventually contain a list of Numpy arrays of binary one-hot labels

    for index in range(one_hot_labels.shape[0]):
        label_list.append(one_hot_labels[index])

     weighted_loss_value = (1/(len(filtered_words))) # Equal weight on each of the output layers' losses

     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:检查目标时出错:预期density_3的形状为(2,),但数组的形状为(1,)


问题答案:

您的numpy arrays(用于输入和输出)都应包含一个批次尺寸。如果您的标签当前为shape (2,),则可以对其进行重塑以包括如下的批次尺寸:

label_array = label_array.reshape(1, -1)