天天看點

Stanford Named Entity Recognizer (NER)簡單應用執行個體

Stanford Named Entity Recognizer (NER)是斯坦福大學自然語言研究小組釋出的成果之一,

其首頁是:http://nlp.stanford.edu/software/CRF-NER.shtml

Stanford NER 是一個Java實作的命名實體識别(以下簡稱NER)程式。NER将文本中的實體按類标記出來,例如人名,公司名,地區,基因和蛋白質的名字等。

NER基于一個訓練而得的Model工作,用于訓練的資料即大量人工标記好的文本,理論上用于訓練的資料量越大,NER的識别效果就越好。

斯坦福小組給出了三個訓練好的Model:

  1. Location, Person, Organization
  2. Location, Person, Organization, Misc
  3. Time, Location, Organization, Person, Money, Percent, Date

但不幸的是,這三個Model都不能被擴充,用于訓練的資料也不公開,是以想要一個适應自己需求的Model我們隻能從頭訓練。

下面我們就用一個簡單的例子來摸索一下如何訓練一個新的Model并用它嘗試識别幾個簡單的句子。

首先從首頁下載下傳Stanford Named Entity Recognizer:http://nlp.stanford.edu/software/stanford-ner-2013-11-12.zip 解壓即可。

文中提到的訓練資料、配置檔案、Model和完整工程可從網盤下載下傳:http://pan.baidu.com/s/1xNAqD

準備訓練資料

Stanford Named Entity Recognizer (NER)簡單應用執行個體

這是本例所使用的訓練資料,包含标記好的兩句話:Today is Friday. Tomorrow is 11/30.

如圖,句子中的每個單詞獨立成行,Tab後跟該單詞的類别,預設為O。例中,我們标記了Friday為WEEK,11/30為DATE,其餘均為預設。

訓練獲得Model

官方說雖然所有的參數都可以通過指令行的方式指定,但更推薦用配置檔案的方式。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 #location of the training file trainFile = testdata . tsv #location where you would like to save (serialize to) your #classifier; adding .gz at the end automatically gzips the file, #making it faster and smaller serializeTo = ner - model . ser . gz   #structure of your training file; this tells the classifier #that the word is in column 0 and the correct answer is in #column 1 map = word = 0 , answer = 1   #these are the features we'd like to train with #some are discussed below, the rest can be #understood by looking at NERFeatureFactory useClassFeature = true useWord = true useNGrams = true #no ngrams will be included that do not contain either the #beginning or end of the word noMidNGrams = true useDisjunctive = true maxNGramLeng = 6 usePrev = true useNext = true useSequences = true usePrevSequences = true maxLeft = 1 #the next 4 deal with word shape features useTypeSeqs = true useTypeSeqs2 = true useTypeySequences = true wordShape = chris2useLC

其中trainFile =testdata.tsv指定了我們用于訓練的資料,serializeTo = ner-model.ser.gz指定了輸出model的名字,其餘參數也均有注釋說明。

我們将該配置檔案austen.prop和訓練資料testdata.tsv都放到stanford-ner-2013-11-12檔案夾中。

cmd中将目前目錄切換到stanford-ner-2013-11-12檔案夾,并執行指令:

java -cp stanford-ner.jar edu.stanford.nlp.ie.crf.CRFClassifier -prop austen.prop

執行成功後,我們就可以看到目錄下多了ner-model.ser.gz,這就是通過我們的訓練資料得到的model。

嘗試識别

Stanford Named Entity Recognizer (NER)簡單應用執行個體

Stanford Named Entity Recognizer (NER)簡單應用執行個體
将剛剛生成的ner-model.ser.gz放到工程根目錄下,在代碼中擷取以後,嘗試用它解析我們的兩個輸入:

1. The next day is Friday

2. Today is 11/29

運作後得到:

The/O next/O day/O is/O Friday/WEEK

Today/O is/O 11/29/DATE

可以看到測試資料中的Friday和11/29都被識别了出來。

注意:在運作這個例子的時候有可能不成功,不成功的原因可能是因為JDK的版本問題,在首頁中有一句話“ Stanford NER requires Java v1.8+.”,是以,JDK的版本需要1.8,看看自己的JDK的版本是否符合。