简体   繁体   English

如何在张量流中加入字符串张量的张量?

[英]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? 我很确定我缺少明显的东西,但是在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: string_join操作仅采用张量列表 ,而我找不到将张量转换为列表的方法:

>>> 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).

Since the tf.string_join function expects the input the be an iterable, you could split the tensor first into its individual elements. 由于tf.string_join函数期望输入是可迭代的,因此您可以先将张量拆分为单独的元素。

The num_or_size_splits attribute defines the number of tensors returned from tf.split() . num_or_size_splits属性定义从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)

A simpler approach could be to use reduce_join : 一种更简单的方法是使用reduce_join

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM