基于预定义实体的文本数据自动标注

数据挖掘 nlp 数据 标签
2022-02-26 23:19:12

我是 NLP 新手。我有一个包含 .txt 文件的文件夹,这些文件是合法的和特定的文件。我想根据四个预定义的标签来标记所有这些文件。我怎样才能自动做到这一点?

1个回答

您的任务称为命名实体识别。来自维基

命名实体识别 (NER)(也称为实体识别、实体分块和实体提取)是信息提取的子任务,旨在将非结构化文本中提及的命名实体定位和分类为预定义的类别,例如人名、组织,地点,医疗代码,时间表达,数量,货币价值,百分比等。

由于这是一项常见的 NLP 任务,因此有一些库可以开箱即用地进行 NER。spaCy就是一个这样的库,它可以使用 Python 执行 NER 以及许多其他 NLP 任务。

如果不先在自定义标签/实体上训练模型,您将无法执行 NER。你需要有一些标记的数据来训练,也许你已经有了这个,或者你可以手动标记它。SpaCy 希望您将数据标记为格式上每个实体的位置:

[("legal text here", {"entities": [(Start index, End index, "Money"), 
                                   (Start index, End index, "Judge"), 
                                   (Start index, End index, "Tribunal"), 
                                   (Start index, End index, "State")]}),
("legal text here", {"entities": [(Start index, End index, "Money"), 
                                  (Start index, End index, "Judge"), 
                                  (Start index, End index, "Tribunal"), 
                                  (Start index, End index, "State")]})
...]

有关如何为 NER 训练 spaCy 模型的示例(取自 docs):

from __future__ import unicode_literals, print_function

import plac
import random
from pathlib import Path
import spacy
from spacy.util import minibatch, compounding  

# training data
TRAIN_DATA =   Insert you labelled training data here  

@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=100):
    """Load the model, set up the pipeline and train the entity recognizer."""
    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")

    # create the built-in pipeline components and add them to the pipeline
    # nlp.create_pipe works for built-ins that are registered with spaCy
    if "ner" not in nlp.pipe_names:
        ner = nlp.create_pipe("ner")
        nlp.add_pipe(ner, last=True)
    # otherwise, get it so we can add labels
    else:
        ner = nlp.get_pipe("ner")

    # add labels
    for _, annotations in TRAIN_DATA:
        for ent in annotations.get("entities"):
            ner.add_label(ent[2])

    # get names of other pipes to disable them during training
    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "ner"]
    with nlp.disable_pipes(*other_pipes):  # only train NER
        # reset and initialize the weights randomly – but only if we're
        # training a new model
        if model is None:
            nlp.begin_training()
        for itn in range(n_iter):
            random.shuffle(TRAIN_DATA)
            losses = {}
            # batch up the examples using spaCy's minibatch
            batches = minibatch(TRAIN_DATA, size=compounding(4.0, 32.0, 1.001))
            for batch in batches:
                texts, annotations = zip(*batch)
                nlp.update(
                    texts,  # batch of texts
                    annotations,  # batch of annotations
                    drop=0.5,  # dropout - make it harder to memorise data
                    losses=losses,
                )
            print("Losses", losses)

    # test the trained model
    for text, _ in TRAIN_DATA:
        doc = nlp(text)
        print("Entities", [(ent.text, ent.label_) for ent in doc.ents])
        print("Tokens", [(t.text, t.ent_type_, t.ent_iob) for t in doc])

    # 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)
        for text, _ in TRAIN_DATA:
            doc = nlp2(text)
            print("Entities", [(ent.text, ent.label_) for ent in doc.ents])
            print("Tokens", [(t.text, t.ent_type_, t.ent_iob) for t in doc])


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

然后,当您拥有经过训练的模型时,您可以使用它来获取实体:

doc = nlp('put legal text to test your model here')

for ent in doc.ents:
    print(ent.text, ent.start_char, ent.end_char, ent.label_)