TensorFlow strings: what they are and how to work with them

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-18 12:56:12

问题


When I read file with tf.read_file I get something with type tf.string. Documentation says only that it is "Variable length byte arrays. Each element of a Tensor is a byte array." (https://www.tensorflow.org/versions/r0.10/resources/dims_types.html). I have no idea how to interpret this.

I can do nothing with this type. In usual python you can get elements by index like my_string[:4], but when I run following code I get an error.

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

It says

  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

Also I cannot convert my string to tf.float32 tensor. It is .flo file and it has magic header "PIEH". This numpy code successfuly convert such header into number (see example here https://stackoverflow.com/a/28016469/4744283) but I can't do that with tensorflow. I tried tf.string_to_number(string, out_type=tf.float32) but it says

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

So, what string is? What it's shape is? How can I at least get part of the string? I suppose that if I can get part of it I can just skip "PIEH" part.

UPD: I forgot to say that tf.slice(string, [0], [4]) also doesn't work with same error.


回答1:


Unlike Python, where a string can be treated as a list of characters for the purposes of slicing and such, TensorFlow's tf.strings are indivisible values. For instance, x below is a Tensor with shape (2,) whose each element is a variable length string.

x = tf.constant(["This is a string", "This is another string"])

However, to achieve what you want, TensorFlow provides the tf.decode_raw operator. It takes a tf.string tensor as input, but can decode the string into any other primitive data type. For instance, to interpret the string as a tensor of characters, you can do the following :

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]


来源:https://stackoverflow.com/questions/38902433/tensorflow-strings-what-they-are-and-how-to-work-with-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!