r - 输入形状(以喀拉斯计)(此损失期望目标与输出具有相同的形状)

标签 r tensorflow keras neural-network

这是我第一次使用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 ...

我的代码:
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)

我似乎无法拟合模型,收到以下错误消息:
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.

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

最佳答案

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

layer_dense(units = 3, activation = "softmax")

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

您可以只更改最后一个密密的units = 2,它应该可以工作。还要注意,您正在使用softmax激活,在这种情况下,您应该更喜欢使用categorical_crossentropy丢失。

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

关于r - 输入形状(以喀拉斯计)(此损失期望目标与输出具有相同的形状),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56598749/

相关文章:

从长数据格式 reshape 为宽数据格式并匹配 R 中的开始到结束日期对

r - 在 R 中不替换地向字符插入空格

r - 从R中的文件读取数据帧时如何跳过无效行?

protocol-buffers - 如何从 C++ 中的 protobuf 执行 TensorFlow 图?

python - 如何展平嵌套模型? (keras 函数式 API)

tensorflow - 为什么我的 TensorBoard 训练图不完整(使用 Jupyter/TensorFlow/Keras)?

css - 如何在 Shiny 的应用程序中突出显示事件代码?

python - 从图 def 到 session 的 tensorflow 重新加载模式

user-interface - 如何构建 tensorflow 分析器 ui?

tensorflow - 当度量为 SparseTopKCategoricalAccuracy/TopKCategoricalAccuracy 时,在 Keras 中使用什么损失函数?