【问题标题】:how to pad a string tensor to a target length in tensorflow如何在张量流中将字符串张量填充到目标长度
【发布时间】:2021-01-14 07:13:25
【问题描述】:
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'>

然而,当我使用这个函数时,是数据集映射函数。 它引发错误:

AttributeError: 'Tensor' 对象没有属性 'numpy'

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

tf 版本:2.3.1

【问题讨论】:

    标签: python tensorflow tensorflow2.0 tensorflow-datasets


    【解决方案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'>,)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-20
      • 1970-01-01
      • 2017-11-05
      相关资源
      最近更新 更多