动态长度张量流平均

2024-10-01 00:14:06 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑到序列的实际长度,我试图做一个平均运算。(屏蔽零向量)

我的输入sequence_outpus为(批处理大小、最大长度、维度)

我有一个张量,它存储了批处理中每个序列的实际长度。我使用了来自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

我这样做:

^{pr2}$

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

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

谢谢!在


Tags: httpscomreducetf序列variable向量length
1条回答
网友
1楼 · 发布于 2024-10-01 00:14:06

我看不出问题。你的代码有点过于复杂。以下代码

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)

在这里运行得很好,没有任何南语。你确定你真的在用这个代码吗?如果我需要猜的话,我敢打赌你忘了序列长度计算中的tf.abs。在

注意:您的长度函数,以及本文中的tf_length,假设序列中有非零值!计算序列长度应该是数据生产者的任务,并输入到计算图中。其他一切,我都认为是一个老生常谈的解决办法。在

相关问题 更多 >