检查目标时出错:预期dense_3 具有形状(2,) 但得到形状为(1,) 的数组 [英] Error when checking target: expected dense_3 to have shape (2,) but got array with shape (1,)

查看:21
本文介绍了检查目标时出错:预期dense_3 具有形状(2,) 但得到形状为(1,) 的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Keras 的功能 API(使用 TensorFlow 后端)训练具有多个输出层的文本情感分类模型.根据 Keras 规范,该模型将 Keras 预处理 API 的 hashing_trick() 函数生成的 Numpy 散列值数组作为输入,并使用二进制 one-hot 标签的 Numpy 数组的list 作为其目标用于训练具有多个输出的模型(请参阅此处的 fit() 文档:https://keras.io/models/模型/).

I'm training a textual sentiment classification model with multiple output layers in Keras's Functional API(using a TensorFlow backend). The model takes as input a Numpy array of hashed values produced by the Keras Preprocessing API's hashing_trick() function, and uses a list of Numpy arrays of binary one-hot labels as its targets, as per Keras specifications for training a model with multiple outputs(see fit()'s documentation here: https://keras.io/models/model/).

这是模型,没有大部分预处理步骤:

Here's the model, sans most of the preprocessing steps:

    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)

以下是此模型生成的错误跟踪训练的要点:

Here's the gist of the error trace training this model produces:

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

ValueError: Error when checking target: expected dense_3 to have shape (2,) but got array with shape (1,)

推荐答案

你的 numpy 数组(输入和输出)应该包含一个批处理维度.如果您的标签当前的形状为 (2,),您可以将它们重塑为包含批处理维度,如下所示:

Your numpy arrays (both for inputs and outputs) should contain a batch dimension. If your labels are currently of shape (2,), you can reshape them to include a batch dimension as follows:

label_array = label_array.reshape(1, -1)

这篇关于检查目标时出错:预期dense_3 具有形状(2,) 但得到形状为(1,) 的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆