机器学习实战笔记(3)-朴素贝叶斯算法(代码实现)
书中第一个例子给的样本如下: 6句话,三句脏话,三句好话。
[['my', 'dog', 'has', 'flea', 'problems', 'help','please'] -- Good words
['maybe', 'not', 'take', 'him', 'to', 'dog', 'park','stupid'] -- Shit words
['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love','him'] -- Good words
['stop', 'posting', 'stupid', 'worthless', 'garbage'] --Shit words
['mr', 'licks', 'ate', 'my', 'steak', 'how', 'to', 'stop','him'] -- Good words
['quit', 'buying', 'worthless', 'dog', 'food', 'stupid']]-- Shit words
目前采用的算法是贝努力类型的朴素贝叶斯,就是对于文本分析,我们只考虑词是否出现,而不考虑出现的次数。
也就是所有的词都是一个权重!模型虽然简单,但是效果还是不错地。
首先是所有出现单词的列表:这里是只看出现不出现,不看频次。
['cute', 'love','help', 'garbage', 'quit', 'I', 'problems', 'is', 'park', 'stop', 'flea','dalmation', 'licks', 'food', 'not', 'him', 'buying', 'posting', 'has','worthless', 'ate', 'to', 'maybe', 'please', 'dog', 'how', 'stupid', 'so','take', 'mr', 'steak', 'my']
>>>
然后根据每个句子的单词,生成对应句子的向量,就是单词是否出现。
句子矩阵:
[0, 0, 1, 0, 0, 0,1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1] --Good words
[0, 0, 0, 0, 0, 0,0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0] -- Shitwords
[1, 1, 0, 0, 0, 1,0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1] --Good words