【问题标题】:ValueError: Can't convert non-rectangular Python sequence to Tensor when using tf.data.Dataset.from_tensor_slicesValueError:使用 tf.data.Dataset.from_tensor_slices 时无法将非矩形 Python 序列转换为张量
【发布时间】:2020-09-15 17:31:42
【问题描述】:

此问题已在 SO 中发布过几次,但我仍然无法弄清楚我的代码有什么问题,尤其是因为它来自 medium 中的教程,并且作者提供了代码谷歌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 方法定义为(我在encode_examples 方法中插入了assert 行,以确保我的问题不是长度不匹配):

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 笔记本中运行 sn-ps。

有人知道我的代码有什么问题吗?感谢您的时间和关注。

【问题讨论】:

    标签: python tensorflow huggingface-transformers


    【解决方案1】:

    原来是我评论这行引起了麻烦

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

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

    我已删除 # 并使用 512 作为 max_lenght。无论如何,这是 BERT 的最大值。 (参考transformer's tokenizer class

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2019-10-11
        • 2020-08-03
        • 2021-07-23
        • 2019-02-04
        • 2018-04-23
        • 2021-06-02
        • 1970-01-01
        • 2023-04-08
        • 2021-10-19
        相关资源
        最近更新 更多