[英]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))
This function can work:这个 function 可以工作:
<tf.Tensor: shape=(), dtype=string, numpy=b'#############################################################################################################################################################################################################################################comcom.android.systemuicom.android.systemuicom.android.systemui'>
However, when I use this function is dataset map function.但是,当我使用这个 function 是数据集 map function 时。 It raises error:它引发错误:
AttributeError: 'Tensor' object has no attribute 'numpy' AttributeError:“张量”object 没有属性“numpy”
How can I get the actual_len
when processing dataset map function?处理数据集 map actual_len
时如何获取 actual_len?
tf version: 2.3.1 tf 版本:2.3.1
You can use tf.cond
and tf.py_function
.您可以使用tf.cond
和tf.py_function
。 This works but there's definitely an easier way than what I did.这行得通,但肯定有比我做的更简单的方法。
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.