【问题标题】:How to find matches faster with SpaCy Matcher?如何使用 SpaCy Matcher 更快地找到匹配项?
【发布时间】:2021-01-05 05:40:07
【问题描述】:

只要句子中有被动语态,我就会尝试使用SpaCy Matcher package 来检测匹配项。我写了下面的模式,它正确地找到了被动动词和句子。虽然我现在的问题是速度。我有大约 100 万条记录,每条记录大约有 10 个句子。我想知道我是否可以做任何事情来提高搜索效率?喜欢不返回结束和开始标记?

匹配器:

matcher = Matcher(nlp.vocab)
passive_rule1 = [{'DEP':'nsubjpass', 'OP':'*'}, {'DEP':'xcomp', 'OP':'*'}, {'DEP':'aux','OP':'*'},{'DEP':'auxpass'}, {'DEP':'nsubj', 'OP':'*'}, {'TAG':'VBN'}]
passive_rule2 =  [{'DEP': 'attr'}, {'DEP':'det', 'OP':'*'}, {'Tag':'NOUN', 'OP': '?'}, {'TAG':'VBN'}]

matcher.add('passive_rule1',None, passive_rule1)
matcher.add('passive_rule2 ', None, passive_rule2)

寻找匹配:

df.loc[:, 'PassiveVoice'] = df.Sentence.apply(lambda x:1 if len(matcher(nlp(x)))>0 else 0)

或者,如果有人有任何其他想法,我会很高兴听到!

【问题讨论】:

    标签: machine-learning text nlp data-science spacy


    【解决方案1】:

    投入 100 万。向熊猫的dataframe 发送文本,然后循环调用nlp 100 万次是个坏主意。相反,通过df["Sentence"].tolist() 将您的文档放在一个列表中,并通过nlp.pipe 有效地处理它们:

    import spacy
    from spacy.matcher import Matcher
    
    nlp = spacy.load("en_core_web_md", disable=["ner"])
    
    matcher = Matcher(nlp.vocab)
    passive_rule1 = [
        {"DEP": "nsubjpass", "OP": "*"},
        {"DEP": "xcomp", "OP": "*"},
        {"DEP": "aux", "OP": "*"},
        {"DEP": "auxpass"},
        {"DEP": "nsubj", "OP": "*"},
        {"TAG": "VBN"},
    ]
    passive_rule2 = [
        {"DEP": "attr"},
        {"DEP": "det", "OP": "*"},
        {"Tag": "NOUN", "OP": "?"},
        {"TAG": "VBN"},
    ]
    
    matcher.add("passive_rule1", None, passive_rule1)
    matcher.add("passive_rule2", None, passive_rule2)
    
    texts = ["this is my first sentence. about something", "this is another"]
    # texts = df["Sentence"].tolist()
    docs = nlp.pipe(texts, n_process = 2, batch_size=50)
    
    for doc in docs:
        if matcher(doc):
            #do something
    

    另外注意,使用nlp.pipe(),您可以使用n_process=2(选择您的)打开多处理,并使用batch_size=50(选择您的)批量处理您的文本。

    【讨论】:

    • 非常感谢您的回答。虽然我在这里有一些问题。我在我的系统上运行了代码,不幸的是,在我用来运行 9 秒的一个示例上运行时只有 1 分钟!虽然当我在 Colab 上运行代码时,我可以得到大约 2 秒,这是一个很大的改进。你能告诉我为什么我不能在我自己的系统上做同样的事情吗?我看到我有 12 个核心,而 Colab 提供 2 个。
    • 当你比较相同代码在两台不同机器上的运行时,CPU/GPU 规格才是最重要的。 CPU 频率、缓存大小、RAM 类型等等。您可以检查代码是否相同。
    • 这个任务完全依赖CPU,不是吗?所以他们应该表现相似。我仍在寻找为什么我不能得到更好的结果,你认为我应该有任何先决条件让这条管道运行得更快吗?(比如 spacy-nightly)
    • 感谢@Sergey,我可以构建一个很好的函数来检测被动语态。尽管速度问题原来是因为更换内核的开销,但在使用大量记录和数据集时这将是微不足道的。 Here is my repository 如果有人对此仍有疑问。
    猜你喜欢
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多