无法打印出tfrecord功能

时间:2018-06-09 18:26:13

标签: python tensorflow

我正在编写一个python代码来创建存储A和C作为功能的tfrecord文件,但是我无法从TFrecord文件中打印出A,C值。任何人都可以看看这个吗?

#Writing TFrecord file
import tensorflow as tf 
import numpy as np 

writer=tf.python_io.TFRecordWriter('output.tfrecord')

A=[1,3,4]
C=[1.1, 2.1, 3.1]


feature_A=tf.train.Feature(int64_list=tf.train.Int64List(value=A))
feature_C=tf.train.Feature(float_list=tf.train.FloatList(value=C))

features={'A':feature_A, 'C':feature_C}

example=tf.train.Example(features=tf.train.Features(feature=features))



writer.write(example.SerializeToString())
writer.close()


#Read TFrecord file    
import tensorflow as tf 

reader=tf.TFRecordReader()


filename_queue = tf.train.string_input_producer(
   ["output.tfrecord"])

_, serialized_example = reader.read(filename_queue)

feature_set = { 'A': tf.FixedLenFeature([], tf.int64),
               'C': tf.FixedLenFeature([], tf.float32)
           }

features = tf.parse_single_example( serialized_example, features= feature_set )
A=features['A']
C=features['C']

with tf.Session() as sess:
  print(sess.run([A,C])) # print out nothing 

1 个答案:

答案 0 :(得分:0)

有两个问题:

  1. FixedlenFeature必须定义大小。所以改为:

    feature_set = { 'A': tf.FixedLenFeature([3], tf.int64),
                    'C': tf.FixedLenFeature([3], tf.float32)}
    
  2. 您需要启动队列来读取输入,因此您的代码应如下所示:

    with tf.Session() as sess:
    
        # for the queues
        init_op = tf.local_variables_initializer()
        sess.run(init_op)
    
        # Create a coordinator, launch the queue runner threads.
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(sess=sess, coord=coord)
        try:
           for _ in range(1):
              print(sess.run([A,C]))
    
        except tf.errors.OutOfRangeError:
        # When done, ask the threads to stop.
        print('')
        finally:
           coord.request_stop()
           # Wait for threads to finish.
        coord.join(threads)