3

次のコードでは、naivebayesクラシファイアがtrainset1で正しく動作しているが、なぜtrainset2で動作していないのかが分かります。私はTextBlobからのものとnltkから直接のものの2つの分類器でそれを試しました。nltk naivebayesテキスト分類用の分類器

from textblob.classifiers import NaiveBayesClassifier 
from textblob import TextBlob 
from nltk.tokenize import word_tokenize 
import nltk 

trainset1 = [('I love this sandwich.', 'pos'), 
('This is an amazing place!', 'pos'), 
('I feel very good about these beers.', 'pos'), 
('This is my best work.', 'pos'), 
("What an awesome view", 'pos'), 
('I do not like this restaurant', 'neg'), 
('I am tired of this stuff.', 'neg'), 
("I can't deal with this", 'neg'), 
('He is my sworn enemy!', 'neg'), 
('My boss is horrible.', 'neg')] 

trainset2 = [('hide all brazil and everything plan limps to anniversary inflation plan initiallyis limping its first anniversary amid soaring prices', 'class1'), 
     ('hello i was there and no one came', 'class2'), 
     ('all negative terms like sad angry etc', 'class2')] 

def nltk_naivebayes(trainset, test_sentence): 
    all_words = set(word.lower() for passage in trainset for word in word_tokenize(passage[0])) 
    t = [({word: (word in word_tokenize(x[0])) for word in all_words}, x[1]) for x in trainset] 
    classifier = nltk.NaiveBayesClassifier.train(t) 
    test_sent_features = {word.lower(): (word in word_tokenize(test_sentence.lower())) for word in all_words} 
    return classifier.classify(test_sent_features) 

def textblob_naivebayes(trainset, test_sentence): 
    cl = NaiveBayesClassifier(trainset) 
    blob = TextBlob(test_sentence,classifier=cl) 
    return blob.classify() 

test_sentence1 = "he is my horrible enemy" 
test_sentence2 = "inflation soaring limps to anniversary" 

print nltk_naivebayes(trainset1, test_sentence1) 
print nltk_naivebayes(trainset2, test_sentence2) 
print textblob_naivebayes(trainset1, test_sentence1) 
print textblob_naivebayes(trainset2, test_sentence2) 

出力:

neg 
class2 
neg 
class2 

test_sentence2がはっきりCLASS1に属しますが。

答えて

3

分類子には3つの例しかない良いモデルを習得することは期待できません。この具体例では、なぜそれがそれを行うのかを理解することが多くなります。

ナイーブベイイ分類器は、以前のクラス確率を使用する可能性が高いと考えられます。すなわち、テキストに関係なく、ネガ対ポジションの確率。あなたのケースでは、例の2/3が負であるため、前者はネガティブで66%、posでは33%です。あなたの1つの肯定的なインスタンスにおける肯定的な言葉は、「記念日」と「急上昇」です。これは、この先のクラスの確率を補うのに十分ではありません。

特に単語の確率の計算には、低頻度の単語を防ぐためにlog10(Term Frequency)ではなく、各クラスでlog10(Term Frequency + 1)になるようなさまざまな '平滑化'関数が含まれていることに注意してください分類結果、ゼロ除算などに多大な影響を及ぼす可能性があります。したがって、 "記念日"と "急上昇"の確率は、あなたが期待していたようにnegでは0.0、posでは1.0ではありません。

関連する問題