2017-12-03 23 views
1

저는 NLTK를 처음 사용하고 아직 Python에 새로 입문했습니다. NLTK의 Perceptron tagger를 훈련하고 테스트하기 위해 자체 데이터 세트를 사용하고 싶습니다. 나는 몇 가지를 시도했습니다NLTK에 대한 내 자신의 데이터 세트 읽기 PerceptronTagger를 사용하여 음성 태깅 파트

perceptron_tagger = nltk.tag.perceptron.PerceptronTagger(load=False) 
perceptron_tagger.train(train_data) 
accuracy = perceptron_tagger.evaluate(test_data) 

:

Pierre NNP 
Vinken NNP 
,  , 
61  CD 
years NNS 
old  JJ 
,  , 
will MD 
join VB 
the  DT 
board NN 
as  IN 
a  DT 
nonexecutive JJ 
director  NN 
Nov. NNP 
29  CD 
.  . 

내가 데이터에 이러한 함수를 호출 할 : 교육 및 테스트 데이터의 형식은 다음 (가 단지 txt 파일에 저장된 것)가 그러나 나는 데이터가 어떤 포맷으로 존재할 것으로 예상되는지 알 수 없다. 어떤 도움을 주시면 감사하겠습니다! 덕분에

답변

2

train()evaluate() 함수에 대한 입력에는 튜플 목록의 목록이 필요합니다. 각 내부 목록은 각 튜플이 한 쌍의 문자열 인 목록입니다.


을 감안할 때 train.txttest.txt :

$ cat train.txt 
This foo 
is foo 
a foo 
sentence bar 
. . 

That foo 
is foo 
another foo 
sentence bar 
in foo 
conll bar 
format bar 
. . 

$ cat test.txt 
What foo 
is foo 
this foo 
sentence bar 
? ? 

How foo 
about foo 
that foo 
sentence bar 
? ? 

은 튜플의리스트에 CoNLL 형식의 파일을 읽습니다.

# Using https://github.com/alvations/lazyme 
>>> from lazyme import per_section 
>>> tagged_train_sentences = [[tuple(token.split('\t')) for token in sent] for sent in per_section(open('train.txt'))] 

# Or otherwise 

>>> def per_section(it, is_delimiter=lambda x: x.isspace()): 
...  """ 
...  From http://stackoverflow.com/a/25226944/610569 
...  """ 
...  ret = [] 
...  for line in it: 
...   if is_delimiter(line): 
...    if ret: 
...     yield ret # OR ''.join(ret) 
...     ret = [] 
...   else: 
...    ret.append(line.rstrip()) # OR ret.append(line) 
...  if ret: 
...   yield ret 
... 
>>> 
>>> tagged_test_sentences = [[tuple(token.split('\t')) for token in sent] for sent in per_section(open('test.txt'))] 
>>> tagged_test_sentences 
[[('What', 'foo'), ('is', 'foo'), ('this', 'foo'), ('sentence', 'bar'), ('?', '?')], [('How', 'foo'), ('about', 'foo'), ('that', 'foo'), ('sentence', 'bar'), ('?', '?')]] 

이제/열차 술래 평가할 수 :

>>> from lazyme import per_section 
>>> tagged_train_sentences = [[tuple(token.split('\t')) for token in sent] for sent in per_section(open('train.txt'))] 
>>> from nltk.tag.perceptron import PerceptronTagger 
>>> pct = PerceptronTagger(load=False) 
>>> pct.train(tagged_train_sentences) 
>>> pct.tag('Where do I find a foo bar sentence ?'.split()) 
[('Where', 'foo'), ('do', 'foo'), ('I', '.'), ('find', 'foo'), ('a', 'foo'), ('foo', 'bar'), ('bar', 'foo'), ('sentence', 'bar'), ('?', '.')] 
>>> tagged_test_sentences = [[tuple(token.split('\t')) for token in sent] for sent in per_section(open('test.txt'))] 
>>> pct.evaluate(tagged_test_sentences) 
0.8 
+0

이 감사를! 이것은 훌륭한 설명이었다. – ellen