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

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

这是我的模型的体系结构:

python - Keras ValueError:检查目标时出错:预期density_1具有3维-LMLPHP

我正在尝试使用分类标签进行二进制分类(逻辑回归),因此最后一层是具有1个单位的密集层,我认为对于正值类别,其值为1,对于负值类别,其值为0。

这是我模型的摘要:

python - Keras ValueError:检查目标时出错:预期density_1具有3维-LMLPHP

我在网的一侧输入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

checkpoint = ModelCheckpoint(filepath="a.hdf5",monitor='val_acc', mode='max',
                             save_best_only=True)
earlystop=EarlyStopping(monitor='val_loss', patience=20)

train_docs.shape = (train_docs.shape[0], 1, train_docs.shape[1])
train_label = to_categorical(train_label, num_classes=2, dtype='float32')
model.fit(train_docs, train_label, epochs=10, batch_size=batchSize,
          validation_data=(test_docs, test_label),
          callbacks=[earlystop, checkpoint], verbose=1)


这是我得到的错误:
““ ValueError:检查目标时出错:预期density_1具有3维,但数组的形状为(1430,2)”

我不知道(1430,2)形状是什么意思,为什么会出现此错误。

最佳答案

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


Keras二进制分类期望标签(“目标”)的形状为(batch_size, 1)。原因:最后一层的目标是输出预测,将预测结果与标签进行比较以计算指标(损耗,准确性等)-标签形状为(batch_size, 1)
上面也是to_categorical问题的原因-请参见下面docs中的代码段;对于二进制分类,单次编码是多余的,因为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)

10-07 13:28
查看更多