python - 从文本和数字数据字典创建网络 - 训练 GNN
问题描述
根据这篇论文,我一直在使用FUNSD数据集来预测非结构化文档中的序列标签:LayoutLM: Pre-training of Text and Layout for Document Image Understanding。清理并从 dict 移动到数据框后 的数据如下所示: 数据集布局如下:
- 列
id
是文档中每个词组的唯一标识符 ,显示在列中text
(如节点) - 该列
label
标识词组是分类为“问题”还是“答案” linking
表示“链接”的词组(如边缘)的列,将相应的“问题”链接到“答案”- 表示词组
相对于左上角 (0.0)
'box'
的位置坐标 (x,y 左上角, x,y 右下角) 的列。 - Column
'words'
包含wordgroup 中的每个单词及其位置(框)。
我的目标是训练一个分类器来识别列'words'
中使用图神经网络链接在一起的单词,第一步是能够将我当前的数据集转换为网络。我的问题如下:
有没有办法将列中的每一行
'words'
分成两列[box_word, text_word]
,每列仅用于一个单词,同时复制其他保持不变的列:[id, label, text, box]
,从而产生具有这些列的最终数据框:[box,text,label,box_word, text_word]
我可以标记列
'text'
和text_word
一个热编码列label
,将具有多个数字的列拆分box
为box_word
单独的列,但是如何拆分/重新排列列'linking'
以定义我的网络图的边缘?我在使用数据帧生成网络并使用它来训练 GNN 中是否采取了正确的路线?
感谢任何和所有帮助/提示。
解决方案
编辑:处理列中的多个条目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:]
推荐阅读
- node.js - 我希望覆盖 find 但同时使用原始版本
- c# - API 服务抱怨 HTTPS 请求缺少用户名和密码
- javascript - Node.js 和 node_modules 不是 whatwg-url 中的 TextEncoder
- amazon-dynamodb - Dynamodb - 使用多个条件查询 Sortkey
- intellij-idea - 在 WebStorm 中查看图像预览
- css - Tailwind 中的边框和间距
- python - 使用 Telethon API 获取所有频道成员列表的问题
- javascript - 带有输入字段的动态图章
- julia - 如何在 Julia 中重命名文件?
- typo3 - TYPO3 V11 安装或配置