Tensorflow CTC损耗的填充标签?

时间:2018-03-02 06:36:55

标签: tensorflow

我想填充我的标签,以便它们具有相同的长度以传递到ctc_loss函数中。显然,-1是不允许的。如果我要应用填充,填充值是否应该是ctc标签的一部分?

更新

我有这个代码将密集标签转换为稀疏标签,然后传递给我认为与问题相关的ctc_loss函数。

def dense_to_sparse(dense_tensor, out_type):
    indices = tf.where(tf.not_equal(dense_tensor, tf.constant(0, dense_tensor.dtype)
    values = tf.gather_nd(dense_tensor, indices)
    shape = tf.shape(dense_tensor, out_type=out_type)
    return tf.SparseTensor(indices, values, shape)

2 个答案:

答案 0 :(得分:1)

以下是我的表现方式。我有一个密集的张量labels,其中包含填充-1,因此批处理中的所有目标都具有相同的长度。然后我用

labels_sparse = dense_to_sparse(labels, sparse_val=-1)

,其中

def dense_to_sparse(dense_tensor, sparse_val=0):
    """Inverse of tf.sparse_to_dense.

    Parameters:
        dense_tensor: The dense tensor. Duh.
        sparse_val: The value to "ignore": Occurrences of this value in the
                    dense tensor will not be represented in the sparse tensor.
                    NOTE: When/if later restoring this to a dense tensor, you
                    will probably want to choose this as the default value.
    Returns:
        SparseTensor equivalent to the dense input.
    """
    with tf.name_scope("dense_to_sparse"):
        sparse_inds = tf.where(tf.not_equal(dense_tensor, sparse_val),
                               name="sparse_inds")
        sparse_vals = tf.gather_nd(dense_tensor, sparse_inds,
                                   name="sparse_vals")
        dense_shape = tf.shape(dense_tensor, name="dense_shape",
                               out_type=tf.int64)
        return tf.SparseTensor(sparse_inds, sparse_vals, dense_shape)

这会创建标签的稀疏张量,这是您需要输入ctc损失的内容。也就是说,你调用tf.nn.ctc_loss(labels=labels_sparse, ...)填充(即密集张量中所有值等于-1)在这个稀疏张量中根本没有表示。

答案 1 :(得分:1)

实际上,ctc_batch_cost-1参数中可以存在y_true个值,但有一个限制-它们不应出现在由label_length(此处第i个标签“内容”将从索引0开始到索引label_length[i]结束)。

因此,最好用-1填充标签,以使它们的长度相等。您唯一需要注意的是正确计算并传递相应的label_length值。

这是示例代码,它是test_ctc unit test from keras的修改版本:

import numpy as np
from tensorflow.keras import backend as K

number_of_categories = 4
number_of_timesteps = 5

labels = np.asarray([[0, 1, 2, 1, 0], [0, 1, 1, 0, -1]])
label_lens = np.expand_dims(np.asarray([5, 4]), 1)

# dimensions are batch x time x categories
inputs = np.zeros((2, number_of_timesteps, number_of_categories), dtype=np.float32)
input_lens = np.expand_dims(np.asarray([5, 5]), 1)

k_labels = K.variable(labels, dtype="int32")
k_inputs = K.variable(inputs, dtype="float32")
k_input_lens = K.variable(input_lens, dtype="int32")
k_label_lens = K.variable(label_lens, dtype="int32")

res = K.eval(K.ctc_batch_cost(k_labels, k_inputs, k_input_lens, k_label_lens))

即使-1作为(第二个)labels序列的最后一个元素,它也可以很好地运行,因为相应的label_lens项(第二个)指定其长度为4。

如果我们将其更改为5或将其他标签值更改为-1,则您提到的All labels must be nonnegative integers例外。但这仅表示我们的label_lens无效。