【问题标题】:Error when checking target: expected dense_3 to have shape (2,) but got array with shape (1,)检查目标时出错:预期 dense_3 的形状为 (2,) 但得到的数组的形状为 (1,)
【发布时间】:2019-01-16 05:15:24
【问题描述】:

我正在 Keras 的功能 API(使用 TensorFlow 后端)中训练具有多个输出层的文本情感分类模型。该模型将由 Keras 预处理 API 的 hashing_trick() 函数生成的散列值的 Numpy 数组作为输入,并根据 Keras 规范使用二进制 one-hot 标签的 Numpy 数组的 list 作为其目标用于训练具有多个输出的模型(请参阅此处的 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: 检查目标时出错:预期dense_3 的形状为(2,),但得到的数组的形状为(1,)

【问题讨论】:

  • 检查Input(shape = (None,)) 提供了什么。
  • 产生以下错误跟踪:TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
  • 由于标签尺寸与输出层的预期不匹配而导致此错误。可以贴一下 label_list[0].shape 的形状吗?
  • label_list[0].shape 是:(2,)。

标签: python tensorflow machine-learning keras deep-learning


【解决方案1】:

您的numpy arrays(用于输入和输出)应包含批处理维度。如果您的标签当前的形状为 (2,),您可以将它们重新调整为包含批处理维度,如下所示:

label_array = label_array.reshape(1, -1)

【讨论】:

  • 感谢您的帮助。
【解决方案2】:

我用过

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

安装

model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])

我改变了损失,它对我有用。

【讨论】:

  • 虽然此代码可能会解决问题,including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
猜你喜欢
  • 2021-06-30
  • 1970-01-01
  • 2018-08-29
  • 2020-05-19
  • 1970-01-01
  • 2019-05-10
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多