对于相同的输入和标签:
- 的输出
pytorch.nn.CTCLoss
为 5.74, - 的输出
tf.nn.ctc_loss
为 129.69, - 但输出
math.log(tf ctc loss)
是 4.86
pytorch.nn.CTCLoss
那么with 和有什么区别tf.nn.ctc_loss
?
tf: 1.13.1
pytorch: 1.1.0
我曾尝试过这些:
log_softmax
输入,然后将其发送到pytorch.nn.CTCLoss
,tf.nn.log_softmax
输入,然后将其发送到tf.nn.ctc_loss
直接将输入发送到
tf.nn.ctc_loss
直接将输入发送到
tf.nn.ctc_loss
, 然后math.log(output of tf.nn.ctc_loss)
在案例 2、案例 3 和案例 4 中,计算结果与pytorch.nn.CTCLoss
from torch import nn
import torch
import tensorflow as tf
import math
time_step = 50 # Input sequence length
vocab_size = 20 # Number of classes
batch_size = 16 # Batch size
target_sequence_length = 30 # Target sequence length
def dense_to_sparse(dense_tensor, sequence_length):
indices = tf.where(tf.sequence_mask(sequence_length))
values = tf.gather_nd(dense_tensor, indices)
shape = tf.shape(dense_tensor, out_type=tf.int64)
return tf.SparseTensor(indices, values, shape)
def compute_loss(x, y, x_len):
ctclosses = tf.nn.ctc_loss(
y,
tf.cast(x, dtype=tf.float32),
x_len,
preprocess_collapse_repeated=False,
ctc_merge_repeated=False,
ignore_longer_outputs_than_inputs=False
)
ctclosses = tf.reduce_mean(ctclosses)
with tf.Session() as sess:
ctclosses = sess.run(ctclosses)
print(f"tf ctc loss: {ctclosses}")
print(f"tf log(ctc loss): {math.log(ctclosses)}")
minimum_target_length = 10
ctc_loss = nn.CTCLoss(blank=vocab_size - 1)
x = torch.randn(time_step, batch_size, vocab_size) # [size] = T,N,C
y = torch.randint(0, vocab_size - 2, (batch_size, target_sequence_length), dtype=torch.long) # low, high, [size]
x_lengths = torch.full((batch_size,), time_step, dtype=torch.long) # Length of inputs
y_lengths = torch.randint(minimum_target_length, target_sequence_length, (batch_size,),
dtype=torch.long) # Length of targets can be variable (even if target sequences are constant length)
loss = ctc_loss(x.log_softmax(2).detach(), y, x_lengths, y_lengths)
print(f"torch ctc loss: {loss}")
x = x.numpy()
y = y.numpy()
x_lengths = x_lengths.numpy()
y_lengths = y_lengths.numpy()
x = tf.cast(x, dtype=tf.float32)
y = tf.cast(dense_to_sparse(y, y_lengths), dtype=tf.int32)
compute_loss(x, y, x_lengths)
我希望 的输出tf.nn.ctc_loss
与 的输出相同pytorch.nn.CTCLoss
,但实际上它们不是,但我怎样才能使它们相同?