【数据挖掘】从“文本”到“知识”:信息抽取(Information Extraction)

2023-10-27

从“文本”到“知识”:信息抽取

这是一个大数据的时代。随着太阳东升西落,每一天都在产生大量的数据信息。人们通常更擅长处理诸如数字之类的结构化数据。但实际情况是,非结构化数据往往比结构化的数据多。

当我们从互联网上获取了大量的如文本之类的非结构化数据,如何去有效地分析它们来帮助我们更好地做出决策呢?这将是本文要回答的问题。

信息提取是从非结构化数据(例如文本)中提取结构化信息的任务。我将这个过程分为以下四个步骤进行处理。
在这里插入图片描述

1.共指解析(Coreference Resolution)

“共指解析”就是在文本中查找引用特定实体的所有表达式。简单来说就是解决代指问题。比如,Deepika has a dog. She loves him. 我们知道这里的she指代的是Deepika,him指代的是dog,但是计算机不知道。

我这里使用Neuralcoref模型解决这个问题,该模型基于SpaCy框架运行。值得注意的是,Neuralcoref模型可能不太适用于位置代词。代码如下:

import spacy
import neuralcoref

# Load SpaCy
nlp = spacy.load('en')
# Add neural coref to SpaCy's pipe
neuralcoref.add_to_pipe(nlp)

def coref_resolution(text):
    """Function that executes coreference resolution on a given text"""
    doc = nlp(text)
    # fetches tokens with whitespaces from spacy document
    tok_list = list(token.text_with_ws for token in doc)
    for cluster in doc._.coref_clusters:
        # get tokens from representative cluster name
        cluster_main_words = set(cluster.main.text.split(' '))
        for coref in cluster:
            if coref != cluster.main:  # if coreference element is not the representative element of that cluster
                if coref.text != cluster.main.text and bool(set(coref.text.split(' ')).intersection(cluster_main_words)) == False:
                    # if coreference element text and representative element text are not equal and none of the coreference element words are in representative element. This was done to handle nested coreference scenarios
                    tok_list[coref.start] = cluster.main.text + \
                        doc[coref.end-1].whitespace_
                    for i in range(coref.start+1, coref.end):
                        tok_list[i] = ""

    return "".join(tok_list)

如果以下面这段文本作为输入:

Elon Musk is a business magnate, industrial designer, and engineer. He is the founder, CEO, CTO, and chief designer of SpaceX. He is also early investor, CEO, and product architect of Tesla, Inc. He is also the founder of The Boring Company and the co-founder of Neuralink. A centibillionaire, Musk became the richest person in the world in January 2021, with an estimated net worth of $185 billion at the time, surpassing Jeff Bezos. Musk was born to a Canadian mother and South African father and raised in Pretoria, South Africa. He briefly attended the University of Pretoria before moving to Canada aged 17 to attend Queen's University. He transferred to the University of Pennsylvania two years later, where he received dual bachelor's degrees in economics and physics. He moved to California in 1995 to attend Stanford University, but decided instead to pursue a business career. He went on co-founding a web software company Zip2 with his brother Kimbal Musk.

则输出为:

Elon Musk is a business magnate, industrial designer, and engineer. Elon Musk is the founder, CEO, CTO, and chief designer of SpaceX. Elon Musk is also early investor, CEO, and product architect of Tesla, Inc. Elon Musk is also the founder of The Boring Company and the co-founder of Neuralink. A centibillionaire, Musk became the richest person in the world in January 2021, with an estimated net worth of $185 billion at the time, surpassing Jeff Bezos. Musk was born to a Canadian mother and South African father and raised in Pretoria, South Africa. Elon Musk briefly attended the University of Pretoria before moving to Canada aged 17 to attend Queen's University. Elon Musk transferred to the University of Pennsylvania two years later, where Elon Musk received dual bachelor's degrees in economics and physics. Elon Musk moved to California in 1995 to attend Stanford University, but decided instead to pursue a business career. Elon Musk went on co-founding a web software company Zip2 with Elon Musk brother Kimbal Musk.

2.命名实体链接(Named Entity Linking)

这部分我使用的是Wikifier API。大家可以自己尝试一下。Wikifier API:http://wikifier.org/
在这里插入图片描述
在通过Wikifier API运行输入文本之前,我们将文本拆分为句子并删除标点符号。代码如下:

import urllib
from string import punctuation
import nltk

ENTITY_TYPES = ["human", "person", "company", "enterprise", "business", "geographic region",
                "human settlement", "geographic entity", "territorial entity type", "organization"]

def wikifier(text, lang="en", threshold=0.8):
    """Function that fetches entity linking results from wikifier.com API"""
    # Prepare the URL.
    data = urllib.parse.urlencode([
        ("text", text), ("lang", lang),
        ("userKey", "tgbdmkpmkluegqfbawcwjywieevmza"),
        ("pageRankSqThreshold", "%g" %
         threshold), ("applyPageRankSqThreshold", "true"),
        ("nTopDfValuesToIgnore", "100"), ("nWordsToIgnoreFromList", "100"),
        ("wikiDataClasses", "true"), ("wikiDataClassIds", "false"),
        ("support", "true"), ("ranges", "false"), ("minLinkFrequency", "2"),
        ("includeCosines", "false"), ("maxMentionEntropy", "3")
    ])
    url = "http://www.wikifier.org/annotate-article"
    # Call the Wikifier and read the response.
    req = urllib.request.Request(url, data=data.encode("utf8"), method="POST")
    with urllib.request.urlopen(req, timeout=60) as f:
        response = f.read()
        response = json.loads(response.decode("utf8"))
    # Output the annotations.
    results = list()
    for annotation in response["annotations"]:
        # Filter out desired entity classes
        if ('wikiDataClasses' in annotation) and (any([el['enLabel'] in ENTITY_TYPES for el in annotation['wikiDataClasses']])):

            # Specify entity label
            if any([el['enLabel'] in ["human", "person"] for el in annotation['wikiDataClasses']]):
                label = 'Person'
            elif any([el['enLabel'] in ["company", "enterprise", "business", "organization"] for el in annotation['wikiDataClasses']]):
                label = 'Organization'
            elif any([el['enLabel'] in ["geographic region", "human settlement", "geographic entity", "territorial entity type"] for el in annotation['wikiDataClasses']]):
                label = 'Location'
            else:
                label = None

            results.append({'title': annotation['title'], 'wikiId': annotation['wikiDataItemId'], 'label': label,
                            'characters': [(el['chFrom'], el['chTo']) for el in annotation['support']]})
    return results

以上一步中共指解析的输出作为这里的输入,运行得到如下结果。
在这里插入图片描述
可以看到,我们还获得了实体对应的WikiId及其label。WikiId可以消除同名实体的歧义问题。虽然维基百科拥有超过1亿个实体,但对于维基百科上不存在的实体,仍将无法识别它。

3.关系提取(Relationship Extraction)

我使用OpenNRE项目来实现关系提取。它具有五个在Wiki80或Tacred数据集上经过训练的开源关系提取模型。在Wiki80数据集上训练的模型可以推断80种关系类型。

  • wiki80_cnn_softmax: trained on wiki80 dataset with a CNN encoder.
  • wiki80_bert_softmax: trained on wiki80 dataset with a BERT encoder.
  • wiki80_bertentity_softmax: trained on wiki80 dataset with a BERT encoder (using entity representation concatenation).
  • tacred_bert_softmax: trained on TACRED dataset with a BERT encoder.
  • tacred_bertentity_softmax: trained on TACRED dataset with a BERT encoder (using entity representation concatenation).

这里,我使用了wiki80_bert_softmax模型(需要GPU提供支持)。

如果我们看一下OpenNRE库中的关系提取示例,我们会注意到它仅推断关系,而不尝试提取命名实体。所以我们必须提供一对带有h和t参数的实体,然后模型尝试推断出一个关系。

# 示例
model.infer({'text': 'He was the son of Máel Dúin mac Máele Fithrich, and grandson of the high king Áed Uaridnach (died 612).', 
			    'h': {'pos': (18, 46)}, 
			    't': {'pos': (78, 91)}
			    })
# 结果
('father', 0.5108704566955566)

实现代码如下所示:

# First get all the entities in the sentence
entities = wikifier(sentence, threshold=entities_threshold)
# Iterate over every permutation pair of entities
for permutation in itertools.permutations(entities, 2):
    for source in permutation[0]['characters']:
        for target in permutation[1]['characters']:
            # Relationship extraction with OpenNRE
            data = relation_model.infer(
                {'text': sentence, 'h': {'pos': [source[0], source[1] + 1]}, 't': {'pos': [target[0], target[1] + 1]}})
            if data[1] > relation_threshold:
                relations_list.append(
                    {'source': permutation[0]['title'], 'target': permutation[1]['title'], 'type': data[0]})

用“命名实体链接”的结果作为“关系提取过程”的输入。我们遍历一对实体的每个排列组合来尝试推断一个关系。用relationship_threshold参数,用于省略较低的置信度关系。在下一步中,我会解释为什么这里使用实体的所有排列而不是一些组合。

运行结果如下:
在这里插入图片描述
关系提取是一个具有挑战性的问题,就目前来说,很难有一个完美的结果。

4.知识图谱(Knowledge Graph)

当我们处理实体及其关系时,将结果存储在图形数据库中才有意义。这里我使用Neo4j作为图数据库。
在这里插入图片描述
我尝试推断实体之间所有排列的关系。查看上一步中的表格结果,很难解释为什么。但在图形可视化中,很容易观察到,虽然大多数关系都是双向推断的,但并非在所有情况下都是如此。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【数据挖掘】从“文本”到“知识”:信息抽取(Information Extraction) 的相关文章

  • 避免由于相对 URL 导致的错误请求

    我正在尝试使用Scrapy抓取一个网站 并且我想要抓取的每个页面的url都是使用这种相对路径编写的 a href en item to scrap html Link a 现在 在我的浏览器中 这些链接可以工作 您可以访问类似的网址http
  • 将tensorflow 2.0 BatchDataset转换为numpy数组

    我有这个代码 train images test images tf keras datasets mnist load data train dataset tf data Dataset from tensor slices train
  • 在 Pandas 中按日期获取有效合约

    我在检测 pandas DataFrame 中的活动合约方面遇到了一些困难 假设每一行都是一个协商 对于每一行 我有两列 initial date 和 end date 我想知道的是按日期划分的活跃合约数量 到目前为止我做了一个非常低效的方
  • 行未从树视图复制

    该行未在树视图中复制 我在按行并复制并粘贴到未粘贴的任何地方后制作了弹出复制 The code popup tk Menu tree opportunity tearoff 0 def row copy item tree opportun
  • 在Python3.6中调用C#代码

    由于完全不了解 C 编码 我希望在我的 python 代码中调用 C 函数 我知道有很多关于同一问题的问答 但由于一些奇怪的原因 我无法从示例 python 模块导入简单的 c 类库 以下是我所做的事情 C 类库设置 我使用的是 VS 20
  • 如何在Python中循环并存储自变量中的值

    我对 python 很陌生 所以这听起来可能很愚蠢 我进行了搜索 但没有找到解决方案 我在 python 中有一个名为 ExcRng 的函数 我可以对该函数执行什么样的 for 循环 以便将值存储在独立变量中 我不想将它们存储在列表中 而是
  • python 中分割字符串以获得一个值?

    需要帮助 假设我在名为 input 的变量中有一个字符串 Sam Person name kind input split 通过执行上述操作 我得到两个具有不同字符串 Sam 和 Person 的变量 有没有办法只获取第一个值 name S
  • sudo pip install python-Levenshtein 失败,错误代码 1

    我正在尝试在 Linux 上安装 python Levenshtein 库 但每当我尝试通过以下方式安装它时 sudo pip install python Levenshtein 我收到此错误 命令 usr bin python c 导入
  • 定义函数后对其进行修饰?

    I think答案是否定的 但我似乎找不到明确的说法 我有以下情况 def decorated function function functools wraps function def my function print Hello s
  • “char”/“character”类型的类型提示

    char 或 character 没有内置的原始类型 因此显然必须使用长度为 1 的字符串 但是为了暗示这一点并暗示它应该被视为一个字符 如何通过类型提示来实现这一点 grade chr A 一种方法可能是使用内置的 chr 函数来表示这一
  • 创建一个类似于 Tkinter 的表

    我希望创建类似于 Tkinter 中的表格的东西 但它不一定是这样的 例如 我想创建标题 Name1 Name2 Value 并在每个标题下面有几个空白行 然后 我希望稍后用我计算的值或名称的字符串值填充这些行 因此是标签 对于 Name2
  • 如何在python中检索aws批处理参数值?

    流程 Dynamo DB gt Lambda gt 批处理 如果将角色 arn 插入动态数据库 它是从 lambda 事件中检索的 然后使用submit job角色 arn 的 API 被传递为 parameters role arn ar
  • 具有多个元素的数组的真值是二义性错误吗? Python

    from numpy import from pylab import from math import def TentMap a x if x gt 0 and x lt 0 5 return 2 a x elif x gt 0 5 a
  • 获取列表中倒数第二个元素[重复]

    这个问题在这里已经有答案了 我可以通过以下方式获取列表的倒数第二个元素 gt gt gt lst a b c d e f gt gt gt print lst len lst 2 e 有没有比使用更好的方法print lst len lst
  • Django 在选择列表更改时创建毫无意义的迁移

    我正在尝试使用可调用创建一个带有选择字段的模型 以便 Django 在选择列表更改时不会创建迁移 如中所述this https stackoverflow com questions 31788450 stop django from cr
  • 如何在与应用程序初始化文件不同的文件中迭代 api 路由

    我有一个 apiroutes py 文件 其中定义了许多路由 例如 api route api read methods GET api route api write methods POST 其中 api 是导入 from import
  • 如何通过字符串匹配加速 pandas 行过滤?

    我经常需要过滤 pandas 数据框df by df df col name string value 并且我想加快行选择操作 有没有快速的方法可以做到这一点 例如 In 1 df mul df 3000 2000 3 reset inde
  • 全局变量是 None 而不是实例 - Python

    我正在处理Python 中的全局变量 代码应该可以正常工作 但是有一个问题 我必须使用全局变量作为类的实例Back 当我运行应用程序时 它说 back is None 这应该不是真的 因为第二行setup 功能 back Back Back
  • 如何在sphinx中启用数学?

    我在用sphinx http sphinx pocoo org index html与pngmath http sphinx pocoo org ext math html module sphinx ext pngmath扩展来记录我的代
  • 在 Python 模块中使用 InstaLoader

    我正在尝试使用 Instaloader 下载与主题标签相关的照片以进行图像分析 我在GitHub存储库中找到了一个全面的方法 如何在终端中执行它 但是 我需要将脚本集成到Python笔记本中 这是脚本 instaloader no vide

随机推荐

  • Golang爬虫终极杀器——Chromedp让你成为二维码登陆终结者(教程)

    Golang爬虫终极杀器 Chromedp让你成为二维码登陆终结者 教程 Github源码 chromedp 文章项目Gitee源码 1 Chromedp是什么 chromedp是一个更快 更简单的Golang库用于调用支持Chrome D
  • 二哈智能图像识别使用I2C导出识别结果到Wemos D1板

    学校比赛 购买了一块智能识别传感器模块huskylens 商家给了使用文档 但是别人用的官方uno板子来连接 我手里面只有ESP8266WiFi板子 只能把I2C驱动程序编译到esp8266上了 这是我的板子 说明文档里面只给了连接UNO
  • LZW编解码算法实现及编码效率分析

    一 编码原理 第二类算法的想法是企图从输入的数据中创建一个 短语词典 dictionary of the phrases 这种短语可以是任意字符的组合 编码数据过程中当遇到已经在词典中出现的 短语 时 编码器就输出这个词典中的短语的 索引号
  • 美国的有线电视节目提供商

    HBO HBO电视网 英文名 Home Box Office 是总部位于美国纽约的有线电视网络媒体公司 HBO电视网于1972年开播 全天候播出电影 音乐 纪录片 体育赛事等娱乐节目 与绝大多数电视频道不同的是 它不卖广告 经过22年的发展
  • 什么是正则表达式?

    什么是正则表达式 1 什么是正则表达式 2 基本匹配 3 元字符 1 什么是正则表达式 正则表达式是 组由字 和符号组成的特殊 本 它可以 来从 本中找出满 你想要的格式的句 个正则表达式是 种从左到右匹配主体字符串的模式 Regular
  • Vue 中给数组增加自定义方法

    第一步 在程序根目录下创建 src common functions myFunction js 文件 第二步 文件内写入 export default install Vue 返回val在当前列表内的位置 Array prototype
  • SimpleServletHandlerAdapter类简介说明

    转自 SimpleServletHandlerAdapter类简介说明 下文笔者讲述SimpleServletHandlerAdapter类简介说明 如下所示 SimpleServletHandlerAdapter简介 SimpleServ
  • pycharm配置python环境变量详细步骤

    1 打开pycharm 点file settings 2 点击profect下的Python Interpeter
  • 目标检测与识别算法研究

    一 目标检测与识别 目标检测与识别是很多计算机视觉任务的基础 通俗地讲 其目的是在目标场景中将目标用一个个框框出来 并且识别出这个框中的物体 即包括加测 where 和识别 what 两个过程 1 技术难点 目标检测与识别任务对于人类来说
  • linux c语言字符串函数replace,indexOf,substring等的实现

    c语言没有像java那么丰富的字符串操作函数 很多有用的函数得自己写 搞了一天 写了几个常用函数 留着以后有用 include
  • Spark大数据分析与实战笔记(第一章 Scala语言基础-1)

    文章目录 章节概要 1 1 初识Scala 1 1 1 Scala的概述 1 1 2 Scala的下载安装 1 1 3 在IDEA开发工具中下载安装Scala插件 1 1 4 开发第一个Scala程序 章节概要 Spark是专为大规模数据处
  • python高级变量类型

    列表概念及操作 1 列表的定义 列表格式 列表名 元素1 元素2 例 my list 1 2 3 True 空列表的定义 my list 或 my list list 2 列表的循环遍历 for 循环遍历 while循环遍历 3 列表的常见
  • 利用Keras实现FGSM算法

    最近项目中需要使用FGSM攻击方法 使用主流的foolbox和cleverhans中的攻击方法时 发现模型不匹配 所以不能继续使用 网上找到的代码也不能使用 需要自己实现一个 根据论文 Explaining and Harnessing A
  • [ACTF新生赛2020]easyre 1

    查壳 是32位 upx壳 脱壳就是找的脱壳软件 我也不是很懂 就说下我的具体操作步骤吧 打开cmd 脱upx壳的软件拖进去 空格 d 空格 有壳文件拖入 解出来了 下面看代码吧 然后就挺简单的 就这点代码 下面那个for循环逆着写就行了 注
  • 欧科云链:2023年5月链上安全事件盘点

    一 基本信息 2023年5月安全事件约造成1800万美元损失 相比上月有显著下降 但安全事件发生频率并未减少 其中针对Jimbos Protocol的攻击造成了约750万美元损失 Arbitrum链的Swaprum项目Rug Pull造成了
  • C++继承-基本语法--继承方式--继承同名成员处理方式--多继承语法--菱形继承

    1 基本语法 继承 减少重复代码 语法 class 子类 继承方式 父类 子类也叫派生类 父类也叫基类 派生类中的成员包括两大部分 一类是从基类继承过来的 一类是自己增加的成员 从基类继承过来的表现其共性 而新增的成员体现了其个性 incl
  • GBASE 8s 并行机制之 PDQ 的基本概念

    Parallel database query PDQ 即并行数据库查询 当处理决策支持类 或数据仓库类查询 查询时 PDQ 特性可以用来极大地提高数据库查询处理的性能 启用PDQ后 GBase 8s 可以将查询操作分布到多个不同的处理器上
  • Kali之MSF的MS08-067漏洞复现详解

    1 MSF初识 MSF即Metasploit Framework 是一个综合性的渗透测试工具 集成信息收集 漏洞扫描 漏洞利用以及提权等功能的工具 目前安装的kali都自带MSF 可以直接在图形界面打开 也可以在kali的终端通过使用命令m
  • 假设检验之T检验、方差检验

    假设检验 spss 差异分析 一 假设检验 1 假设检验的假设 2 原假设与研究假设的关系 3 区分两种假设 4 假设检验统计决策的原理 5 假设检验的步骤 二 t检验 1 单样本T检验 2 独立样本T检验 3 配对样本T检验 三 方差分析
  • 【数据挖掘】从“文本”到“知识”:信息抽取(Information Extraction)

    从 文本 到 知识 信息抽取 这是一个大数据的时代 随着太阳东升西落 每一天都在产生大量的数据信息 人们通常更擅长处理诸如数字之类的结构化数据 但实际情况是 非结构化数据往往比结构化的数据多 当我们从互联网上获取了大量的如文本之类的非结构化