【问题标题】:TensorFlow Averaging with Dynamic Lengths具有动态长度的 TensorFlow 平均
【发布时间】:2016-12-07 06:48:01
【问题描述】:

考虑到序列的实际长度,我正在尝试进行平均操作。 (屏蔽零向量)

我的输入 sequence_outpus 是 (batch_size, max_len, dimensions)

我有一个张量,用于存储批次中每个序列的实际长度。我使用了https://danijar.com/variable-sequence-lengths-in-tensorflow/的函数

 def length(sequence):
     used = tf.sign(tf.reduce_max(tf.abs(sequence), reduction_indices=2))
     length = tf.reduce_sum(used, reduction_indices=1)
     length = tf.cast(length, tf.int64)
     return length

我这样做:

lengths = length(sequence_outputs)
lengths = tf.cast(length, tf.float32) 
lengths = tf.expand_dims(lengths,1)
sentence_outputs = tf.reduce_sum(sentence_outputs,1) / lengths

图表可以编译,但我得到的是 NaN 损失值。此外,在使用 eval() 进行调试时,我的长度变为负值。

这似乎是一个简单的问题,但我已经被这个问题困扰了一段时间,希望能得到一些帮助!

谢谢!

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    我认为没有问题。您的代码有点过于复杂。以下代码

    import numpy as np
    import tensorflow as tf
    
    # creating data
    B = 15
    MAX_LEN = 4
    data = np.zeros([B, MAX_LEN], dtype=np.float32)
    
    for b in range(B):
        current_len = np.random.randint(2, MAX_LEN)
        current_vector = np.concatenate([np.random.randn(current_len), np.zeros(MAX_LEN - current_len)], axis=-1)
        print("{}\t\t{}".format(current_vector, current_vector.shape))
        data[b, ...] = current_vector
    
    data_op = tf.convert_to_tensor(data)
    
    
    def tf_length(x):
        assert len(x.get_shape().as_list()) == 2
        length = tf.count_nonzero(x, axis=1, keepdims=True)
        return length
    
    
    x = tf.reduce_sum(data_op, axis=1) / tf_length(data_op)
    
    # test gradients
    grads = tf.gradients(tf.reduce_mean(x), [data_op])
    
    with tf.Session() as sess:
        print sess.run(grads)
    

    在没有任何 NaN 的情况下在这里运行得非常好。你确定,你真的在​​使用这个代码吗?如果我需要猜测,我敢打赌你会在序列长度计算中忘记tf.abs

    注意:您的长度函数以及本文中的tf_length,假定序列中的值非零!计算序列长度应该是数据生产者的任务并输入计算图中。其他一切,我认为是一个 hacky 解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      • 2017-09-28
      • 2018-10-03
      • 1970-01-01
      • 2018-02-09
      • 2012-08-16
      • 1970-01-01
      相关资源
      最近更新 更多