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

我正在使用带有 tensorflow 后端的 keras,并且在为我的模型确定图层的正确形状时遇到了问题。

我已经阅读关于各种 keras 层属性差异的有用解释。

这是我的模型的架构:

http://img1.mukewang.com/629f388e0001e3d403240643.jpg

我正在尝试使用分类标签进行二元分类(逻辑回归),因此最后一层是具有 1 个单元的 Dense 层,我认为对于正类评估为 1,对于负类评估为 0。

这是我的模型的总结:

http://img2.mukewang.com/629f389a0001fde306570452.jpg

我在网络一侧的输入是 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) 形状指的是什么以及为什么会出现此错误。


翻翻过去那场雪
浏览 232回答 3
3回答

繁星coding

您确实确实直接解决了问题-方法如下:Keras 二进制分类期望标签(“目标”)形状为(batch_size, 1).&nbsp;原因:最后一层的目标是输出预测,将其与标签进行比较以计算指标(损失、准确性等) - 并且标签被塑造(batch_size, 1)以上也是问题所在 - 请参阅下面文档to_categorical中的片段;对于二进制分类,one-hot 编码是多余的,因为直接将标签与提供的预测进行比较binary_crossentropyKerasDense期望输入是 2D:&nbsp;(batch_size, input_dim).&nbsp;您的重塑使输入 3D:(batch_size, 1, input_dim)以上也是shape=(1, no_terms)-->shape=(no_terms,)帮助的原因;事实上,两者都适合您当时提供的数据形状。完整的批次形状仅包括批次暗淡:(batch_size, no_terms)(&nbsp;no_terms == input_dim)最后,对于二元分类,loss='binary_crossentropy'对分类问题使用 - 而不是均方误差(除非出于非常特殊的原因)# Consider an array of 5 labels out of a set of 3 classes {0, 1, 2}:> labelsarray([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.,&nbsp; 0.,&nbsp; 0.],&nbsp; &nbsp; &nbsp; &nbsp;[ 0.,&nbsp; 0.,&nbsp; 1.],&nbsp; &nbsp; &nbsp; &nbsp;[ 0.,&nbsp; 1.,&nbsp; 0.],&nbsp; &nbsp; &nbsp; &nbsp;[ 0.,&nbsp; 0.,&nbsp; 1.],&nbsp; &nbsp; &nbsp; &nbsp;[ 1.,&nbsp; 0.,&nbsp; 0.]], dtype=float32)

婷婷同学_

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

莫回无

检查目标:预期dense_1有3维,但得到的数组形状为(1430, 2)"这意味着 dense_1 有 3 个维度,但如果您在图像处理中设计此模型,则您的输入只有 2 个维度,在这种情况下,您已声明图像形状 yhat 为 ((48,48),1) & ((48,48),3 ) 这里 1 用于灰度,3 用于 rgb 图像
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python