簡體   English   中英

Keras 中的排名不匹配

[英]Rank mismatch in 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)應等於對數等級減 1(收到 2)。

這個錯誤究竟意味着什么,為什么我的張量組合可能是錯誤的?

編輯:我將 cross_entropy 從稀疏修改為密集: softmax_cross_entropy_with_logits_v2softmax_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/task:0/device:CPU:0"](_arg_input_4_0_1, Cast_9)]]

該錯誤意味着標簽 ( y_true ) 必須比 logits ( y_pred ) 少一維。

它還說您的y_pred是二維的,而您的y_true是二維的。

好吧,如果您的y_pred是 2D,那么您的y_true應該是 1D。

看起來您的模型輸出 6 個類,而您的y_pred形狀為(batch_size, 6) 因此,您的y_true必須是 shape (batch_size,)


現在,如果您的y_true是 one-hot,則不應使用“稀疏”,而應使用正常的交叉熵。

注意loss的形狀(在交叉熵之后),它可能是一維的,因為類維度可能已經折疊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM