通过拥抱面标记器映射文本数据

时间:2020-05-02 05:54:21

标签: tensorflow tensorflow-datasets huggingface-transformers

我的编码函数如下所示:

from transformers import BertTokenizer, BertModel

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

def encode(texts, tokenizer=tokenizer, maxlen=10):
#     import pdb; pdb.set_trace()
    inputs = tokenizer.encode_plus(
        texts,
        return_tensors='tf',
        return_attention_masks=True, 
        return_token_type_ids=True,
        pad_to_max_length=True,
        max_length=maxlen
    )

    return inputs['input_ids'], inputs["token_type_ids"], inputs["attention_mask"]

我想通过以下方式对数据进行动态编码:

x_train = (tf.data.Dataset.from_tensor_slices(df_train.comment_text.astype(str).values)
           .map(encode))

但是,这会消除错误:

ValueError: Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers.

据我所知,当我在encode内设置断点时,是因为我要发送一个非numpy数组。如何使用张紧流字符串作为输入来使抱紧的脸部变形器发挥出色?

如果您需要一个虚拟数据框,则为:

df_train = pd.DataFrame({'comment_text': ['Today was a good day']*5})

我尝试过的

因此,我尝试使用from_generator,以便可以将字符串解析为encode_plus函数。但是,这不适用于TPU。

AUTO = tf.data.experimental.AUTOTUNE

def get_gen(df):
    def gen():
        for i in range(len(df)):
            yield encode(df.loc[i, 'comment_text']) , df.loc[i, 'toxic']
    return gen

shapes = ((tf.TensorShape([maxlen]), tf.TensorShape([maxlen]), tf.TensorShape([maxlen])), tf.TensorShape([]))

train_dataset = tf.data.Dataset.from_generator(
    get_gen(df_train),
    ((tf.int32, tf.int32, tf.int32), tf.int32),
    shapes
)
train_dataset = train_dataset.batch(BATCH_SIZE).prefetch(AUTO)

版本信息:

transformers.__version__, tf.__version__ => ('2.7.0', '2.1.0')

2 个答案:

答案 0 :(得分:2)

使用以下命令创建张量流数据集时:tf.data.Dataset.from_tensor_slices(df_train.comment_text.astype(str).values) tensorflow将您的字符串转换为字符串类型的张量,该张量不是tokenizer.encode_plus的可接受输入。就像错误消息说的那样,它仅接受a string, a list/tuple of strings or a list/tuple of integers。您可以通过在编码函数(输出:print(type(texts)))内添加一个<class 'tensorflow.python.framework.ops.Tensor'>来进行验证。

我不确定您的后续计划是什么,为什么需要tf.data.Dataset,但是您必须先对输入内容进行编码,然后再将其转换为tf.data.Dataset

import tensorflow as tf
from transformers import BertTokenizer, BertModel

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

texts = ['Today was a good day', 'Today was a bad day',
       'Today was a rainy day', 'Today was a sunny day',
       'Today was a cloudy day']


#inputs['input_ids'], inputs["token_type_ids"], inputs["attention_mask"]
inputs = tokenizer.batch_encode_plus(
        texts,
        return_tensors='tf',
        return_attention_masks=True, 
        return_token_type_ids=True,
        pad_to_max_length=True,
        max_length=10
    )

dataset = tf.data.Dataset.from_tensor_slices((inputs['input_ids'],
                                              inputs['attention_mask'],
                                              inputs['token_type_ids']))
print(type(dataset))

输出:

<class 'tensorflow.python.data.ops.dataset_ops.TensorSliceDataset'>

答案 1 :(得分:2)

bert的分词器可以处理字符串,字符串的列表/元组或整数的列表/元组。因此,请检查您的数据是否转换为字符串。为了在整个数据集上应用标记化器,我使用了Dataset.map,但这在图形模式下运行。因此,我需要将其包装在tf.py_function中。 tf.py_function将把常规张量(带有一个值和一个.numpy()方法来访问)传递给包装的python函数。使用py_function后,我的数据被转换为字节,因此我应用tf.compat.as_str将字节转换为字符串。

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
def encode(lang1, lang2):
    lang1 = tokenizer.encode(tf.compat.as_str(lang1.numpy()), add_special_tokens=True)
    lang2 = tokenizer.encode(tf.compat.as_str(lang2.numpy()), add_special_tokens=True)
    return lang1, lang2
def tf_encode(pt, en):
    result_pt, result_en = tf.py_function(func = encode, inp = [pt, en], Tout=[tf.int64, tf.int64])
    result_pt.set_shape([None])
    result_en.set_shape([None])
    return result_pt, result_en
train_dataset = dataset3.map(tf_encode)
BUFFER_SIZE = 200
BATCH_SIZE = 64

train_dataset = train_dataset.shuffle(BUFFER_SIZE).padded_batch(BATCH_SIZE, 
                                                           padded_shapes=(60, 60))
a,p = next(iter(train_dataset))