python - 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)]]
解决方案
该错误意味着标签 ( 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
(在交叉熵之后)的形状,它可能是一维的,因为类维度可能会合并。
推荐阅读
- javascript - 连续遍历第 n 个长度的数组的最有效方法?
- vb.net - 如何选择数据表中的行?
- java - 应用程序不运行,但编译时没有错误
- android - 差异设备上的物料日期选择器差异格式
- java - 为什么我在运行时收到 java.lang.StringIndexOutOfBoundsException 错误?
- python - 类型错误:'在
' 需要字符串作为左操作数,而不是 NoneType - arrays - tableview 单元格添加说明第 0 节中的无效行数
- python - 为什么在 Pandas 中出现 KeyError 3
- javascript - Frida的代码在Android中调用时拦截通过函数传递的参数的值是什么
- ios - SwiftUI 更改状态不会关闭模态视图