在标记标记任务中,我使用transformers标记器,它输出BatchEncoding类的对象.

以下是代码的主要部分:

tokenizer = BertTokenizerFast.from_pretrained('bert-base-multilingual-uncased')

def extract_labels(raw_text):
  # split text into words and extract label
  (...)
  return clean_words, labels


def tokenize_text(words, labels):

  # tokenize text
  tokens = tokenizer(words, is_split_into_words=True, padding='max_length', truncation=True, max_length=MAX_LENGTH)
  
  # since words might be split into subwords, labels need to be re-arranged
  # only the first subword has the label
  (...)
  tokens['labels'] = label_ids

  return tokens



tokens = []
for raw_text in data:
  clean_text, l = extract_labels(raw_text)
  t = tokenize_text(clean_text, l)
  tokens.append(t)


type(tokens[0])
# transformers.tokenization_utils_base.BatchEncoding
tokens[0]
# {'input_ids': [101, 69887, 10112, ..., 0, 0, 0], 'attention_mask': [1, 1, 1, ... 0, 0, 0], 'labels': [-100, 0, -100, ..., -100, -100, -100]}

Update,正如所问,一个基本的例子来重现:

from transformers import BertTokenizerFast
import tensorflow as tf
tokenizer = BertTokenizerFast.from_pretrained('bert-base-multilingual-uncased')
tokens = []
for text in ["Hello there", "Good morning"]:
  t = tokenizer(text.split(), is_split_into_words=True, padding='max_length', truncation=True, max_length=10)
  t['labels'] = list(map(lambda x: 1, t.word_ids())) # fake labels to simplify example
  tokens.append(t)

print(type(tokens[0])) # now tokens is a list of BatchEncodings
print(tokens)

如果我直接标记整个数据集,我会有一个包含所有内容的BatchEncoding,但我无法处理标签:

data = ["Hello there", "Good morning"]
tokens = tokenizer(data,  padding='max_length', truncation=True, max_length=10)
# now tokens is a batch encoding comprising all the dataset
print(type(tokens))
print(tokens)
# This way I can get a tf dataset like this:
tf.data.Dataset.from_tensor_slices(tokens)

注意,我需要首先迭代文本以获得标签,并且需要每个文本的word\u id()来重新排列标签.

推荐答案

你有几个 Select .您可以使用defaultdict:

from collections import defaultdict
import tensorflow as tf

result = defaultdict(list)
for d in tokens:
    for k, v in d.items():
        result[k].append(v)

dataset = tf.data.Dataset.from_tensor_slices(dict(result))

或者可以使用pandas,如图here所示:

import pandas as pd
import tensorflow as tf

dataset = tf.data.Dataset.from_tensor_slices(pd.DataFrame.from_dict(tokens).to_dict(orient="list"))

或者在预处理数据时创建正确的 struct :

from transformers import BertTokenizerFast
from collections import defaultdict
import tensorflow as tf

tokenizer = BertTokenizerFast.from_pretrained('bert-base-multilingual-uncased')
tokens = defaultdict(list)
for text in ["Hello there", "Good morning"]:
  t = tokenizer(text.split(), is_split_into_words=True, padding='max_length', truncation=True, max_length=10)
  tokens['input_ids'].append(t['input_ids'])
  tokens['token_type_ids'].append(t['token_type_ids'])
  tokens['attention_mask'].append(t['attention_mask'])
  t['labels'] = list(map(lambda x: 1, t.word_ids())) # fake labels to simplify example
  tokens['labels'].append(t['labels'])

dataset = tf.data.Dataset.from_tensor_slices(dict(tokens))
for x in dataset:
  print(x)
{'input_ids': <tf.Tensor: shape=(10,), dtype=int32, numpy=
array([  101, 29155, 10768,   102,     0,     0,     0,     0,     0,
           0], dtype=int32)>, 'token_type_ids': <tf.Tensor: shape=(10,), dtype=int32, numpy=array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)>, 'attention_mask': <tf.Tensor: shape=(10,), dtype=int32, numpy=array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0], dtype=int32)>, 'labels': <tf.Tensor: shape=(10,), dtype=int32, numpy=array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)>}
{'input_ids': <tf.Tensor: shape=(10,), dtype=int32, numpy=
array([  101, 12050, 17577,   102,     0,     0,     0,     0,     0,
           0], dtype=int32)>, 'token_type_ids': <tf.Tensor: shape=(10,), dtype=int32, numpy=array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)>, 'attention_mask': <tf.Tensor: shape=(10,), dtype=int32, numpy=array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0], dtype=int32)>, 'labels': <tf.Tensor: shape=(10,), dtype=int32, numpy=array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)>}

Python相关问答推荐

Python—压缩叶 map html作为邮箱附件并通过sendgrid发送

OpenGL仅渲染第二个三角形,第一个三角形不可见

使用Python异步地持久跟踪用户输入

GPT python SDK引入了大量开销/错误超时

仅使用预先计算的排序获取排序元素

如何在Gekko中处理跨矢量优化

如何使用matplotlib查看并列直方图

你能把函数的返回类型用作其他地方的类型吗?'

为什么在Python中00是一个有效的整数?

用LAKEF划分实木地板AWS Wrangler

更新包含整数范围的列表中的第一个元素

根据边界点的属性将图划分为子图

简化通用属性的创建

使用Python下载pdf url

Python:打开名称中带有最新时间戳的特定文件

收到Firebase推送通知时,电话不会震动

导入pythoncom如何找到正确的文件?

.pth文件如何区分带有路径信息的行和带有Python代码的行?

支持向量机模型突出错误的数据点作为支持向量

如果没有强制转换Numy数组,则通过ctype将Numy数组传递给C函数会产生错误的结果