python - ValueError:使用 tf.data.Dataset.from_tensor_slices 时无法将非矩形 Python 序列转换为张量
问题描述
此问题已在 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_feature
和map_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 的最大值。(请参阅转换器的标记器类以供参考)
推荐阅读
- python - 在python中自动调整数据框
- applescript - 如何在活动选项卡中保存显示的 PDF(不打印)?
- python - 在 sklearn VotingClassifier 上使用 pickle.load 时出错
- google-apps-script - 使用 IF 语句根据表单提交向单元格添加信息
- ruby-on-rails - RAILS_ENV 未按预期工作。环境怎么设置?
- c++ - 如何使用 C++ 中的 recv 或读取函数从 tcp 套接字读取大请求?
- sonos - GET 收藏夹/播放列表有时会返回 500
- angular - 角度变化检测仅检测产品中的变化
- syslog-ng - 远程 syslog 服务器在转发 apache 日志时未从 syslog-ng 获取 IP 地址
- android - 如何在不取消配对的情况下让两个 Android 设备连接到同一个蓝牙设备?