src
src

Reputation: 377

How to join a tensor of string tensors in tensorflow?

I am pretty sure I am missing something obvious, but is it not possible to join a one dimensional tensor of string tensors in tensorflow? The string_join operation only takes a list of tensors and I can't find a way to convert a tensor to a list:

>>> x = tf.string_join(['a', 'b'], '')
>>> sess.run(x)
b'ab'
>>> x = tf.string_join(tf.constant(['a', 'b']), '')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/digitalroots/anaconda2/envs/dl/lib/python3.6/site-packages/tensorflow/python/ops/gen_string_ops.py", line 164, in string_join
    separator=separator, name=name)
  File "/home/digitalroots/anaconda2/envs/dl/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 406, in apply_op
    (input_name, op_type_name, values))
TypeError: Expected list for 'inputs' argument to 'StringJoin' Op, not Tensor("Const:0", shape=(2,), dtype=string).

Upvotes: 3

Views: 3562

Answers (2)

src
src

Reputation: 377

A simpler approach could be to use reduce_join:

>>> value = tf.constant(['a','b'])
>>> x = tf.reduce_join(value)
>>> sess.run(x)
b'ab'

Upvotes: 5

openloop
openloop

Reputation: 91

Since the tf.string_join function expects the input the be an iterable, you could split the tensor first into its individual elements.

The num_or_size_splits attribute defines the number of tensors returned from tf.split().

value = tf.constant(['a','b'])
split = tf.split(value, num_or_size_splits = value.shape[0], axis = 0)
string = tf.string_join(split)

Upvotes: 2

Related Questions