tensorflow - Tensorflow 1.12 将 dataset.filter 应用于 dataset.window
问题描述
我有一个顺序数据集,我从中创建窗口以训练 RNN。在某些情况下,我想扔掉某些窗户。但是,当我使用dataset.window
后跟dataset.filter
管道内的东西中断时。这是一个玩具示例,有人可以告诉我如何正确执行此操作。这个玩具示例演示了我的问题。下面的代码创建大小为 4 的窗口,然后每批创建 4 个窗口。如果窗口中的最后一个元素是奇数,我想扔掉一个窗口,所以我的批次总是大小为 4,但批次中的窗口总是必须以事件元素结束。
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]))
解决方案
如果您查看过滤器方法中谓词的返回类型,您需要返回一个标量 tf bool 张量,我怀疑您的 Python 谓词不会发生这种情况。修改代码以返回这样的张量,给了我结果。
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]])]
等等
推荐阅读
- aem - AEM 6.5.3 - WCM IO 问题 - 在上下文感知配置页面上显示标签 ID 而不是标签值
- reactjs - 在可重用组件中呈现不同的 html
- flutter - 创建商店时测试加载失败
- python-3.x - How to extract the URL of a particular page using selenium/python?
- javascript - Node.js 中的管理员角色使用 Express Session
- c - 将数据从队列传输到数组
- python - 正则表达式代码与我想要的所有内容都不匹配
- python - 可变时间延迟定时器
- powerbi - 有没有办法限制用户访问 Power BI 仪表板,但允许他们通过连接到底层多维数据集来通过 excel 进行分析?
- c# - 将 .Net 4.8 EF6 SQL Server webapi 项目转换为 AWS RDS Aurora MySQL