繁体   English   中英

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

[英]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))

这个 function 可以工作:

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

但是,当我使用这个 function 是数据集 map function 时。 它引发错误:

AttributeError:“张量”object 没有属性“numpy”

处理数据集 map actual_len时如何获取 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'>,)

暂无
暂无

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

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