如何在张量流中将字符串张量填充到目标长度

how to pad a string tensor to a target length in tensorflow

t = 'comcom.android.systemuicom.android.systemuicom.android.systemui'
def pad_trunc_shingle(t):
    shingle_max = 300
    actual_len = tf.strings.length(t).numpy()
    if actual_len > shingle_max:
        return tf.strings.substr(t, 0, shingle_max)
    else:
        return tf.strings.join(('#' * (shingle_max- actual_len) ,t))

这个函数可以工作:

<tf.Tensor: shape=(), dtype=string, numpy=b'#############################################################################################################################################################################################################################################comcom.android.systemuicom.android.systemuicom.android.systemui'>

但是,我使用这个函数的时候是dataset map函数。 它引发错误:

AttributeError: 'Tensor' object has no attribute 'numpy'

处理数据集映射函数时如何获取actual_len

tf 版本:2.3.1

您可以使用 tf.condtf.py_function。这行得通,但肯定有比我做的更简单的方法。

import tensorflow as tf


def joining(word, shin_max, act_len):
    return tf.strings.join([*tf.repeat('#', shin_max - act_len), word])

def substr(word, shin_max):
    return tf.strings.substr(word, 0, shin_max)

t = 'comcom.android.systemuicom.android.systemuicom.android.systemui'

def pad_trunc_shingle(t):
    shingle_max = 100
    actual_len = tf.strings.length(t)
    if_actual_longer = lambda: tf.py_function(joining, inp=[t, shingle_max, actual_len], Tout=[tf.string])
    if_word_longer = lambda: tf.py_function(substr, inp=[t, shingle_max], Tout=[tf.string])
    return tf.cond(actual_len < shingle_max, if_actual_longer, if_word_longer)
    
    
words = [t for i in range(10)]

ds = tf.data.Dataset.from_tensor_slices(words).map(pad_trunc_shingle)


next(iter(ds))
(<tf.Tensor: shape=(), dtype=string, numpy=b'#####################################comcom.android.systemuicom.android.systemuicom.android.systemui'>,)