为了账号安全,请及时绑定邮箱和手机立即绑定

Keras ValueError:检查目标时出错:预期dense_1有3个维度

Keras ValueError:检查目标时出错:预期dense_1有3个维度

翻翻过去那场雪 2022-06-07 19:37:29
我正在使用带有 tensorflow 后端的 keras,并且在为我的模型确定图层的正确形状时遇到了问题。我已经阅读了关于各种 keras 层属性差异的有用解释。这是我的模型的架构:我正在尝试使用分类标签进行二元分类(逻辑回归),因此最后一层是具有 1 个单元的 Dense 层,我认为对于正类评估为 1,对于负类评估为 0。这是我的模型的总结:我在网络一侧的输入是 10158,另一侧是 20316。我总共有 1370 个样本。我的 train_data 的形状是 (1370, 1, 10158),标签的形状是 (1, 1370),批量大小是 100。input_layer = Input(shape=(1,no_terms), name='docs')s = Lambda(lambda x: x+1)(input_layer)log_layer = Lambda(log, name='tf_output')(input_layer)tpr_fpr = np.zeros((2, no_terms))tpr_fpr[0,:] = np.sum(train_docs[np.where(train_label>0), :]>0, axis=1                      )/np.sum(train_label>0) * (1000)tpr_fpr[1,:] = np.sum(train_docs[np.where(train_label>0), :]>0, axis=1                     )/np.sum(train_label <= 0) * (1000)k_constants = backend.constant(np.reshape(tpr_fpr.T, (1,2*no_terms)))fixed_input = Input(tensor=k_constants, shape=(1, 2*no_terms), name='tpr_fpr')h = Dense(int(300), activation='relu', name='hidden', input_shape=(1, 2*no_terms),           trainable=True)(fixed_input)h = Dropout(0.2, name="D")(h)cd = Dense(units=no_terms, activation='relu', name='cd', trainable=True)(h)prod = Multiply()([log_layer, cd])o = Lambda(lambda x:(x/backend.sqrt(backend.sum(x * x,axis=1,keepdims=True))))(prod)o = ReLU(max_value=None, negative_slope=0.0, threshold=0.0)(o)o = Dense(1, activation='sigmoid', input_shape=(no_terms,))(o)model_const = Model(fixed_input,cd)model = Model([input_layer, fixed_input], o)op = optimizers.RMSprop(learning_rate=.1, rho=0.9)model.compile(optimizer=op, loss=mean_squared_error, metrics=['accuracy'])plot_model(model, to_file='model.png')model.summary()batchSize = 100这是我得到的错误:“ValueError:检查目标时出错:预期dense_1有3个维度,但得到了形状为(1430、2)的数组”我不知道 (1430, 2) 形状指的是什么以及为什么会出现此错误。
查看完整描述

3 回答

?
繁星coding

TA贡献1797条经验 获得超4个赞

您确实确实直接解决了问题-方法如下:

  • Keras 二进制分类期望标签(“目标”)形状为(batch_size, 1). 原因:最后一层的目标是输出预测,将其与标签进行比较以计算指标(损失、准确性等) - 并且标签被塑造(batch_size, 1)

  • 以上也是问题所在 - 请参阅下面文档to_categorical中的片段;对于二进制分类,one-hot 编码是多余的,因为直接将标签与提供的预测进行比较binary_crossentropy

  • KerasDense期望输入是 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)


查看完整回答
反对 回复 2022-06-07
?
婷婷同学_

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),它是二进制而不是分类标签。


所以新的结构是: 

//img1.sycdn.imooc.com//629f38c50001fdfe06620482.jpg

我希望有人可以解释以前的模型有什么问题,所以我会避免再次犯同样的错误。



查看完整回答
反对 回复 2022-06-07
?
莫回无

TA贡献1865条经验 获得超7个赞

检查目标:预期dense_1有3维,但得到的数组形状为(1430, 2)"

这意味着 dense_1 有 3 个维度,但如果您在图像处理中设计此模型,则您的输入只有 2 个维度,在这种情况下,您已声明图像形状 yhat 为 ((48,48),1) & ((48,48),3 ) 这里 1 用于灰度,3 用于 rgb 图像


查看完整回答
反对 回复 2022-06-07
  • 3 回答
  • 0 关注
  • 231 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号