首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python,TensorFlow,Keras: tf.data.Dataset只将令牌程序应用于一个轴,即放置轴

Python,TensorFlow,Keras: tf.data.Dataset只将令牌程序应用于一个轴,即放置轴
EN

Stack Overflow用户
提问于 2022-01-31 06:19:09
回答 1查看 135关注 0票数 1

我正在尝试构建一个tf.data.Dataset管道,用于读取16个选项卡分隔的.gzip文件,其中包括一个句子、一个无用的文件指示符和一个标签。我只想将令牌程序应用到数据集的第一个轴上。另外,我想要删除中轴--这里是我的代码:

代码语言:javascript
复制
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)

以下是数据:

代码语言:javascript
复制
>>> [print(a) for a in ds.take(2)]
tf.Tensor([b'Happy little sentence.'  b'Useless Text'  b'Label'], shape=(3,), dtype=string)

如果我可以删除('Happy little sentence.'),我想将我的令牌程序应用到张量'Useless Text'加成点的第一个轴上。以下是我不成功的方法:

代码语言:javascript
复制
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)

这代表了一切!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-31 06:32:54

假设在每个张量中总是有3个元素(一个句子、一个无用的文件指示符和一个标签),您可以尝试索引第一个和最后一个元素:

代码语言:javascript
复制
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)
代码语言:javascript
复制
(<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'>)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70921932

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档