keras 中的输入形状(此损失期望目标与输出具有相同的形状)

Mar*_*hař 10 r neural-network keras tensorflow

这是我第一次使用 keras,我正在尝试按照我在网上找到的教程并将我自己的数据适合它。我有一个矩阵和二进制标签。

> str(d_train)
 num [1:1062, 1:180] -0.04748 0.04607 -0.05429 -0.0126 -0.00219 ...
> str(trainlabels)
 num [1:1062, 1:2] 0 0 0 0 0 0 1 0 0 0 ...
Run Code Online (Sandbox Code Playgroud)

我的代码:

model = keras_model_sequential()
model %>%
  layer_dense(units = 8, activation = 'relu', input_shape = c(180)) %>%
  layer_dense(units = 3, activation = "softmax")
summary(model)
## Compile
model %>%
  compile(loss = "binary_crossentropy",
          optimizer = "adam",
          metrics = "accuracy")
## Fit model
history = model %>%
  fit(d_train,
      trainlabels,
      epoch=200,
      batch_size=32,
      validation_split=0.2)
Run Code Online (Sandbox Code Playgroud)

我似乎不适合模型,我收到此错误消息:

Error in py_call_impl(callable, dots$args, dots$keywords) : 
  ValueError: A target array with shape (1062, 2) was passed for an output of shape (None, 3) while using as loss `binary_crossentropy`. This loss expects targets to have the same shape as the output.
Run Code Online (Sandbox Code Playgroud)

根据错误消息,要求输入数组的不同形状,我尝试更改尺寸但没有运气。

Mat*_*gro 15

我不是 R 专家,但在这里:

layer_dense(units = 3, activation = "softmax")
Run Code Online (Sandbox Code Playgroud)

你告诉 Keras 你的网络的输出有三个类。您的标签的形状(1062, 2)表明它有两个类,因此存在不一致。

你可以改变units = 2你最后的密集,它应该工作。另请注意,您正在使用softmax激活,在这种情况下,您应该更喜欢使用categorical_crossentropy损失。

binary_crossentropy用于二进制分类,您应该有units = 1sigmoid激活和标签应该是(1062, 1)(1062,),这意味着它们是 0-1 编码的。