英語(yǔ)文本處理工具庫(kù)2 — spaCy

網(wǎng)易云課堂AI工程師(自然語(yǔ)言處理)學(xué)習(xí)筆記,接上一篇《英文文本處理工具庫(kù)1 — NLTK》。


1. spaCy簡(jiǎn)介

spaCy
spaCy是Python和Cython中的高級(jí)自然語(yǔ)言處理庫(kù),它建立在最新的研究基礎(chǔ)之上,從一開(kāi)始就設(shè)計(jì)用于實(shí)際產(chǎn)品。

spaCy 帶有預(yù)先訓(xùn)練的統(tǒng)計(jì)模型和單詞向量,目前支持 34+語(yǔ)言的標(biāo)記(暫不支持中文)。它具有世界上速度最快的句法分析器,用于標(biāo)簽的卷積神經(jīng)網(wǎng)絡(luò)模型,解析和命名實(shí)體識(shí)別以及與深度學(xué)習(xí)整合。

2. spaCy與NLTK的對(duì)比

image.png

3. spaCy安裝

windows + Anoconda環(huán)境,使用conda命令安裝比較方便:

conda config --add channels conda-forge
conda install spacy
python -m spacy download en

參考:Windows下在anaconda環(huán)境中安裝自然語(yǔ)言處理工具---Spacy

4. spaCy基本操作

(1)英文Tokenization(標(biāo)記化/分詞)

import spacy
nlp = spacy.load('en')

doc = nlp('Hello! My name is LittleTree!')
print("分詞如下:")
for token in doc:
    print(token.text)

print("\n斷句如下:")
for sent in doc.sents:
    print(sent)
輸出

每個(gè)token對(duì)象有著非常豐富的屬性,如下的方式可以取出其中的部分屬性。

doc = nlp("Next week I'll be in SZ.")
for token in doc:
    print("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}".format(
        token.text,
        token.idx,
        token.lemma_,
        token.is_punct,
        token.is_space,
        token.shape_,
        token.pos_,
        token.tag_
    ))
輸出

(2)詞性標(biāo)注

doc = nlp("Next week I'll be in Shanghai.")
print([(token.text, token.tag_) for token in doc])

輸出:
[('Next', 'JJ'), ('week', 'NN'), ('I', 'PRP'), ("'ll", 'MD'), ('be', 'VB'), ('in', 'IN'), ('Shanghai', 'NNP'), ('.', '.')]

(3)命名實(shí)體識(shí)別

doc = nlp("Next week I'll be in Shanghai.")
for ent in doc.ents:
    print(ent.text, ent.label_)

輸出:
Next week DATE
Shanghai GPE

還可以用非常漂亮的可視化做顯示:

from spacy import displacy

displacy.render(doc, style='ent', jupyter=True)
輸出

(4)chunking/組塊分析

spaCy可以自動(dòng)檢測(cè)名詞短語(yǔ),并輸出根(root)詞,比如下面的"Journal","piece","currencies".

doc = nlp("Wall Street Journal just published an interesting piece on crypto currencies")
for chunk in doc.noun_chunks:
    print(chunk.text, chunk.label_, chunk.root.text)
輸出

(5)句法依存解析

doc = nlp('Wall Street Journal just published an interesting piece on crypto currencies')
 
for token in doc:
    print("{0}/{1} <--{2}-- {3}/{4}".format(
        token.text, token.tag_, token.dep_, token.head.text, token.head.tag_))
輸出

(6)詞向量使用

NLP中有一個(gè)非常強(qiáng)大的文本表示學(xué)習(xí)方法叫做word2vec,通過(guò)詞的上下文學(xué)習(xí)到詞語(yǔ)的稠密向量化表示,同時(shí)在這個(gè)表示形態(tài)下,語(yǔ)義相關(guān)的詞在向量空間中會(huì)比較接近。也有類似v(爺爺)-v(奶奶) ≈ v(男人)-v(女人)的關(guān)系。

關(guān)于詞向量的詳細(xì)內(nèi)容,請(qǐng)參考吳恩達(dá)序列模型第二課自然語(yǔ)言處理與詞嵌入

在spaCy中,要使用英文的詞向量,需先下載預(yù)先訓(xùn)練好的結(jié)果,終端命令如下:

python3 -m spacy download en_core_web_lg

下面我們使用詞向量來(lái)做一些有趣的事情。

nlp = spacy.load('en_core_web_lg')
from scipy import spatial

# 余弦相似度計(jì)算
cosine_similarity = lambda x, y: 1 - spatial.distance.cosine(x, y)

# 男人、女人、國(guó)王、女王 的詞向量
man = nlp.vocab['man'].vector
woman = nlp.vocab['woman'].vector
queen = nlp.vocab['queen'].vector
king = nlp.vocab['king'].vector
 
# 我們對(duì)向量做一個(gè)簡(jiǎn)單的計(jì)算,"man" - "woman" + "queen"
maybe_king = man - woman + queen
computed_similarities = []

# 掃描整個(gè)詞庫(kù)的詞向量做比對(duì),召回最接近的詞向量
for word in nlp.vocab:
    if not word.has_vector:
        continue
 
    similarity = cosine_similarity(maybe_king, word.vector)
    computed_similarities.append((word, similarity))

# 排序與最接近結(jié)果展示
computed_similarities = sorted(computed_similarities, key=lambda item: -item[1])
print([w[0].text for w in computed_similarities[:10]])

輸出:
['Queen', 'QUEEN', 'queen', 'King', 'KING', 'king', 'KIng', 'Kings', 'KINGS', 'kings']

(7)詞匯與文本相似度

在詞向量的基礎(chǔ)上,spaCy提供了從詞到文檔的相似度計(jì)算的方法,下面的例子是它的使用方法。

# 詞匯語(yǔ)義相似度(關(guān)聯(lián)性)
banana = nlp.vocab['banana']
dog = nlp.vocab['dog']
fruit = nlp.vocab['fruit']
animal = nlp.vocab['animal']
 
print(dog.similarity(animal), dog.similarity(fruit)) # 0.6618534 0.23552845
print(banana.similarity(fruit), banana.similarity(animal)) # 0.67148364 0.2427285
# 文本語(yǔ)義相似度(關(guān)聯(lián)性)
target = nlp("Cats are beautiful animals.")
 
doc1 = nlp("Dogs are awesome.")
doc2 = nlp("Some gorgeous creatures are felines.")
doc3 = nlp("Dolphins are swimming mammals.")
 
print(target.similarity(doc1))  # 0.8901765218466683
print(target.similarity(doc2))  # 0.9115828449161616
print(target.similarity(doc3))  # 0.7822956752876101

持續(xù)更新中,要不要點(diǎn)個(gè)小??鼓勵(lì)鼓勵(lì)我(????)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容