tensorflow:根据某个分隔符拆分张量

tensorflow:根据某个分隔符拆分张量,tensorflow,Tensorflow,假设我有一个张量,比如: ts = tf.constant([1,2,3,-1,3,4,5,-1,2]) 如何将张量拆分为一个以-1为分隔符的张量列表,并获得以下结果 tf.constant([1,2,3]) tf.constant([3,4,5]) tf.constant([1,2]) 您可以将常量转换为字符串,然后将其作为字符串拆分为所需的片段,然后再将其转换回数字列表: 以下是切片步骤: import tensorflow as tf ts = tf.constant([1,2,3,

假设我有一个张量,比如:

ts = tf.constant([1,2,3,-1,3,4,5,-1,2])
如何将张量拆分为一个以
-1
为分隔符的张量列表,并获得以下结果

tf.constant([1,2,3])
tf.constant([3,4,5])
tf.constant([1,2])

您可以将常量转换为字符串,然后将其作为字符串拆分为所需的片段,然后再将其转换回数字列表:

以下是切片步骤:

import tensorflow as tf

ts = tf.constant([1,2,3,-1,3,4,5,-1,2])
ts_slices = 
    tf.string_split(tf.reshape(tf.reduce_join(tf.as_string(ts)), 
    [-1]), delimiter='-1')
sess = tf.Session()
sess.run(ts_slices.values)
这将为您提供:

array([b'23', b'345', b'2'], dtype=object)
现在您可以再次转换为整数


我不确定这是否是解决这个问题的最好办法,但至少它会解决你的问题

部分解决方案,您必须提前指定块的数量。希望这仍然有帮助

代码(已测试):

产出:

[[array([1,2,3],dtype=int32),
数组([3,4,5],dtype=int32),
数组([1,2],dtype=int32)]]


借用Sabine Maennel的答案,这里有一个完整的解决方案:

import tensorflow as tf

def split_by_delimiter(ts, delimiter):
    """Split a tensor similarly to python's `str.split` method."""
    ts_str = tf.reshape(tf.reduce_join(tf.as_string(ts), separator=' '), [-1])
    ts_slices = tf.string_split(
        tf.string_split(ts_str, delimiter=str(delimiter)).values)

    result = tf.SparseTensor(
        ts_slices.indices,
        tf.string_to_number(ts_slices.values, out_type=tf.int64),
        ts_slices.dense_shape)

    return tf.sparse_tensor_to_dense(result)

此解决方案将丢失第一个块上的前导1。
import tensorflow as tf

def split_by_delimiter(ts, delimiter):
    """Split a tensor similarly to python's `str.split` method."""
    ts_str = tf.reshape(tf.reduce_join(tf.as_string(ts), separator=' '), [-1])
    ts_slices = tf.string_split(
        tf.string_split(ts_str, delimiter=str(delimiter)).values)

    result = tf.SparseTensor(
        ts_slices.indices,
        tf.string_to_number(ts_slices.values, out_type=tf.int64),
        ts_slices.dense_shape)

    return tf.sparse_tensor_to_dense(result)