TensorFlow字符串:它们是什么以及如何使用它们

cko*_*hik 15 python string numpy tensorflow tfrecord

当我读取文件时,tf.read_file我得到了类型的东西tf.string.文档只说它是"可变长度字节数组.Tensor的每个元素都是一个字节数组." (https://www.tensorflow.org/versions/r0.10/resources/dims_types.html).我不知道如何解释这个.

我对这种类型无能为力.在通常的python中你可以通过索引获取元素my_string[:4],但是当我运行以下代码时,我得到一个错误.

import tensorflow as tf
import numpy as np

x = tf.constant("This is string")
y = x[:4]


init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
result = sess.run(y)
print result
Run Code Online (Sandbox Code Playgroud)

它说

  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_shape.py", line 621, in assert_has_rank
    raise ValueError("Shape %s must have rank %d" % (self, rank))
ValueError: Shape () must have rank 1

我也无法将我的字符串转换为tf.float32张量.它是.flo文件,它有魔术标题"PIEH".这个numpy代码成功地将这样的头转换为数字(参见这里的例子/sf/answers/1961152861/)但我不能用tensorflow做到这一点.我试过tf.string_to_number(string, out_type=tf.float32)但它说

tensorflow.python.framework.errors.InvalidArgumentError: StringToNumberOp could not correctly convert string: PIEH

那么,字符串是什么?它的形状是什么?我怎么能至少得到一部分字符串?我想如果我可以参与其中,我可以跳过"PIEH"部分.

UPD:我忘了说tf.slice(string, [0], [4])也没有同样的错误.

kev*_*man 17

与Python不同,其中字符串可以被视为用于切片等的字符列表,TensorFlow tf.string是不可分割的值.例如,x下面是一个Tensorwith形状,(2,)其每个元素是一个可变长度的字符串.

x = tf.constant(["This is a string", "This is another string"])
Run Code Online (Sandbox Code Playgroud)

但是,要实现您的目标,TensorFlow为tf.decode_raw操作员提供服务.它需要tf.string张量作为输入,但可以将字符串解码为任何其他原始数据类型.例如,要将字符串解释为字符张量,可以执行以下操作:

x = tf.constant("This is string")
x = tf.decode_raw(x, tf.uint8)
y = x[:4]
sess = tf.InteractiveSession()
print(y.eval())
# prints [ 84 104 105 115]
Run Code Online (Sandbox Code Playgroud)