尝试在 R 中使用朴素贝叶斯学习器,但 predict() 给出的结果与模型建议的结果不同



我正在尝试使用e1071的朴素贝叶斯学习者进行垃圾邮件分析。这是我用来设置模型的代码。

library(e1071)
emails=read.csv("emails.csv")
emailstrain=read.csv("emailstrain.csv")
model<-naiveBayes(type ~.,data=emailstrain)

有两组电子邮件,都有"声明"和类型。一个用于培训,一个用于测试。当我跑步时

model

只需阅读原始输出,当语句确实是垃圾邮件时,它似乎为语句提供了更高的百分比,而不是零,当语句不是垃圾邮件时也是如此。但是,当我尝试使用该模型来预测测试数据时

table(predict(model,emails),emails$type)

我明白了

    ham  spam
ham 2086 321
spam 2   0

这似乎是错误的。 我还尝试使用训练集来测试数据,在这种情况下,它应该给出相当好的结果,或者至少与模型中观察到的结果一样好。然而它给了

    ham  spam
ham 2735 420
spam 0   6

这仅比测试集略好。我认为预测函数的工作方式一定有问题。

如何设置数据文件以及其中内容的一些示例:

type,statement
ham,How much did ur hdd casing cost.
ham,Mystery solved! Just opened my email and he's sent me another batch! Isn't he a sweetie
ham,I can't describe how lucky you are that I'm actually awake by noon
spam,This is the 2nd time we have tried to contact u. U have won the £1450 prize to claim just call 09053750005 b4 310303. T&Cs/stop SMS 08718725756. 140ppm
ham,"TODAY is Sorry day.! If ever i was angry with you, if ever i misbehaved or hurt you? plz plz JUST SLAP URSELF Bcoz, Its ur fault, I'm basically GOOD"
ham,Cheers for the card ... Is it that time of year already?
spam,"HOT LIVE FANTASIES call now 08707509020 Just 20p per min NTT Ltd, PO Box 1327 Croydon CR9 5WB 0870..k"
ham,"When people see my msgs, They think Iam addicted to msging... They are wrong, Bcoz They don't know that Iam addicted to my sweet Friends..!! BSLVYL"
ham,Ugh hopefully the asus ppl dont randomly do a reformat.
ham,"Haven't seen my facebook, huh? Lol!"
ham,"Mah b, I'll pick it up tomorrow"
ham,Still otside le..u come 2morrow maga..
ham,Do u still have plumbers tape and a wrench we could borrow?
spam,"Dear Voucher Holder, To claim this weeks offer, at you PC please go to http://www.e-tlp.co.uk/reward. Ts&Cs apply."
ham,It vl bcum more difficult..
spam,UR GOING 2 BAHAMAS! CallFREEFONE 08081560665 and speak to a live operator to claim either Bahamas cruise of£2000 CASH 18+only. To opt out txt X to 07786200117

我真的很喜欢建议。非常感谢您的帮助

实际上预测函数工作得很好。不要误会我的意思,但问题在于你在做什么。您正在使用以下公式构建模型:type ~ .,对吗?很明显,我们在公式的左侧有什么,所以让我们看看右侧。

在数据中,您只需要变量 - typestatement,并且由于type是因变量,因此唯一算作自变量的东西是statement。到目前为止,一切都清楚了。

让我们来看看贝叶斯分类器。先验概率是显而易见的,对吧?怎么样条件概率?从分类器的角度来看,你只有一个分类变量(你的句子(。对于分类器点,它只是一些标签列表。所有这些都是唯一的,因此后验概率将接近先验概率。

换句话说,当我们得到一个新的观察结果时,我们唯一能知道的是,它是垃圾邮件的概率等于你的训练集中消息是垃圾邮件的概率。

如果你想使用任何机器学习方法来使用自然语言,你必须先预处理你的数据。根据您的问题,例如,它可能意味着词干提取、词形还原、计算 n-gram 统计、tf-idf。训练分类器是最后一步。

相关内容

最新更新