NeuralCoref는 Spacy 2.1+의 파이프 라인 확장으로, 신경망을 사용하여 코퍼레이션 클러스터에 주석을 달고 해결합니다. NeuralCoref는 생산 준비가되어 있으며 Spacy의 NLP 파이프 라인에 통합되어 있으며 새로운 교육 데이터 세트에 확장 가능합니다.
Correference Resolution 및 NeuralCoref에 대한 간단한 소개는 블로그 게시물을 참조하십시오. NeuralCoref는 Python/Cython으로 작성되었으며 영어 에 대한 미리 훈련 된 통계 모델이 제공됩니다.
NeuralCoref에는 온라인으로 시도 할 수있는 REST 서버로 구동되는 웹 인터페이스 인 시각화 클라이언트 NeuralCoref-Viz가 동반됩니다. NeuralCoref는 MIT 라이센스에 따라 릴리스됩니다.
지금 버전 4.0! PIP에서 사용할 수 있으며 Spacy 2.1+와 호환됩니다.
이것은 NeuralCoref를 설치하는 가장 쉬운 방법입니다.
pip install neuralcorefspacy.strings.StringStore size changed 오류 spacy.strings.StringStore size changed, may indicate binary incompatibility 오류가있는 경우 NeuralCoref를 import neuralcoref 로로드 할 때 이진 비 호환성을 나타낼 수 있습니다. 즉, 휠 대신 분포기에서 NeuralCoref를 설치해야합니다.
이 경우, 다음과 같이 신경계를 다시 설치하십시오.
pip uninstall neuralcoref
pip install neuralcoref --no-binary neuralcorefNeuralCoref를 사용할 수 있으려면 Spacy를위한 영어 모델도 필요합니다.
응용 프로그램에 적합한 영어 모델을 사용할 수 있지만 NeuralCoref의 성능은 스파크 모델의 성능, 특히 Spacy Model 's Tagger, Parser 및 NER 구성 요소의 성능에 크게 의존합니다. 따라서 더 큰 스파이의 영어 모델은 코퍼레이션 해상도의 품질도 향상시킬 것입니다 (아래의 내부 및 모델 섹션의 일부 세부 사항 참조).
다음은 Spacy를위한 Spacy 및 (작은) 영어 모델을 설치하는 방법의 예입니다. 자세한 내용은 Spacy 웹 사이트에서 확인할 수 있습니다.
pip install -U spacy
python -m spacy download en소스에서 NeuralCoref를 설치할 수도 있습니다. Cython 및 Spacy를 포함한 종속성을 먼저 설치해야합니다.
프로세스는 다음과 같습니다.
venv .env
source .env/bin/activate
git clone https://github.com/huggingface/neuralcoref.git
cd neuralcoref
pip install -r requirements.txt
pip install -e . Neuralcoref는 두 가지 하위 모듈로 만들어졌습니다.
Python에서 NeuralCoref를 처음으로 가져 오면 Cache 폴더에서 Neural Network 모델의 가중치를 다운로드합니다.
캐시 폴더는 기본값으로 ~/.neuralcoref_cache (file_utils.py 참조)로 설정되지만 환경 변수 NEURALCOREF_CACHE 다른 위치를 가리 키게 하여이 동작을 과도하게 조정할 수 있습니다.
캐시 폴더는 언제든지 안전하게 삭제할 수 있으며 다음에로드 할 때 모듈이 모델을 다시 다운로드합니다.
NeuralCoref를 다음과 같이로드하기 전에 Python의 logging 모듈을 활성화하여 내부 모델의 위치, 다운로드 및 캐싱 프로세스에 대한 자세한 정보를 얻을 수 있습니다.
import logging ;
logging . basicConfig ( level = logging . INFO )
import neuralcoref
> >> INFO : neuralcoref : Getting model from https : // s3 . amazonaws . com / models . huggingface . co / neuralcoref / neuralcoref . tar . gz or cache
> >> INFO : neuralcoref . file_utils : https : // s3 . amazonaws . com / models . huggingface . co / neuralcoref / neuralcoref . tar . gz not found in cache , downloading to / var / folders / yx / cw8n_njx3js5jksyw_qlp8p00000gn / T / tmp_8y5_52m
100 % | █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ | 40155833 / 40155833 [ 00 : 06 < 00 : 00 , 6679263.76 B / s ]
> >> INFO : neuralcoref . file_utils : copying / var / folders / yx / cw8n_njx3js5jksyw_qlp8p00000gn / T / tmp_8y5_52m to cache at / Users / thomaswolf / . neuralcoref_cache / f46bc05a4bfba2ae0d11ffd41c4777683fa78ed357dc04a23c67137abf675e14 . 7 d6f9a6fecf5cf09e74b65f85c7d6896b21decadb2554d486474f63b95ec4633
> >> INFO : neuralcoref . file_utils : creating metadata file for / Users / thomaswolf / . neuralcoref_cache / f46bc05a4bfba2ae0d11ffd41c4777683fa78ed357dc04a23c67137abf675e14 . 7 d6f9a6fecf5cf09e74b65f85c7d6896b21decadb2554d486474f63b95ec4633
>> > INFO : neuralcoref . file_utils : removing temp file / var / folders / yx / cw8n_njx3js5jksyw_qlp8p00000gn / T / tmp_8y5_52m
>> > INFO : neuralcoref : extracting archive file / Users / thomaswolf / . neuralcoref_cache / f46bc05a4bfba2ae0d11ffd41c4777683fa78ed357dc04a23c67137abf675e14 . 7 d6f9a6fecf5cf09e74b65f85c7d6896b21decadb2554d486474f63b95ec4633 to dir / Users / thomaswolf / . neuralcoref_cache / neuralcoref 다음은 NeuralCoref를 인스턴스화하여 Spacy의 주석 파이프 라인에 추가하는 권장 방법입니다.
# Load your usual SpaCy model (one of SpaCy English models)
import spacy
nlp = spacy . load ( 'en' )
# Add neural coref to SpaCy's pipe
import neuralcoref
neuralcoref . add_to_pipe ( nlp )
# You're done. You can now use NeuralCoref as you usually manipulate a SpaCy document annotations.
doc = nlp ( u'My sister has a dog. She loves him.' )
doc . _ . has_coref
doc . _ . coref_clustersSpacy 모델 파이프에 NeuralCoref를 추가하는 동등한 방법은 NeuralCoref 클래스를 먼저 인스턴스화 한 다음 Spacy Language 모델의 파이프에 수동으로 추가하는 것입니다.
# Load your usual SpaCy model (one of SpaCy English models)
import spacy
nlp = spacy . load ( 'en' )
# load NeuralCoref and add it to the pipe of SpaCy's model
import neuralcoref
coref = neuralcoref . NeuralCoref ( nlp . vocab )
nlp . add_pipe ( coref , name = 'neuralcoref' )
# You're done. You can now use NeuralCoref the same way you usually manipulate a SpaCy document and it's annotations.
doc = nlp ( u'My sister has a dog. She loves him.' )
doc . _ . has_coref
doc . _ . coref_clusters NeuralCoref는 코어 페리런스를 해결하고 ._의 스파크 Doc , Span 및 Token 객체의 확장 속성으로 주석을 달 것입니다 ._. 사전.
주석 목록은 다음과 같습니다.
| 기인하다 | 유형 | 설명 |
|---|---|---|
doc._.has_coref | 부울 | DOC에서 코어가 해결되었습니다 |
doc._.coref_clusters | Cluster 목록 | Corefering의 모든 클러스터는 문서에서 언급합니다 |
doc._.coref_resolved | 유니 코드 | 각 코어 퍼링 언급이 관련 클러스터의 주요 언급으로 대체되는 DOC의 유니 코드 표현. |
doc._.coref_scores | DITT의 DITT | 언급 사이의 코퍼레이션 해상도의 점수. |
span._.is_coref | 부울 | 스팬에 적어도 하나의 핵심 언급이 있는지 여부 |
span._.coref_cluster | Cluster | 클러스터의 클러스터는 그 범위와 코어 퍼팅을합니다 |
span._.coref_scores | DITT | 다른 언급 (해당되는 경우)의 코어 컨퍼런스 해상도 점수. |
token._.in_coref | 부울 | 토큰이 적어도 하나의 코어 퍼링 언급 내부에 있는지 여부 |
token._.coref_clusters | Cluster 목록 | 토큰이 포함 된 모든 코어 퍼링 언급 클러스터 |
Cluster 는 클러스터 내부에서 내비게이션을 단순화하는 3 가지 속성과 몇 가지 방법을 갖는 코어 퍼링 언급의 클러스터입니다.
| 속성 또는 방법 | 유형 / 반환 유형 | 설명 |
|---|---|---|
i | int | 문서에서 클러스터의 색인 |
main | Span | 클러스터에서 가장 대표적인 언급의 범위 |
mentions | Span 목록 | 클러스터의 모든 언급 목록 |
__getitem__ | 반환 Span | 클러스터에서 언급에 액세스하십시오 |
__iter__ | 수율 Span | 클러스터에 대한 언급을 반복하십시오 |
__len__ | int | 클러스터의 언급 수 |
또한 Coreference 클러스터 체인을 쉽게 탐색하고 클러스터 및 언급을 표시 할 수 있습니다.
다음은 몇 가지 예입니다. 직접 테스트하기 위해 시도해보십시오.
import spacy
import neuralcoref
nlp = spacy . load ( 'en' )
neuralcoref . add_to_pipe ( nlp )
doc = nlp ( u'My sister has a dog. She loves him' )
doc . _ . coref_clusters
doc . _ . coref_clusters [ 1 ]. mentions
doc . _ . coref_clusters [ 1 ]. mentions [ - 1 ]
doc . _ . coref_clusters [ 1 ]. mentions [ - 1 ]. _ . coref_cluster . main
token = doc [ - 1 ]
token . _ . in_coref
token . _ . coref_clusters
span = doc [ - 1 :]
span . _ . is_coref
span . _ . coref_cluster . main
span . _ . coref_cluster . main . _ . coref_cluster 중요 : NeuralCoref 언급은 Spacy Span 객체입니다. 즉 span.start (문서의 스팬의 첫 번째 토큰의 색인), span.end (문서의 첫 번째 토큰의 색인) 등의 모든 일반적인 범위 속성에 액세스 할 수 있습니다.
예 : doc._.coref_clusters[1].mentions[-1].start 문서에서 두 번째 Corections 클러스터에 대한 마지막 언급의 첫 번째 토큰의 색인을 제공합니다.
NeuralCoref의 동작을 제어하기 위해 몇 가지 추가 매개 변수를 neuralcoref.add_to_pipe 또는 NeuralCoref() 로 전달할 수 있습니다.
다음은 이러한 매개 변수와 그 설명의 전체 목록입니다.
| 매개 변수 | 유형 | 설명 |
|---|---|---|
greedyness | 뜨다 | 0과 1 사이의 숫자는 모델이 욕심이 얼마나 욕심이 많은지를 결정하는 것입니다 (더 탐욕은 더 많은 욕구 링크를 의미합니다). 기본값은 0.5입니다. |
max_dist | int | 현재 언급의 가능한 선행자를 고려할 때 얼마나 많은 언급이 되돌아 보는가. 값을 줄이면 시스템이 더 빠르지 만 정확하게 실행됩니다. 기본값은 50입니다. |
max_dist_match | int | 이 시스템은 명사 또는 적절한 명사를 공유하는 경우 현재의 언급을 max_dist 보다 앞의 언급에 연결하는 것을 고려할 것입니다. 이 경우 대신 max_dist_match 로 보입니다. 기본값은 500입니다. |
blacklist | 부울 | 시스템이 다음 목록에서 대명사에 대한 핵심을 해결하면 : ["i", "me", "my", "you", "your"] . 기본값은 true입니다 (Correference Resolded). |
store_scores | 부울 | 시스템이 주석에 핵심 점수를 저장해야합니다. 기본값은 참입니다. |
conv_dict | dict (str, list (str)) | 희귀 단어 (키)의 임베딩을 일반 단어 목록 (값)의 평균으로 대체하는 데 사용할 수있는 전환 사전. 예 : conv_dict={"Angela": ["woman", "girl"]} Angela 의 삽입 대신 더 일반적인 woman 와 girl 를위한 임베딩을 사용하여 Angela 의 핵심을 해결하는 데 도움이됩니다. 이것은 현재 단일 단어에 대해서만 작동합니다 (단어 그룹이 아닌). |
import spacy
import neuralcoref
# Let's load a SpaCy model
nlp = spacy . load ( 'en' )
# First way we can control a parameter
neuralcoref . add_to_pipe ( nlp , greedyness = 0.75 )
# Another way we can control a parameter
nlp . remove_pipe ( "neuralcoref" ) # This remove the current neuralcoref instance from SpaCy pipe
coref = neuralcoref . NeuralCoref ( nlp . vocab , greedyness = 0.75 )
nlp . add_pipe ( coref , name = 'neuralcoref' ) 다음은 이름과 같은 희귀 단어의 핵심을 해결하기 위해 매개 conv_dict 사용하는 방법에 대한 예입니다.
import spacy
import neuralcoref
nlp = spacy . load ( 'en' )
# Let's try before using the conversion dictionary:
neuralcoref . add_to_pipe ( nlp )
doc = nlp ( u'Deepika has a dog. She loves him. The movie star has always been fond of animals' )
doc . _ . coref_clusters
doc . _ . coref_resolved
# >>> [Deepika: [Deepika, She, him, The movie star]]
# >>> 'Deepika has a dog. Deepika loves Deepika. Deepika has always been fond of animals'
# >>> Not very good...
# Here are three ways we can add the conversion dictionary
nlp . remove_pipe ( "neuralcoref" )
neuralcoref . add_to_pipe ( nlp , conv_dict = { 'Deepika' : [ 'woman' , 'actress' ]})
# or
nlp . remove_pipe ( "neuralcoref" )
coref = neuralcoref . NeuralCoref ( nlp . vocab , conv_dict = { 'Deepika' : [ 'woman' , 'actress' ]})
nlp . add_pipe ( coref , name = 'neuralcoref' )
# or after NeuralCoref is already in SpaCy's pipe, by modifying NeuralCoref in the pipeline
nlp . get_pipe ( 'neuralcoref' ). set_conv_dict ({ 'Deepika' : [ 'woman' , 'actress' ]})
# Let's try agin with the conversion dictionary:
doc = nlp ( u'Deepika has a dog. She loves him. The movie star has always been fond of animals' )
doc . _ . coref_clusters
# >>> [Deepika: [Deepika, She, The movie star], a dog: [a dog, him]]
# >>> 'Deepika has a dog. Deepika loves a dog. Deepika has always been fond of animals'
# >>> A lot better! REST API에서 NeuralCoref를 통합하기위한 서버 스크립트의 간단한 예는 examples/server.py 의 예제로 제공됩니다.
이를 사용하려면 먼저 Falcon을 설치해야합니다.
pip install falcon그런 다음 다음과 같이 서버를 시작할 수 있습니다.
cd examples
python ./server.py그리고 다음과 같이 서버를 쿼리하십시오.
curl --data-urlencode " text=My sister has a dog. She loves him. " -G localhost:8000NeuralCoref를 관리하고 배포 할 수있는 다른 방법은 여러 가지가 있습니다. 일부 예는 Spacy Universe에서 찾을 수 있습니다.
모델을 재교육하거나 다른 언어로 훈련하려면 교육 지침과 블로그 게시물을 참조하십시오.