将TensorFlow字符串转换为python字符串

Ujj*_*wal 13 python tensorflow

我知道在TensorFlow中,tf.string张量基本上是一个字节字符串.我需要使用tf.train.string_input_producer()存储在队列中的文件名进行一些操作.

下面显示了一个小片段:

 key, value = reader.read(filename_queue)
 filename = value.eval(session=sess)
 print(filename)
Run Code Online (Sandbox Code Playgroud)

但是,作为字节字符串,它提供如下输出:

b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t\t\x08'
Run Code Online (Sandbox Code Playgroud)

我试着转换使用

filename = tf.decode_raw(filename, tf.uint8)
filename = ''.join(chr(i) for i in filename)
Run Code Online (Sandbox Code Playgroud)

但是Tensor对象不可迭代,因此失败.

我哪里错了?

它是TensorFlow中缺少的一个特性,tf.string可以很容易地转换为Python字符串,还是有其他一些我不知道的功能?

更多信息

filename_queue的编写如下:

train_set = ['file1.jpg', 'file2.jpg'] # Truncated for illustration
filename_queue = tf.train.string_input_producer(train_set, num_epochs=10, seed=0, capacity=1000)                  
Run Code Online (Sandbox Code Playgroud)

Aal*_*k_G 7

在 tensorflow 2.0.0 中,可以通过以下方式完成:

import tensorflow as tf

my_str = tf.constant('Hello World')
my_str_npy = my_str.numpy()

print(my_str_npy)
type(my_str_npy)
Run Code Online (Sandbox Code Playgroud)

这将字符串张量转换为“字节”类的字符串

  • AttributeError:'Tensor'对象在tensorflow 2.1.0中没有属性'numpy' (16认同)
  • 我可以确认上面的转换代码确实有效: `a = tf.constant('hello')` 后跟 `a.numpy().decode('ascii')` 将返回一个 TF2.2 的 python 字符串。但是,我认为这只适用于急切执行模式。例如,它在命令行下工作正常,但在定义图形时可能无法在图形模式下工作,但在执行图形时可以工作。 (3认同)
  • AttributeError:'Tensor'对象在tensorflow 2.2.0中没有属性'numpy' (2认同)

mxl*_*mxl 1

key, value = reader.read(filename_queue)
Run Code Online (Sandbox Code Playgroud)

在这里,Reader只是读取你给的文件,所以value是文件的内容,而不是文件名,但是你可以输出key,然后你得到文件名