簡體   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