首页 > 解决方案 > 用于输出的 Keras 2D 密集层

问题描述

我正在玩一个模型,它应该以 8x8 棋盘作为输入,编码为 224x224 灰度图像,然后输出 64x13 单热编码逻辑回归 = 方块上的概率。

现在,在我不太清楚的卷积层之后,如何继续获得 2D-Dense 层作为结果/目标。

我尝试将 Dense(64,13) 作为层添加到我的 Sequential 模型中,但出现错误“Dense` 只能接受 1 个位置参数('units',)”

甚至可以训练二维目标吗?

EDIT1:这是我的代码的相关部分,简化:

# X.shape = (10000, 224, 224, 1)
# Y.shape = (10000, 64, 13)

model = Sequential([
    Conv2D(8, (3,3), activation='relu', input_shape=(224, 224, 1)),
    Conv2D(8, (3,3), activation='relu'),

    # some more repetitive Conv + Pooling Layers here

    Flatten(),

    Dense(64,13)
])

TypeError:Dense只能接受 1 个位置参数 ('units',),但您传递了以下位置参数:[64, 13]

EDIT2:正如 Anand V. Singh 所建议的,我将 Dense(64, 13) 更改为 Dense(832),效果很好。损失 = 毫秒。

使用“sparse_categorical_crossentropy”作为损失和 64x1 编码(而不是 64x13)不是更好吗?

标签: conv-neural-networkkeras-layersequential

解决方案


在 Dense 中,您只传递您期望的层数作为输出,如果您想要 (64x13) 作为输出,请将层尺寸设置为Dense(832)(64x13 = 832),然后再进行整形。您还需要重塑 Y 以便准确计算损失,这将用于反向传播。

# X.shape = (10000, 224, 224, 1)
# Y.shape = (10000, 64, 13)
Y = Y.reshape(10000, 64*13)
model = Sequential([
    Conv2D(8, (3,3), activation='relu', input_shape=(224, 224, 1)),
    Conv2D(8, (3,3), activation='relu'),
    # some more repetitive Conv + Pooling Layers here
    Flatten(),
    Dense(64*13)
])

那应该可以完成工作,如果它没有在失败的地方发布,我们可以继续进行。


推荐阅读