Textblob 逻辑帮助。 NaiveBayes分类器
Posted
技术标签:
【中文标题】Textblob 逻辑帮助。 NaiveBayes分类器【英文标题】:Textblob logic help. NaiveBayesClassifier 【发布时间】:2017-11-13 19:28:46 【问题描述】:我正在构建一个简单的分类器,用于确定句子是否为正。这就是我使用 textblob 训练分类器的方式。
train = [
'i love your website', 'pos',
'i really like your site', 'pos',
'i dont like your website', 'neg',
'i dislike your site', 'neg
]
cl.NaiveBayesClassifier(train)
#im clasifying text from twitter using tweepy and it goes like this and
stored into the databse and using the django to save me doing all the hassle
of the backend
class StdOutListener(StreamListener)
def __init__(self)
self.raw_tweets = []
self.raw_teets.append(jsin.loads(data)
def on_data(self, data):
tweets = Htweets() # connection to the database
for x in self.raw_data:
tweets.tweet_text = x['text']
cl.classify(x['text'])
if classify(x['text]) == 'pos'
tweets.verdict = 'pos'
elif classify(x['text]) == 'neg':
tweets.verdict = 'neg'
else:
tweets.verdict = 'normal'
逻辑看起来很简单,但是当我训练分类器是正面还是负面时,它应该将判决与推文一起保存到数据库中。
但这似乎并非如此,我一直在以多种方式改变逻辑,但仍然不成功。问题是推文是肯定的还是否定的,是的,算法确实可以识别它们。
但是,如果它们不是并且它没有这样做,我希望它保存“正常”。我承认分类器只能识别正面或负面的两件事,但它当然也应该识别文本是否不属于此类别。
在使用 textblob 时这怎么可能。示例替代逻辑和建议将非常感谢。
【问题讨论】:
实现这一目标的常用方法是创建第三类:中立,并提供示例。 我不认为 textblob 接受第三类它给出了太多的值解包错误 然后你可以创建两个二元分类器,一个 neg 对中性,另一个 pos 对中性。中性可以表示“没有表达情绪”或“平衡的情绪”(尽可能多的 pos 和 neg)。因此,同一个实例有可能被它们各自的分类器分类为正面和负面(由您决定是中性的还是第四类,平衡的) 【参考方案1】:分类总是会给你一个最大概率的答案,所以你应该使用prob_classify
方法来获得你的类别标签的概率分布。在观察概率分布并设置适当的置信度阈值后,您也将通过良好的训练集开始获得“中性”分类。
用最小的训练集来反映这个概念的例子,对于实际使用,你应该使用一个大的训练集:
>>> train
[('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')]
>>> from pprint import pprint
>>> pprint(train)
[('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')]
>>> train2 = [('science is a subject','neu'),('this is horrible food','neg'),('glass has water','neu')]
>>> train = train+train2
>>> from textblob.classifiers import NaiveBayesClassifier
>>> cl = NaiveBayesClassifier(train)
>>> prob_dist = cl.prob_classify("I had a horrible day,I am tired")
>>> (prob_dist.prob('pos'),prob_dist.prob('neg'),prob_dist.prob('neu'))
(0.01085221171283812, 0.9746799258978173, 0.014467862389343378)
>>>
>>> prob_dist = cl.prob_classify("This is a subject")
>>> (prob_dist.prob('pos'),prob_dist.prob('neg'),prob_dist.prob('neu'))
(0.10789848368588585, 0.14908905046805337, 0.7430124658460614)
【讨论】:
以上是关于Textblob 逻辑帮助。 NaiveBayes分类器的主要内容,如果未能解决你的问题,请参考以下文章