我正在尝试构建一个tf.data.Dataset
管道,该管道读取16个以制表符分隔的.gzip
文件,其中包括一个句子、一个无用的文件指示符和一个标签。我只想将标记化器应用于数据集的第一个轴。此外,我很想去掉中轴线这是我的代码:
ds = tf.data.Dataset.list_files("references/reads/*.txt.gz")
ds = tf.data.TextLineDataset(filenames=ds, compression_type="GZIP", num_parallel_reads=tf.data.experimental.AUTOTUNE)
ds = ds.map(lambda x: tf.strings.split(x, "t"), num_parallel_calls=tf.data.experimental.AUTOTUNE)
数据如下:
>>> [print(a) for a in ds.take(2)]
tf.Tensor([b'Happy little sentence.' b'Useless Text' b'Label'], shape=(3,), dtype=string)
如果我可以删除'Useless Text'
,我想只将我的标记化器应用于张量('Happy little sentence.')
的第一个轴。这是我不成功的方法:
with open('my_tokenizer.model', 'rb') as f_in:
model = f_in.read()
s = text.SentencepieceTokenizer(model=model)
ds = ds.map(lambda x: s.tokenize(x), num_parallel_calls=tf.data.experimental.AUTOTUNE)
这标志着一切!
假设每个张量中总是有3个元素(一个句子、一个无用的文件指示符和一个标签(,则可以尝试索引第一个和最后一个元素:
import tensorflow as tf
import tensorflow_text as tf_text
import requests
url = "https://github.com/tensorflow/text/blob/master/tensorflow_text/python/ops/test_data/test_oss_model.model?raw=true"
model = requests.get(url).content
ds = tf.data.Dataset.from_tensor_slices(([['Happy little sentence.', 'Useless Text', 'Faust'],
['Happy little sentence1.', 'Useless Text1', 'Faust1'],
['Happy little sentence2.', 'Useless Text2', 'Faust2']]))
s = tf_text.SentencepieceTokenizer(model=model)
def transform_data(x):
return s.tokenize(x[0]), x[2]
ds = ds.map(transform_data, num_parallel_calls=tf.data.experimental.AUTOTUNE)
for d in ds:
print(d)
(<tf.Tensor: shape=(11,), dtype=int32, numpy=array([ 4, 165, 19, 29, 29, 34, 544, 331, 15, 256, 6], dtype=int32)>, <tf.Tensor: shape=(), dtype=string, numpy=b'Faust'>)
(<tf.Tensor: shape=(12,), dtype=int32, numpy=
array([ 4, 165, 19, 29, 29, 34, 544, 331, 15, 256, 357, 6],
dtype=int32)>, <tf.Tensor: shape=(), dtype=string, numpy=b'Faust1'>)
(<tf.Tensor: shape=(12,), dtype=int32, numpy=
array([ 4, 165, 19, 29, 29, 34, 544, 331, 15, 256, 596, 6],
dtype=int32)>, <tf.Tensor: shape=(), dtype=string, numpy=b'Faust2'>)