检查目标时出错:期望dense_3的形状为(2,),但得到的数组形状为(1,)

我在使用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)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注