python - SpaCy 在解析文本时未分配正确的依赖标签

标签 python machine-learning nlp spacy

我从 the SpaCy docs 获取了一些代码允许您将自定义依赖标签分配给文本,我想用它来解释用户的意图。它大部分工作正常,但例如,当我运行代码时,它会将“delete”标记为“ROOT”,而它应该将其标记为“INTENT”,就像在 deps 字典中显示的那样。

from __future__ import unicode_literals, print_function

import plac
import random
import spacy
from pathlib import Path


# training data: texts, heads and dependency labels
# for no relation, we simply chose an arbitrary dependency label, e.g. '-'
TRAIN_DATA = [
    ("How do I delete my account?", {
        'heads': [3, 3, 3, 3, 5, 3, 3],  # index of token head
        'deps': ['ROOT', '-', '-', 'INTENT', '-', 'OBJECT', '-']
    }),
    ("How do I add a balance?", {
        'heads': [3, 3, 3, 3, 5, 3, 3],
        'deps': ['ROOT', '-', '-', 'INTENT', '-', 'OBJECT', '-']
    }),
    ("How do I deposit my funds into my bank account?", {
        'heads': [3, 3, 3, 3, 5, 3, 3, 9, 9, 6, 3],
        'deps': ['ROOT', '-', '-', 'INTENT', '-', '-', '-', '-', '-', 'OBJECT', '-']
    }),
    ("How do I fill out feedback forms?", {
        'heads': [3, 3, 3, 3, 3, 6, 3, 3],
        'deps': ['ROOT', '-', '-', 'INTENT', '-', '-', 'OBJECT', '-']
    }),
    #("How does my profile impact my score?", {
        #'heads': [4, 4, 4, 4, 4, 6, 4, 4],
        #'deps': ['ROOT', '-', '-', '-', 'INTENT', '-', 'OBJECT' '-']
    #}),
    ("What are the fees?", {
        'heads': [1, 1, 3, 1, 1],
        'deps': ['ROOT', '-', '-', 'INTENT', '-']
    }),
    ("How do I update my profile picture?", {
        'heads': [3, 3, 3, 3, 6, 6, 3, 3],
        'deps': ['ROOT', '-', '-', 'INTENT', '-', 'OBJECT', 'OBJECT', '-']
    }),
    ("How do I add a referral to the marketplace?", {
        'heads': [3, 3, 3, 3, 5, 3, 3, 8, 6, 3],
        'deps': ['ROOT', '-', '-', 'INTENT', '-', 'OBJECT', '-', '-', 'OBJECT', '-']
    }),


]


@plac.annotations(
    model=("Model name. Defaults to blank 'en' model.", "option", "m", str),
    output_dir=("Optional output directory", "option", "o", Path),
    n_iter=("Number of training iterations", "option", "n", int))
def main(model=None, output_dir=None, n_iter=5):
    """Load the model, set up the pipeline and train the parser."""
    if model is not None:
        nlp = spacy.load(model)  # load existing spaCy model
        print("Loaded model '%s'" % model)
    else:
        nlp = spacy.blank('en')  # create blank Language class
        print("Created blank 'en' model")

    # We'll use the built-in dependency parser class, but we want to create a
    # fresh instance – just in case.
    if 'parser' in nlp.pipe_names:
        nlp.remove_pipe('parser')
    parser = nlp.create_pipe('parser')
    nlp.add_pipe(parser, first=True)

    #add new labels to the parser
    for text, annotations in TRAIN_DATA:
        for dep in annotations.get('deps', []):
            parser.add_label(dep)

    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'parser']
    with nlp.disable_pipes(*other_pipes):  # only train parser
        optimizer = nlp.begin_training()
        for itn in range(n_iter):
            random.shuffle(TRAIN_DATA)
            losses = {}
            for text, annotations in TRAIN_DATA:
                nlp.update([text], [annotations], sgd=optimizer, losses=losses)
            print(losses)

    # test the trained model
    test_model(nlp)

    # save model to output directory
    if output_dir is not None:
        output_dir = Path(output_dir)
        if not output_dir.exists():
            output_dir.mkdir()
        nlp.to_disk(output_dir)
        print("Saved model to", output_dir)

        # test the saved model
        print("Loading from", output_dir)
        nlp2 = spacy.load(output_dir)
        test_model(nlp2)


def test_model(nlp):
    texts = ["How do I delete my account?"]
    docs = nlp.pipe(texts)
    for doc in docs:
        print(doc.text)
        print([(t.text, t.dep_, t.head.text) for t in doc if t.dep_ != '-'])


if __name__ == '__main__':
    plac.call(main)

这是输出: 如何删除我的帐户? [(u'如何', u'ROOT', u'删除'), (u'删除', u'ROOT', u'删除'), (u'帐户', u'OBJECT', u'删除' )]

最佳答案

我认为问题的根源在于依赖树的根自动标记为'ROOT', (依赖树的根定义为头为其自身的标记)。

一种可能的解决方法是在训练数据中添加人工根:

("root How do I delete my account?", {
    'heads': [0, 4, 4, 4, 0, 6, 4, 4],  # index of token head
    'deps': ['ROOT', '-', '-', '-', 'INTENT', '-', 'OBJECT', '-']
})

(同时将符号 root 添加到您的测试示例中:texts = ["root How do I delete my account?"])

通过这些更改,如果您训练模型足够长的时间,您将获得:

root How do I delete my account?
[('root', 'ROOT', 'root'), ('delete', 'INTENT', 'root'), ('account', 'OBJECT', 'delete')]

关于python - SpaCy 在解析文本时未分配正确的依赖标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50207313/

相关文章:

machine-learning - 无监督感兴趣区域与词袋模型的异同

python - 计算功能词的频率

python - 如何给 matplotlib slider 贴上标签?

python - 在 matplotlib 2.0 中,如何将颜色条行为恢复为 matplotlib 1.5 的行为?

python - 使用 Mechanize 登录

python - 使用 Science-Kit 对文档(即文本)执行欧几里德距离测量

python - 如何切片 numpy 数组的一个子集

matlab - 一维高斯混合拟合 Matlab/Python 中的数据

python - 如何使用 python 删除 xml 或 html 命令行并检索实际文本数据?

java - 在哪里可以找到荷兰语工具的 opennlp.tools.lang.dutch.* 软件包?