ValueError:使用tf.data.Dataset.from_tensor_slices

问题描述

这个问题已经在SO中发布了很多次,但是我仍然无法弄清楚我的代码有什么问题,特别是因为它来自medium中的一个教程,并且作者编写了代码可在Google colab

上使用

我看到其他用户在使用错误的变量类型#56304986时遇到了问题(这不是我的情况,因为我的模型输入是tokenizer输出),甚至看到了我正在尝试使用的函数tf.data.Dataset.from_tensor_slices)被建议作为解决方#56304986

行产生错误是:

# train dataset
ds_train_encoded = encode_examples(ds_train).shuffle(10000).batch(batch_size)

其中方法encode_examples定义为(我在assert方法中插入了encode_examples行,以确保我的问题不是长度不匹配):

def encode_examples(ds,limit=-1):
    # prepare list,so that we can build up final TensorFlow dataset from slices.
    input_ids_list = []
    token_type_ids_list = []
    attention_mask_list = []
    label_list = []
    if (limit > 0):
        ds = ds.take(limit)

    for review,label in tfds.as_numpy(ds):

            bert_input = convert_example_to_feature(review.decode())

            ii = bert_input['input_ids']
            tti = bert_input['token_type_ids']
            am = bert_input['attention_mask']

            assert len(ii) == len(tti) == len(am),"unmatching lengths!"

            input_ids_list.append(ii)
            token_type_ids_list.append(tti)
            attention_mask_list.append(am)
            label_list.append([label])

    return tf.data.Dataset.from_tensor_slices((input_ids_list,attention_mask_list,token_type_ids_list,label_list)).map(map_example_to_dict)

数据是这样加载的(这里我更改了数据集以仅获取10%的训练数据,以便加快调试速度)

(ds_train,ds_test),ds_info = tfds.load('imdb_reviews',split = ['train[:10%]','test[10%:15%]'],as_supervised=True,with_info=True)

另外两个调用convert_example_to_featuremap_example_to_dict)和令牌生成器如下:

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased',do_lower_case=True)
def convert_example_to_feature(text):
    # combine step for tokenization,WordPiece vector mapping,adding special tokens as well as truncating reviews longer than the max length
    return tokenizer.encode_plus(text,add_special_tokens = True,# add [CLS],[SEP]
                                 #max_length = max_length,# max length of the text that can go to BERT
                                 pad_to_max_length = True,# add [PAD] tokens
                                 return_attention_mask = True,)# add attention mask to not focus on pad tokens

def map_example_to_dict(input_ids,attention_masks,token_type_ids,label):
    return ({"input_ids": input_ids,"token_type_ids": token_type_ids,"attention_mask": attention_masks,},label)

我怀疑该错误可能与TensorFlow的不同版本有关(我使用的是2.3),但由于内存原因,我无法在google.colab笔记本中运行摘要

有人知道我的代码在哪里出问题吗?感谢您的时间和关注。

解决方法

事实证明我是通过注释该行引起麻烦的

#max_length = max_length,# max length of the text that can go to BERT

我假设它将截断模型的最大大小,或者将最长的输入作为最大大小。它什么都不做,然后即使我具有相同数量的条目,这些条目的大小也会变化,从而生成非矩形张量。

我删除了#,并使用512作为max_lenght。无论如何,这是BERT所能承受的最大费用。 (请参阅transformer's tokenizer class作为参考)

,

另一个可能的原因是应该在分词器中显式启用截断。参数为truncation = True