首页 > 解决方案 > 将字典列表转换为 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与我所拥有的一起工作。

标签: pythontensorflowdatasetpreprocessor

解决方案


您可以通过使用 pandas 来做到这一点(或者您可以模仿该to_dict方法的输出)

dataset = tf.data.Dataset.from_tensor_slices(pd.DataFrame.from_dict(records).to_dict(orient="list"))

哪里records是字典列表。


推荐阅读