Python 如何将字符串张量(从.tfrecords获得)转换为浮点张量?
我的网络的输入来自包含int32的文件。它们存储为.tf记录,如下所示:Python 如何将字符串张量(从.tfrecords获得)转换为浮点张量?,python,tensorflow,Python,Tensorflow,我的网络的输入来自包含int32的文件。它们存储为.tf记录,如下所示: writer = tf.python_io.TFRecordWriter(output_file) with tf.gfile.FastGFile(file_path, 'rb') as f: data = f.read() example = tf.train.Example(features=tf.train.Features(feature={ 'data': tf.train.F
writer = tf.python_io.TFRecordWriter(output_file)
with tf.gfile.FastGFile(file_path, 'rb') as f:
data = f.read()
example = tf.train.Example(features=tf.train.Features(feature={
'data': tf.train.Feature(bytes_list=tf.train.BytesList(value=[data])) }))
writer.write(example.SerializeToString())
然后我像这样读取tfrecords文件:
with tf.name_scope(self.name):
filename_queue = tf.train.string_input_producer([path])
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
features={ 'data': tf.FixedLenFeature([], tf.string) })
data = features['data']
阅读TFR记录后,我得到如下字符串张量:
Tensor("X/ParseSingleExample/ParseSingleExample:0", shape=(), dtype=string)
我想首先将其转换为int32,因为这是初始数据所表示的。在那之后,我需要得到一个浮子张量,有人能给我指出正确的方向吗
PS我是tensorflow的新手,如果我能提供更多有用的信息,请告诉我。这应该会有所帮助
data = features['data']
decoded = tf.decode_raw(data, tf.int32)
这将输出dtypetf.int32
的张量。然后您可以对其进行重塑并将其转换为tf.float32
decoded = tf.reshape(decoded, shape)
decoded = tf.cast(decoded, tf.float32)
如果要在tf.Session
for str_rec in tf.python_io.tf_record_iterator('file.tfrecords'):
example = tf.train.Example()
example.ParseFromString(str_rec)
data_str = example.features.feature['data'].bytes_list.value[0])
decoded = np.fromstring(data_str, dtype)
要验证张量的内容,可以在图中插入一个打印节点,如下所述
您是使用
tf.parse\u single\u example
作为输入管道的一部分来读取tfrecords,还是只想使用tf.python\u io
api来检查它?请添加您的代码,以便我们可以帮助您更新问题,您可以考虑将数据直接存储为浮动向量,而不是每次重新解释它的负载。正如答案所指出的,应该会有所帮助,只要确保little_endian
参数正确即可。是的,数据流不是最佳的atm,baby steps;)感谢您的帮助,它似乎起到了作用。顺便问一下,我可以检查实际值吗?使用tf 1.7.1更新的问题,如果你没有会话就可以了。对不起,我应该更清楚,我指的是浮点张量的内容
# Add print operation
decoded = tf.Print(decoded, [decoded])