Tensorflow 1.12将dataset.filter应用于dataset.window

时间:2018-11-27 21:47:23

标签: tensorflow rnn tensorflow-datasets

我有一个顺序数据集,可从中创建窗口以训练RNN。在某些情况下,我想扔掉某些窗户。但是,当我使用dataset.window后接dataset.filter时,管道内部会中断。这是一个玩具示例,有人可以建议我如何正确执行此操作。这个玩具示例演示了我的问题。下面的代码创建大小为4的窗口,然后每批创建4个窗口的批处理。如果窗口中的最后一个元素为奇数,我想扔掉一个窗口,因此我的批次将始终为4,但是批次中的窗口始终必须以event元素结尾。

import tensorflow as tf
sess = tf.InteractiveSession()
ds = tf.data.Dataset.range(100)
ds = ds.window(size=4, shift=1,
               stride=1,
               drop_remainder=True).flat_map(lambda x: x.batch(4))

#*I want to keep the window if the last element in the window is even*
ds = ds.filter(lambda x: x[3] % 2 == 0) 

ds = ds.repeat()
ds = ds.batch(4, drop_remainder=True)
it = ds.make_one_shot_iterator()
data = it.get_next()
for i in range(100):
    print(sess.run([data]))
sess.close()

这会引发以下错误:

OutOfRangeError: End of sequence
     [[{{node IteratorGetNext_6}} = IteratorGetNext[output_shapes=[[4,?]], output_types=[DT_INT64], _device="/job:localhost/replica:0/task:0/device:CPU:0"](OneShotIterator_6)]]

During handling of the above exception, another exception occurred:

OutOfRangeError                           Traceback (most recent call last)
<ipython-input-54-d6d959b5be78> in <module>
      1 for i in range(100):
----> 2     print(sess.run([data]))

1 个答案:

答案 0 :(得分:2)

如果您在filter方法中查看谓词的返回类型,则需要返回标量tf bool张量,我怀疑您的pythonic谓词不会发生这种情况。修改代码以返回这样的张量,可以得到结果。

import tensorflow as tf
sess = tf.InteractiveSession()
ds = tf.data.Dataset.range(100)
ds = ds.window(size=4, shift=1,
               stride=1,
               drop_remainder=True).flat_map(lambda x: x.batch(4))

#*I want to keep the window if the last element in the window is even*
ds = ds.filter(lambda x: tf.equal(x[3] % 2, 0)) 

ds = ds.repeat()
ds = ds.batch(4, drop_remainder=True)
it = ds.make_one_shot_iterator()
data = it.get_next()
for i in range(100):
    print(sess.run([data]))
sess.close()

结果:

[array([[ 1,  2,  3,  4],
       [ 3,  4,  5,  6],
       [ 5,  6,  7,  8],
       [ 7,  8,  9, 10]])]
[array([[ 9, 10, 11, 12],
       [11, 12, 13, 14],
       [13, 14, 15, 16],
       [15, 16, 17, 18]])]
[array([[17, 18, 19, 20],
       [19, 20, 21, 22],
       [21, 22, 23, 24],
       [23, 24, 25, 26]])]
[array([[25, 26, 27, 28],
       [27, 28, 29, 30],
       [29, 30, 31, 32],
       [31, 32, 33, 34]])]
[array([[33, 34, 35, 36],
       [35, 36, 37, 38],
       [37, 38, 39, 40],
       [39, 40, 41, 42]])]

以此类推