2017-04-13 58 views
5

我正在尝试执行与tf.decode_raw相反的操作。如何创建一个encode_raw tensorflow函数?

一个例子会给出dtype = tf.float32的张量,我想要一个函数encode_raw(),它接受一个浮点张量并返回一个字符串类型的张量。

这很有用,因为我可以使用tf.write_file来写入文件。

有谁知道如何使用现有函数在Tensorflow中创建这样的功能?

回答

2

我会建议用tf.as_string作为文本编写数字。如果你真的想给他们写一个二进制字符串,然而,事实证明是可行的:

import tensorflow as tf 

with tf.Graph().as_default(): 
    character_lookup = tf.constant([chr(i) for i in range(256)]) 
    starting_dtype = tf.float32 
    starting_tensor = tf.random_normal(shape=[10, 10], stddev=1e5, 
            dtype=starting_dtype) 
    as_string = tf.reduce_join(
     tf.gather(character_lookup, 
       tf.cast(tf.bitcast(starting_tensor, tf.uint8), tf.int32))) 
    back_to_tensor = tf.reshape(tf.decode_raw(as_string, starting_dtype), 
           [10, 10]) # Shape information is lost 
    with tf.Session() as session: 
    before, after = session.run([starting_tensor, back_to_tensor]) 
    print(before - after) 

这对我打印全零的数组。

+0

它的工作原理!谢谢! –

1

对于那些与Python 3个工作:

CHR()具有在Python 3不同的行为改变与来自先前答案的代码所获得的字节输出。 更换这行代码

character_lookup = tf.constant([chr(i) for i in range(256)])

character_lookup = tf.constant([i.tobytes() for i in np.arange(256, dtype=np.uint8)])

修复此问题。

相关问题