NLP(5)固有表現抽出(NER)

この記事では、自然言語処理(NLP)における固有表現抽出(NER)について簡単に紹介します。

1つは、エンティティ認識と呼ばれるものです。

1.固有表現抽出の概要

    固有表現抽出(NER)は、情報抽出、質問応答システム、構文解析、機械翻訳などのアプリケーション分野における重要な基本ツールであり、自然言語処理技術の実際のプロセスにおいて重要な位置を占めています。一般的に、名前付きエンティティの認識のタスクは、テキスト内の3つのカテゴリ(エンティティカテゴリ、時間カテゴリ、および番号カテゴリ)と7つのカテゴリ(人名、組織名、地名、時間、日付、通貨、およびパーセンテージ)を識別することです。処理済みエンティティ。

2.固有表現抽出の例

簡単な例として、「Xiao Mingは朝8時に学校に行く」という文で、固有表現抽出は情報を抽出できる必要があります。

名前:シャオミン、時間:午前8時、場所:学校。

2.NLTKおよびStanfordNLPでの固有表現抽出の分類

NLTKおよびStanfordNLPでの固有表現抽出の分類は次のとおりです。
  ここに画像の説明を挿入

上の図では、LOCATIONとGPEが重なっています。GPEは通常、都市、州、国、大陸などの地政学的項目を意味します。上記のコンテンツに加えて、LOCATIONは有名な山や川を表すこともできます。FACILITYは通常、有名なモニュメントや遺物などを意味します。

第三に、NLTKを使用してNERタスクを実装します

1.サンプルドキュメント

サンプルドキュメント(ウィキペディアからのFIFAの紹介)は次のとおりです。

FIFAは、ベルギー、
デンマーク、フランス、ドイツ、オランダ、スペイン、スウェーデン、スイスの各国協会間の国際競争を監督するために1904年に設立されましたチューリッヒに本部を置き、
その会員は現在211の全国協会で構成されています。加盟国はそれぞれ、世界が分割されている6つの地域連合(アフリカ、アジア、ヨーロッパ、北および中央アメリカ、カリブ海、オセアニア、南アメリカ)のいずれかのメンバーである必要があります。

2.Python実装コード

NERを実装するPythonコードは次のとおりです。

import re
import pandas as pd
import nltk

def parse_document(document):
   document = re.sub('\n', ' ', document)
   if isinstance(document, str):
       document = document
   else:
       raise ValueError('Document is not string!')
   document = document.strip()
   sentences = nltk.sent_tokenize(document)
   sentences = [sentence.strip() for sentence in sentences]
   return sentences

# sample document
text = """
FIFA was founded in 1904 to oversee international competition among the national associations of Belgium, 
Denmark, France, Germany, the Netherlands, Spain, Sweden, and Switzerland. Headquartered in Zürich, its 
membership now comprises 211 national associations. Member countries must each also be members of one of 
the six regional confederations into which the world is divided: Africa, Asia, Europe, North & Central America 
and the Caribbean, Oceania, and South America.
"""

# tokenize sentences
sentences = parse_document(text)
tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]
# tag sentences and use nltk's Named Entity Chunker
tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]
ne_chunked_sents = [nltk.ne_chunk(tagged) for tagged in tagged_sentences]
# extract all named entities
named_entities = []
for ne_tagged_sentence in ne_chunked_sents:
   for tagged_tree in ne_tagged_sentence:
       # extract only chunks having NE labels
       if hasattr(tagged_tree, 'label'):
           entity_name = ' '.join(c[0] for c in tagged_tree.leaves()) #get NE name
           entity_type = tagged_tree.label() # get NE category
           named_entities.append((entity_name, entity_type))
           # get unique named entities
           named_entities = list(set(named_entities))

# store named entities in a data frame
entity_frame = pd.DataFrame(named_entities, columns=['Entity Name', 'Entity Type'])
# display results
print(entity_frame)

# ------output---------------
        Entity Name   Entity Type
0         Caribbean      LOCATION
1             North           GPE
2       Switzerland           GPE
3              Asia           GPE
4           Denmark           GPE
5            Africa        PERSON
6            Zürich           GPE
7            Europe           GPE
8   Central America  ORGANIZATION
9     South America           GPE
10            Spain           GPE
11      Netherlands           GPE
12             FIFA  ORGANIZATION
13          Oceania           GPE
14           Sweden           GPE
15          Germany           GPE
16          Belgium           GPE
17           France           GPE

NLTKのNERタスクは一般的に十分に完了していることがわかります。FIFAを組織(ORGANIZATION)として、ベルギーとアジアをGPEとして識別できます
が、中米をORGANIZATIONとして認識しているなど、不十分な場所もいくつかあります。しかし実際にはそれはGPEでなければなりません;アフリカを人として認識するためには、それは実際にはGPEでなければなりません。

第4に、StanfordNLPを使用してNERタスクを実装します

1.スタンフォードNLPツールを使用する前の環境への設置
1)Javaをインストールします

Stanford NLPツールを使用する前に、コンピューターにJava(通常はJDK)をインストールし、システムパスにJavaを追加する必要があります。
ubuntuシステムにjava8をダウンロードする方法は次のとおりです。https
//blog.csdn.net/mucaoyx/article/details/82949450Javalが配置されているパスは次のとおりです。/opt/java/jdk1.8.0_261/bin

2)スタンフォードNERをダウンロードする

英語のNERファイルパッケージをダウンロードします:stanford-ner-2018-10-16.zip(サイズ172MB)、ダウンロードアドレスは次のとおりです:https://nlp.stanford.edu/software/CRF-NER.shtml
ここに画像の説明を挿入
ここに画像の説明を挿入
のzipをダウンロードしますStanford NERファイルが解凍された後のフォルダーのパスは次のとおりです。次の/home/nijiahui/anaconda3/envs/nlp/lib/python3.6/site-packages/stanford-ner-4.0.0図に示すように:
classiferフォルダーには次のファイルがあります。
ここに画像の説明を挿入
それらの意味は次のとおりです。

3 class: Location, Person, Organization
4 class: Location, Person, Organization, Misc
7 class: Location, Person, Organization, Money, Percent, Date, Time
2.PythonはStanfordNERコードを実装します

Pythonを使用してStanfordNERを実装します。完全なコードは、次のとおりです。

import re
from nltk.tag import StanfordNERTagger
import os
import pandas as pd
import nltk

def parse_document(document):
   document = re.sub('\n', ' ', document)
   if isinstance(document, str):
       document = document
   else:
       raise ValueError('Document is not string!')
   document = document.strip()
   sentences = nltk.sent_tokenize(document)
   sentences = [sentence.strip() for sentence in sentences]
   return sentences

# sample document
text = """
FIFA was founded in 1904 to oversee international competition among the national associations of Belgium, 
Denmark, France, Germany, the Netherlands, Spain, Sweden, and Switzerland. Headquartered in Zürich, its 
membership now comprises 211 national associations. Member countries must each also be members of one of 
the six regional confederations into which the world is divided: Africa, Asia, Europe, North & Central America 
and the Caribbean, Oceania, and South America.
"""

sentences = parse_document(text)
tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]

# set java path in environment variables
java_path = r'C:\Program Files\Java\jdk1.8.0_161\bin\java.exe'
os.environ['JAVAHOME'] = java_path
# load stanford NER
sn = StanfordNERTagger('E://stanford-ner-2018-10-16/classifiers/english.muc.7class.distsim.crf.ser.gz',
                       path_to_jar='E://stanford-ner-2018-10-16/stanford-ner.jar')

# tag sentences
ne_annotated_sentences = [sn.tag(sent) for sent in tokenized_sentences]
# extract named entities
named_entities = []
for sentence in ne_annotated_sentences:
   temp_entity_name = ''
   temp_named_entity = None
   for term, tag in sentence:
       # get terms with NE tags
       if tag != 'O':
           temp_entity_name = ' '.join([temp_entity_name, term]).strip() #get NE name
           temp_named_entity = (temp_entity_name, tag) # get NE and its category
       else:
           if temp_named_entity:
               named_entities.append(temp_named_entity)
               temp_entity_name = ''
               temp_named_entity = None

# get unique named entities
named_entities = list(set(named_entities))
# store named entities in a data frame
entity_frame = pd.DataFrame(named_entities, columns=['Entity Name', 'Entity Type'])
# display results
print(entity_frame)

# ----------output----------
                Entity Name   Entity Type
0                   Belgium      LOCATION
1   North & Central America  ORGANIZATION
2                 Caribbean      LOCATION
3                    France      LOCATION
4                      1904          DATE
5             South America      LOCATION
6                      Asia      LOCATION
7                   Denmark      LOCATION
8                    Zürich      LOCATION
9                      FIFA  ORGANIZATION
10                   Sweden      LOCATION
11                    Spain      LOCATION
12                   Europe      LOCATION
13                  Oceania      LOCATION
14                   Africa      LOCATION
15          the Netherlands      LOCATION
16              Switzerland      LOCATION
17                  Germany      LOCATION

スタンフォードNERの助けを借りて、NERの実装効果が向上していることがわかります。アフリカはLOCATIONとして認識され、1904は時間として認識されます(これはNLTKでは認識されません)が、北および中央アメリカの認識は依然としてです。間違っています。組織として識別してください。

五数要約

スタンフォードNERがNLTKNERよりも優れているとは限らないことは注目に値します。この2つの対象となるオブジェクト、コーパス、およびアルゴリズムは異なる場合があるため、必要に応じて使用するツールを決定する必要があります。

おすすめ

転載: blog.csdn.net/TFATS/article/details/109098400