首页 > 解决方案 > 从文本和数字数据字典创建网络 - 训练 GNN

问题描述

根据这篇论文,我一直在使用FUNSD数据集来预测非结构化文档中的序列标签:LayoutLM: Pre-training of Text and Layout for Document Image Understanding。清理并从 dict 移动到数据框后 FUNSD 数据框的数据如下所示: 数据集布局如下:

我的目标是训练一个分类器来识别列'words'中使用图神经网络链接在一起的单词,第一步是能够将我当前的数据集转换为网络。我的问题如下:

  1. 有没有办法将列中的每一行'words'分成两列[box_word, text_word],每列仅用于一个单词,同时复制其他保持不变的列:[id, label, text, box],从而产生具有这些列的最终数据框:[box,text,label,box_word, text_word]

  2. 我可以标记列'text'text_word一个热编码列label,将具有多个数字的列拆分boxbox_word单独的列,但是如何拆分/重新排列列'linking'以定义我的网络图的边缘?

  3. 我在使用数据帧生成网络并使用它来训练 GNN 中是否采取了正确的路线?

感谢任何和所有帮助/提示。

标签: pythondictionarygraphnetworkxmultilabel-classification

解决方案


编辑:处理列中的多个条目words

您的问题 1 和 2 已在代码中得到解答。实际上很简单(假设数据格式由屏幕截图所示正确表示)。消化:

Q1:apply列上的拆分功能和解包方式.tolist(),可以创建单独的列。另见这篇文章

Q2:使用列表推导解包额外的列表层并仅保留非空边。

Q3:是的,不是的。是的,因为pandas擅长组织异构类型的数据。例如,列表、dict、int 和 float 可以出现在不同的列中。几个 I/O 函数,例如pd.read_csv()or pd.read_json(),也非常方便。

但是,数据访问存在开销,这对于遍历行(记录)尤其昂贵。因此,直接输入模型的转换数据通常会转换为numpy.array或更有效的格式。这样的格式转换任务是数据科学家的唯一责任。

代码和输出

我制作了自己的样本数据集。不相关的列被忽略(因为我没有义务也不应该这样做)。

import networkx as nx
import pandas as pd

# data
df = pd.DataFrame(
    data={
        "words": [
            [{"box": [1, 2, 3, 4], "text": "TO:"}, {"box": [7, 7, 7, 7], "text": "777"}],
            [{"box": [1, 2, 3, 4], "text": "TO:"}],
            [{"text": "TO:", "box": [1, 2, 3, 4]}, {"box": [4, 4, 4, 4], "text": "444"}],
            [{"text": "TO:", "box": [1, 2, 3, 4]}],
        ],
        "linking": [
            [[0, 4]],
            [],
            [[4, 6]],
            [[6, 0]],
        ]
    }
)


# Q1. split
def split(el):
    ls_box = []
    ls_text = []
    for dic in el:
        ls_box.append(dic["box"])
        ls_text.append(dic["text"])
    return ls_box, ls_text

# straightforward but receives a deprecation warning
df[["box_word", "text_word"]] = df["words"].apply(split).tolist()
# to avoid that,
ls_tup = df["words"].apply(split).tolist()  # len: 4x2
ls_tup_tr = list(map(list, zip(*ls_tup)))  # len: 2x4
df["box_word"] = ls_tup_tr[0]
df["text_word"] = ls_tup_tr[1]

# Q2. construct graph
ls_edges = [item[0] for item in df["linking"].values if len(item) > 0]
print(ls_edges)  # [[0, 4], [4, 6], [6, 0]]

g = nx.Graph()
g.add_edges_from(ls_edges)
list(g.nodes)  # [0, 4, 6]
list(g.edges)  # [(0, 4), (0, 6), (4, 6)]

Q1输出

# trim the first column for printing
df_show = df.__deepcopy__()
df_show["words"] = df_show["words"].apply(lambda s: str(s)[:10])
df_show

Out[51]: 
        words   linking                      box_word   text_word
0  [{'box': [  [[0, 4]]  [[1, 2, 3, 4], [7, 7, 7, 7]]  [TO:, 777]
1  [{'box': [        []                [[1, 2, 3, 4]]       [TO:]
2  [{'text':   [[4, 6]]  [[1, 2, 3, 4], [4, 4, 4, 4]]  [TO:, 444]
3  [{'text':   [[6, 0]]                [[1, 2, 3, 4]]       [TO:]

推荐阅读