TFRecords QueueRunner错误

时间:2017-02-01 22:17:57

标签: python tensorflow

我正在尝试将许多csv文件加载到单个TFRecord文件中,然后能够将TFRecord提供给我的模型。我下面是我的所有代码,我试图将其分解为我认为我在做什么。

生成数据..目标变量将是最后一列。

for i in range(10):
    filename = './Data/random_csv' + str(i) + '.csv'
    pd.DataFrame(np.random.randint(0,100,size=(100, 50))).to_csv(filename)

制作TFRecord档案的功能

def _int64_feature(value):
  return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

def _float_feature(value):
  return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))

def _bytes_feature(value):
  return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def make_q_list(filepathlist, filetype):
    filepathlist = filepathlist
    filepaths = []
    labels = []
    for path in filepathlist:
        data_files = os.listdir(path)
        for data in data_files:
            if data.endswith(filetype):
                data_file = os.path.join(path, data)
                data_file = data_file
                data_label = os.path.basename(os.path.normpath(path))
                filepaths.append(data_file)
                labels.append(data_label)

    return filepaths, labels

def rnn_list_format(df):
    input_data_list = []
    output_data_list = []
    y = df[df.columns[-1]]
    X = df[df.columns[:-1]]
    for i in range(len(df)):
        output_data_list.append(y.loc[i])
        input_data_list.append(X.loc[i].as_matrix())

    return input_data_list, output_data_list

def data_split(df):
    y = df[df.columns[-1]]
    X = df[df.columns[:-1]]
    X, y = X.as_matrix(), y.as_matrix()
    return X, y

将csvs加载到Pandas中的功能。然后取最后一列,使其成为我的目标变量y。 Pandas数据帧将转换为numpy数组并写入TFRecords文件。

def tables_to_TF(queue_list, tf_filename, file_type='csv'):
    #Target variable needs to be the last column of data
    filepath = os.path.join(tf_filename)
    print('Writing', filepath)
    writer = tf.python_io.TFRecordWriter(tf_filename)
    for file in tqdm(queue_list):
        if file_type == 'csv':
            data = pd.read_csv(file)
            X, y = data_split(data)
        elif file_type == 'hdf':
            data = pd.read_hdf(file)
            X, y = data_split(data)
        else:
            print(file_type, 'is not supported at this time...')
            break
        rec_count = X.shape[0]
        for index in range(rec_count):
            _X = np.asarray(X[index]).tostring()
            _y = np.asarray(y[index]).tostring()
            example = tf.train.Example(features=tf.train.Features(feature={
                'X': _bytes_feature(_X),
                'y': _bytes_feature(_y)}))
            writer.write(example.SerializeToString())

读取TFRecords文件的功能。

def read_and_decode(filename_queue, datashape=160*160*3):
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(
        serialized_example,
        features={
            'X': tf.FixedLenFeature([], tf.string),  
            'y': tf.FixedLenFeature([], tf.string)
        })

    X = tf.decode_raw(features['X'], tf.float32)
    X.set_shape([datashape])
    X = tf.cast(X, tf.float32)

    y = tf.decode_raw(features['y'], tf.float32)
    y.set_shape([1])
    y = tf.cast(y, tf.float32)

    return X, y

在Tensorflow中创建批次

def inputs(train_dir, file, batch_size, num_epochs, n_classes, one_hot_labels=False, datashape=160*160*3):

    if not num_epochs: num_epochs = None
    filename = os.path.join(train_dir, file)

    with tf.name_scope('input'):
        filename_queue = tf.train.string_input_producer(
            [filename], num_epochs=num_epochs)

        X, y = read_and_decode(filename_queue, datashape)

        if one_hot_labels:
            label = tf.one_hot(label, n_classes, dtype=tf.int32)

        example_batch, label_batch = tf.train.shuffle_batch(
            [X, y], batch_size=batch_size, num_threads=2,
            capacity=2000, enqueue_many=False,
            # Ensures a minimum amount of shuffling of examples.
            min_after_dequeue=1000, name=file)

    return example_batch, label_batch

根据创建的数据制作TFRecord文件。

filepathlist = ['./Data']
q, _ = make_q_list(filepathlist, '.csv')            
tffilename = 'Demo_TFR.tfrecords'
tables_to_TF(q, tffilename, file_type='csv')

尝试将TFRecord文件加载到queueRunner中。

X_train_batch, y_train_batch = inputs('./',
                                      'Demo_TFR.tfrecords',
                                      50,
                                      1,
                                      0,
                                      one_hot_labels=False,
                                      datashape=50)
sess = tf.Session()
init_op = tf.group(tf.global_variables_initializer())
sess.run(init_op)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
sess.run([X_train_batch, y_train_batch])

错误

    INFO:tensorflow:Error reported to Coordinator: <class 'tensorflow.python.framework.errors_impl.FailedPreconditionError'>, Attempting to use uninitialized value input/input_producer/limit_epochs/epochs
     [[Node: input/input_producer/limit_epochs/CountUpTo = CountUpTo[T=DT_INT64, _class=["loc:@input/input_producer/limit_epochs/epochs"], limit=1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/input_producer/limit_epochs/epochs)]]

Caused by op 'input/input_producer/limit_epochs/CountUpTo', defined at:
  File "/home/mcamp/anaconda3/lib/python3.5/runpy.py", line 184, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/mcamp/anaconda3/lib/python3.5/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/ipykernel/__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/ipykernel/kernelapp.py", line 474, in start
    ioloop.IOLoop.instance().start()
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tornado/ioloop.py", line 887, in start
    handler_func(fd_obj, events)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tornado/stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tornado/stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 390, in execute_request
    user_expressions, allow_stdin)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/ipykernel/zmqshell.py", line 501, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2717, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2821, in run_ast_nodes
    if self.run_code(code, result):
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-13-a00f528d3e80>", line 7, in <module>
    datashape=50)
  File "<ipython-input-11-468d0a66f589>", line 94, in inputs
    [filename], num_epochs=num_epochs)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/training/input.py", line 230, in string_input_producer
    cancel_op=cancel_op)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/training/input.py", line 156, in input_producer
    input_tensor = limit_epochs(input_tensor, num_epochs)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/training/input.py", line 96, in limit_epochs
    counter = epochs.count_up_to(num_epochs)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/variables.py", line 652, in count_up_to
    return state_ops.count_up_to(self._variable, limit=limit)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/gen_state_ops.py", line 126, in count_up_to
    result = _op_def_lib.apply_op("CountUpTo", ref=ref, limit=limit, name=name)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 759, in apply_op
    op_def=op_def)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 2240, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1128, in __init__
    self._traceback = _extract_stack()

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value input/input_producer/limit_epochs/epochs
     [[Node: input/input_producer/limit_epochs/CountUpTo = CountUpTo[T=DT_INT64, _class=["loc:@input/input_producer/limit_epochs/epochs"], limit=1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/input_producer/limit_epochs/epochs)]]

---------------------------------------------------------------------------
OutOfRangeError                           Traceback (most recent call last)
/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1020     try:
-> 1021       return fn(*args)
   1022     except errors.OpError as e:

/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1002                                  feed_dict, fetch_list, target_list,
-> 1003                                  status, run_metadata)
   1004 

/home/mcamp/anaconda3/lib/python3.5/contextlib.py in __exit__(self, type, value, traceback)
     65             try:
---> 66                 next(self.gen)
     67             except StopIteration:

/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py in raise_exception_on_not_ok_status()
    468           compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 469           pywrap_tensorflow.TF_GetCode(status))
    470   finally:

OutOfRangeError: RandomShuffleQueue '_7_input_1/Demo_TFR.tfrecords/random_shuffle_queue' is closed and has insufficient elements (requested 50, current size 0)
     [[Node: input_1/Demo_TFR.tfrecords = QueueDequeueMany[_class=["loc:@input_1/Demo_TFR.tfrecords/random_shuffle_queue"], component_types=[DT_FLOAT, DT_FLOAT], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input_1/Demo_TFR.tfrecords/random_shuffle_queue, input_1/Demo_TFR.tfrecords/n)]]

During handling of the above exception, another exception occurred:

OutOfRangeError                           Traceback (most recent call last)
<ipython-input-17-a00f528d3e80> in <module>()
     12 coord = tf.train.Coordinator()
     13 threads = tf.train.start_queue_runners(sess=sess, coord=coord)
---> 14 sess.run([X_train_batch, y_train_batch])

/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    764     try:
    765       result = self._run(None, fetches, feed_dict, options_ptr,
--> 766                          run_metadata_ptr)
    767       if run_metadata:
    768         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    962     if final_fetches or final_targets:
    963       results = self._do_run(handle, final_targets, final_fetches,
--> 964                              feed_dict_string, options, run_metadata)
    965     else:
    966       results = []

/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1012     if handle is None:
   1013       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1014                            target_list, options, run_metadata)
   1015     else:
   1016       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1032         except KeyError:
   1033           pass
-> 1034       raise type(e)(node_def, op, message)
   1035 
   1036   def _extend_graph(self):

OutOfRangeError: RandomShuffleQueue '_7_input_1/Demo_TFR.tfrecords/random_shuffle_queue' is closed and has insufficient elements (requested 50, current size 0)
     [[Node: input_1/Demo_TFR.tfrecords = QueueDequeueMany[_class=["loc:@input_1/Demo_TFR.tfrecords/random_shuffle_queue"], component_types=[DT_FLOAT, DT_FLOAT], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input_1/Demo_TFR.tfrecords/random_shuffle_queue, input_1/Demo_TFR.tfrecords/n)]]

Caused by op 'input_1/Demo_TFR.tfrecords', defined at:
  File "/home/mcamp/anaconda3/lib/python3.5/runpy.py", line 184, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/mcamp/anaconda3/lib/python3.5/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/ipykernel/__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/ipykernel/kernelapp.py", line 474, in start
    ioloop.IOLoop.instance().start()
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tornado/ioloop.py", line 887, in start
    handler_func(fd_obj, events)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tornado/stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tornado/stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 390, in execute_request
    user_expressions, allow_stdin)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/ipykernel/zmqshell.py", line 501, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2717, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2821, in run_ast_nodes
    if self.run_code(code, result):
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-17-a00f528d3e80>", line 7, in <module>
    datashape=50)
  File "<ipython-input-15-468d0a66f589>", line 105, in inputs
    min_after_dequeue=1000, name=file)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/training/input.py", line 917, in shuffle_batch
    dequeued = queue.dequeue_many(batch_size, name=name)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/data_flow_ops.py", line 458, in dequeue_many
    self._queue_ref, n=n, component_types=self._dtypes, name=name)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/gen_data_flow_ops.py", line 1099, in _queue_dequeue_many
    timeout_ms=timeout_ms, name=name)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 759, in apply_op
    op_def=op_def)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 2240, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/home/mcamp/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1128, in __init__
    self._traceback = _extract_stack()

OutOfRangeError (see above for traceback): RandomShuffleQueue '_7_input_1/Demo_TFR.tfrecords/random_shuffle_queue' is closed and has insufficient elements (requested 50, current size 0)
     [[Node: input_1/Demo_TFR.tfrecords = QueueDequeueMany[_class=["loc:@input_1/Demo_TFR.tfrecords/random_shuffle_queue"], component_types=[DT_FLOAT, DT_FLOAT], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input_1/Demo_TFR.tfrecords/random_shuffle_queue, input_1/Demo_TFR.tfrecords/n)]]

修改 以下代码似乎是问题的根本原因。我想我没有正确解析TFRecord文件(duh *)。我想也许我不是在读正确的数据类型。几乎完全相同的代码将图片读入TFRecord并退出..唯一的区别是我试图通过它发送float32值。

def read_and_decode(filename_queue, datashape=160*160*3):
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(
        serialized_example,
        features={
            'X': tf.FixedLenFeature([], tf.string),  
            'y': tf.FixedLenFeature([], tf.string)
        })

    X = tf.decode_raw(features['X'], tf.float32)
    X.set_shape([datashape])
    X = tf.cast(X, tf.float32)

    y = tf.decode_raw(features['y'], tf.float32)
    y.set_shape([1])
    y = tf.cast(y, tf.float32)

    return X, y

1 个答案:

答案 0 :(得分:0)

有很多东西要关注,所以我不确定,但最快的检查是你的“num_epochs”设置是否正确。达到纪元限制时会抛出那些OutOfRangeErrors。

相关问题