python - 将字典列表转换为 tf 数据集
问题描述
我有一本经过完全预处理的字典,可以输入到 BERT 模型中。但是,我正在努力将其放入 tf.dataset。这是我的数据集的一个元素的样子:
print(dataset[0])
{'input_ids': <tf.Tensor: shape=(128,), dtype=int64, numpy= array([ 101, 171, 112, 2537, 12293, 131, 11250, 118, 118,
2537, 12293, 131, 11250, 1110, 1126, 1237, 1778, 1326,
1687, 1111, 5957, 1398, 11737, 1118, 8129, 14399, 1105,
3230, 9426, 27277, 119, 1135, 1110, 1103, 1148, 1326,
1872, 4418, 1111, 1115, 1555, 117, 1105, 1103, 1148,
2537, 12293, 1326, 1290, 2537, 12293, 131, 9892, 4803,
1107, 1478, 119, 9617, 4986, 170, 4967, 1196, 1103,
1958, 1104, 1103, 1560, 2537, 12293, 1326, 1105, 2767,
1121, 1103, 21169, 1104, 1103, 18061, 1666, 2672, 2441,
117, 11250, 16001, 1103, 4245, 118, 118, 148, 1979,
1320, 1594, 1229, 1378, 1103, 3039, 1104, 1103, 6684,
11250, 119, 23886, 147, 119, 16218, 1105, 6619, 11679,
19644, 2145, 2867, 1112, 1437, 14627, 102, 171, 112,
1110, 1175, 170, 1207, 2851, 189, 14909, 1326, 1909,
112, 102])>, 'input_mask': <tf.Tensor: shape=(128,), dtype=int64, numpy= array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])>, 'segment_ids': <tf.Tensor: shape=(128,), dtype=int64, numpy= array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])>, 'labels': <tf.Tensor: shape=(), dtype=int64, numpy=1>}
我需要做的就是把它变成 tf.data.Dataset() 格式,但是,我似乎无法弄清楚如何使任何可用的功能from_tensor_slices, from_tensors, from_generator
与我所拥有的一起工作。
解决方案
您可以通过使用 pandas 来做到这一点(或者您可以模仿该to_dict
方法的输出)
dataset = tf.data.Dataset.from_tensor_slices(pd.DataFrame.from_dict(records).to_dict(orient="list"))
哪里records
是字典列表。
推荐阅读
- c - 为什么如果我重定向文件上的 STD_OUT 并写入 STD_OUT 文件仍然为空?
- r - 从列表中获取值并从中生成列名
- android - Android ScaleAnimation 是相对于当前大小而不是实际大小...如何解决?
- python - Numpy数组中某个轴的重复值的累积计数
- angular - 由于内容安全策略指令,无法在生产中的 Angular 应用程序中保存 PDF 文件
- c# - 在 F# 中,如何根据某些选项值是否为空来调用具有重载的构造函数?
- javascript - 如何实现基于嵌套数组的 UI?
- reactjs - 在 Redux + 本地存储中使用函数存储对象
- python - 在python中查找字符串中单词完全匹配的所有位置
- java - 无法从文件中读取有效负载