3 回答

TA贡献1797条经验 获得超4个赞
您确实确实直接解决了问题-方法如下:
Keras 二进制分类期望标签(“目标”)形状为
(batch_size, 1)
. 原因:最后一层的目标是输出预测,将其与标签进行比较以计算指标(损失、准确性等) - 并且标签被塑造(batch_size, 1)
以上也是问题所在 - 请参阅下面文档
to_categorical
中的片段;对于二进制分类,one-hot 编码是多余的,因为直接将标签与提供的预测进行比较binary_crossentropy
Keras
Dense
期望输入是 2D:(batch_size, input_dim)
. 您的重塑使输入 3D:(batch_size, 1, input_dim)
以上也是
shape=(1, no_terms)
-->shape=(no_terms,)
帮助的原因;事实上,两者都适合您当时提供的数据形状。完整的批次形状仅包括批次暗淡:(batch_size, no_terms)
(no_terms == input_dim
)最后,对于二元分类,
loss='binary_crossentropy'
对分类问题使用 - 而不是均方误差(除非出于非常特殊的原因)
# Consider an array of 5 labels out of a set of 3 classes {0, 1, 2}:
> labels
array([0, 2, 1, 2, 0])
# `to_categorical` converts this into a matrix with as many
# columns as there are classes. The number of rows
# stays the same.
> to_categorical(labels)
array([[ 1., 0., 0.],
[ 0., 0., 1.],
[ 0., 1., 0.],
[ 0., 0., 1.],
[ 1., 0., 0.]], dtype=float32)

TA贡献1844条经验 获得超8个赞
好吧,我找到了错误的解决方案,但仍然无法理解为什么以前的形状没有成功,坦率地说,这个修复在无数次尝试和错误中取得了成功。
我将以下图层输入从形状格式 (1, x) 更改为 (x,) 格式:
input_layer = Input(shape=(no_terms,), name='docs')
k_constants = backend.constant(np.reshape(tpr_fpr.T, (1,2*no_terms)))
fixed_input = Input(tensor=k_constants, shape=(2*no_terms,), name='tpr_fpr')
h = Dense(int(300), activation='relu', name='hidden', input_shape=(2*no_terms,), trainable=True)(fixed_input)
o = ReLU(max_value=None, negative_slope=0.0, threshold=0.0)(o)
o = Dense(1, activation='sigmoid', input_shape=(no_terms,))(o)
并且还从代码中删除了以下几行:
train_docs.shape = (train_docs.shape[0], 1, train_docs.shape[1])
train_label = to_categorical(train_label, num_classes=2, dtype='float32')
现在我只使用形状标签 (#no_of_samples, 1),它是二进制而不是分类标签。
所以新的结构是:
我希望有人可以解释以前的模型有什么问题,所以我会避免再次犯同样的错误。

TA贡献1865条经验 获得超7个赞
检查目标:预期dense_1有3维,但得到的数组形状为(1430, 2)"
这意味着 dense_1 有 3 个维度,但如果您在图像处理中设计此模型,则您的输入只有 2 个维度,在这种情况下,您已声明图像形状 yhat 为 ((48,48),1) & ((48,48),3 ) 这里 1 用于灰度,3 用于 rgb 图像
添加回答
举报