2016-12-05 15 views
0

現在、Naive Bayesを使用して複数のテキストを分類しています。私は複数のカテゴリを持っています。今私は事後確率とカテゴリーを出力していますが、私がしたいことは事後確率に基づいてカテゴリーをランク付けし、第2位、第3位カテゴリーを「バックアップ」カテゴリーとして使用することです。NLTKでNaive Bayesを使用してテキスト文字列を複数のクラスに分類する

df = pandas.DataFrame({ 'text' : pandas.Categorical(["I have wings","Metal wings","Feathers","Airport"]), 'true_cat' : pandas.Categorical(["bird","plane","bird","plane"])}) 

text   true_cat 
----------------------- 
I have wings bird 
Metal wings plane 
Feathers  bird 
Airport  plane 

私がやっている:ここで

は一例です

new_cat = classifier.classify(features(text)) 
prob_cat = classifier.prob_classify(features(text)) 

最終的な出力:私はclassify_manyを使用してカップルの例を発見した

new_cat prob_cat text   true_cat 
bird 0.67  I have wings bird 
bird 0.6   Feathers  bird 
bird 0.51  Metal wings plane 
plane 0.8   Airport  plane 

prob_classify_manyしかし、私はPythonを初めて使っているので、問題に翻訳するのに問題があります。私はそれがパンダでどこでも使われているのを見たことがありません。

私はそれは次のようになりたい:

df_new = pandas.DataFrame({'text': pandas.Categorical(["I have wings","Metal wings","Feathers","Airport"]),'true_cat': pandas.Categorical(["bird","plane","bird","plane"]), 'new_cat1': pandas.Categorical(["bird","bird","bird","plane"]), 'new_cat2': pandas.Categorical(["plane","plane","plane","bird"]), 'prob_cat1': pandas.Categorical(["0.67","0.51","0.6","0.8"]), 'prob_cat2': pandas.Categorical(["0.33","0.49","0.4","0.2"])}) 


new_cat1 new_cat2 prob_cat1 prob_cat2 text   true_cat 
----------------------------------------------------------------------- 
bird  plane  0.67  0.33  I have wings bird 
bird  plane  0.51  0.49  Metal wings plane 
bird  plane  0.6   0.4   Feathers  bird 
plane  bird  0.8   0.2   Airport  plane 

任意の助けをいただければ幸いです。

答えて

1

あなたの自己回答をあなたの質問の一部として扱っています。

ここ
prob_cat.prob("bird") 

prob_catはNLTK確率分布(ProbDist)です:おそらくあなたは、このような分類birdの確率を得ました。あなたはすでにあなたが訓練を受けたカテゴリを知っているので、あなたが代わりにprob_cat.samples()の定義済みリストを使用することができます

probs = list((x, prob_cat.prob(x)) for x in prob_cat.samples()) 

:あなたはすべての離散ProbDistのカテゴリと、このような彼らの確率を得ることができます。最後に、あなたは同じ表現の中から可能性の高いものから順不同に並べ替えることができます:

mycategories = ["bird", "plane"] 
probs = sorted(((x, prob_cat.prob(x)) for x in mycategories), key=lambda tup: -tup[1]) 
+0

完璧、ありがとう! –

0

私は今そこに着いています。私はカテゴリの数十を持っているので

#This gives me the probability it's a bird. 
prob_cat.prob(bird) 

#This gives me the probability it's a plane. 
prob_cat.prob(plane) 

は今、私はそれは、カテゴリ名のすべてを入れずに私にそれらのすべてを与える持っている良い方法に取り組んでいますが、それは非常に単純でなければなりません。

関連する問題