如何使用Tensorflow数据集管道进行可变长度输入?

时间:2018-05-14 12:04:15

标签: python tensorflow pipeline tensorflow-datasets

我正在使用不同长度的数字序列的数据集训练Tensorflow中的递归神经网络,并且一直在尝试使用tf.data API来创建有效的管道。但是,我似乎无法让这件事发挥作用

我的方法

我的数据集是一个形状为[10000, ?, 32, 2]的NumPy数组,它以.npy格式保存在我的磁盘上。这里?表示元素在第二维中具有可变长度。 10000表示数据集中的小批量数,32表示小批量的大小。

我正在使用np.load打开此数据集,我正在尝试使用tf.data.Dataset方法创建from_tensor_slices对象,但似乎只有在所有输入的Tensors都具有相同的形状!

我试过阅读docs,但他们只给出了一个非常简单的例子。

我的代码

所以numpy文件的生成如下 -

dataset = []
for i in xrange(num_items):
  #add an element of shape [?, 32, 2] to the list where `?` takes
  # a random value between [1, 40]
  dataset.append(generate_random_rnn_input())

with open('data.npy', 'w') as f:
  np.save(f, dataset)

下面给出的代码是我尝试创建tf.data.Dataset对象

# dataset_list is a list containing `num_items` number of itesm
# and each item has shape [?, 32, 2]
dataset_list = np.load('data.npy')

# error, this doesn't work!
dataset = tf.data.Dataset.from_tensor_slices(dataset_list)

我得到的错误是" TypeError:预期的二进制或unicode字符串,得到数组([[[0.0875,0。],..."

继续,仍然需要帮助!

所以我尝试了@ mrry的回答,我现在能够创建一个数据集对象。 然而,我无法使用迭代器迭代这个数据集,如教程中所述。这就是我现在的代码 -

dataset_list = np.load('data.npy')

dataset = tf.data.Dataset.from_generator(lambda: dataset_list, 
                                         dataset_list[0].dtype,
                                         tf.TensorShape([None, 32, 2]))

dataset = dataset.map(lambda x : tf.cast(x, tf.float32))

iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()

with tf.Session() as sess:
  print sess.run(next_element) # The code fails on this line

我得到的错误是AttributeError: 'numpy.dtype' object has no attribute 'as_numpy_dtype'。我完全不知道这意味着什么。

这是完整的堆栈跟踪 -

2018-05-15 04:19:25.559922: W tensorflow/core/framework/op_kernel.cc:1261] Unknown: exceptions.AttributeError: 'numpy.dtype' object has no attribute 'as_numpy_dtype'
Traceback (most recent call last):

  File "/home/vastolorde95/virtualenvs/thesis/local/lib/python2.7/site-packages/tensorflow/python/ops/script_ops.py", line 147, in __call__
    ret = func(*args)

  File "/home/vastolorde95/virtualenvs/thesis/local/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 378, in generator_py_func
    nest.flatten_up_to(output_types, values), flattened_types)

AttributeError: 'numpy.dtype' object has no attribute 'as_numpy_dtype'


2018-05-15 04:19:25.559989: W tensorflow/core/framework/op_kernel.cc:1273] OP_REQUIRES failed at iterator_ops.cc:891 : Unknown: exceptions.AttributeError: 'numpy.dtype' object has no attribute 'as_numpy_dtype'
Traceback (most recent call last):

  File "/home/vastolorde95/virtualenvs/thesis/local/lib/python2.7/site-packages/tensorflow/python/ops/script_ops.py", line 147, in __call__
    ret = func(*args)

  File "/home/vastolorde95/virtualenvs/thesis/local/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 378, in generator_py_func
    nest.flatten_up_to(output_types, values), flattened_types)

AttributeError: 'numpy.dtype' object has no attribute 'as_numpy_dtype'


     [[Node: PyFunc = PyFunc[Tin=[DT_INT64], Tout=[DT_DOUBLE], token="pyfunc_1"](arg0)]]
Traceback (most recent call last):
  File "pipeline_test.py", line 320, in <module>
    tf.app.run()
  File "/home/vastolorde95/virtualenvs/thesis/local/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 126, in run
    _sys.exit(main(argv))
  File "pipeline_test.py", line 316, in main
    train(FLAGS.num_training_iterations, FLAGS.report_interval, FLAGS.report_interval_verbose)
  File "pipeline_test.py", line 120, in train
    print(sess.run(next_element))
  File "/home/vastolorde95/virtualenvs/thesis/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 905, in run
    run_metadata_ptr)
  File "/home/vastolorde95/virtualenvs/thesis/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1140, in _run
    feed_dict_tensor, options, run_metadata)
  File "/home/vastolorde95/virtualenvs/thesis/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1321, in _do_run
    run_metadata)
  File "/home/vastolorde95/virtualenvs/thesis/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1340, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.UnknownError: exceptions.AttributeError: 'numpy.dtype' object has no attribute 'as_numpy_dtype'
Traceback (most recent call last):

  File "/home/vastolorde95/virtualenvs/thesis/local/lib/python2.7/site-packages/tensorflow/python/ops/script_ops.py", line 147, in __call__
    ret = func(*args)

  File "/home/vastolorde95/virtualenvs/thesis/local/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 378, in generator_py_func
    nest.flatten_up_to(output_types, values), flattened_types)

AttributeError: 'numpy.dtype' object has no attribute 'as_numpy_dtype'


     [[Node: PyFunc = PyFunc[Tin=[DT_INT64], Tout=[DT_DOUBLE], token="pyfunc_1"](arg0)]]
     [[Node: IteratorGetNext = IteratorGetNext[output_shapes=[[?,32,2]], output_types=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](OneShotIterator)]]

1 个答案:

答案 0 :(得分:3)

正如您所注意到的,tf.data.Dataset.from_tensor_slices()仅适用于可以转换为(密集)tf.Tensortf.SparseTensor的对象。将可变长度NumPy数据转换为Dataset的最简单方法是使用tf.data.Dataset.from_generator(),如下所示:

dataset = tf.data.Dataset.from_generator(lambda: dataset_list, 
                                         tf.as_dtype(dataset_list[0].dtype),
                                         tf.TensorShape([None, 32, 2]))