Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you get length of a TensorFlow string?

Tags:

tensorflow

Is there any way to get length of a TensorFlow string within TensorFlow? For example, is there any function that returns the length of a = tf.constant("Hello everyone", tf.string) as 14 without passing the string back to Python.

like image 916
Ata Avatar asked Jul 05 '16 21:07

Ata


People also ask

How do you find the size of a tensor in Python?

Using size() method: The size() method returns the size of the self tensor. The returned value is a subclass of a tuple.

Can tensor be string?

Tensors often contain floats and ints, but have many other types, including: complex numbers. strings.

Does Tensorflow work with strings?

string data type. The basic TensorFlow tf. string dtype allows you to build tensors of byte strings. Unicode strings are utf-8 encoded by default.


2 Answers

This works for me:

x = tf.constant("Hello everyone")

# Launch the default graph.
with tf.Session() as sess:
    print(tf.size(tf.string_split([x],"")).eval())
like image 65
Forth Temple Avatar answered Nov 15 '22 08:11

Forth Temple


No such function exists as of TensorFlow version 0.9. However, you can use tf.py_func to run arbitrary Python functions over TensorFlow tensors. Here is one way to get length of a TensorFlow string :

def string_length(t):
  return tf.py_func(lambda p: [len(x) for x in p], [t], [tf.int64])[0]

a = tf.constant(["Hello everyone"], tf.string)
sess = tf.InteractiveSession()
sess.run(string_length(a))
like image 40
keveman Avatar answered Nov 15 '22 07:11

keveman