首页 > 解决方案 > Keras 中的排名不匹配

问题描述

我有一种方法可以计算网络输出层与我在训练期间作为输入提供的输入目标标签之间的损失。我的代码如下所示:

def get_loss(y_pred, y_true):

   y_true = tf.cast(y_true, 'int32')
   loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y_true, logits=y_pred)
   # loss shape : <tf.Tensor 'softmax_cross_entropy_with_logits/Reshape_2:0' shape=(?,) dtype=float32>
   mask = tf.cast(tf.not_equal(y_true, 0), 'float32')
   loss = tf.reduce_sum(loss * mask, -1) / tf.reduce_sum(mask, -1)
   loss = K.mean(loss)
   return loss

src_seq_input = Input(shape=(None,), dtype='int32')
# <tf.Tensor 'input_1:0' shape=(?, ?) dtype=int32>
tgt_seq_input = Input(shape=(6,), dtype='int32')
# <tf.Tensor 'input_2:0' shape=(?, 6) dtype=int32>
enc_output = self.model(src_emb, src_seq, active_layers=active_layers)
# <tf.Tensor 'layer_normalization_5/add_1:0' shape=(?, 6) dtype=float32>
loss = get_loss(enc_output, tgt_seq_input)

当我尝试运行代码的最后一行时,我收到以下错误:

ValueError:排名不匹配:标签排名(收到 2)应等于 logits 排名减去 1(收到 2)。

这个错误到底意味着什么,为什么我的张量组合可能是错误的?

编辑: 我将 cross_entropy 从稀疏修改为密集:softmax_cross_entropy_with_logits_v2或者softmax_cross_entropy_with_logits现在我收到的错误如下:

*** tensorflow.python.framework.errors_impl.InvalidArgumentError:不兼容的形状:[32,6] vs. [32] [[{{node Equal_1}} = Equal[T=DT_INT32, _device="/job:localhost/replica :0/任务:0/设备:CPU:0"](_arg_input_4_0_1, Cast_9)]]

标签: pythonkeras

解决方案


该错误意味着标签 ( y_true) 必须比 logits ( y_pred) 少一维。

它还说你y_pred是二维的,你y_true是二维的。

好吧,如果你y_pred是二维的,那么你y_true应该是一维的。

看起来您的模型输出了 6 个类,而您的y_pred则是 shape (batch_size, 6)。因此,你y_true必须塑造(batch_size,)


现在,如果你y_true是一个热的,你不应该使用“稀疏”而只是一个正常的交叉熵。

注意loss(在交叉熵之后)的形状,它可能是一维的,因为类维度可能会合并。


推荐阅读