R语言朴素贝叶斯分类上机指导 下载本文

内容发布更新时间 : 2024/6/12 5:46:01星期一 下面是文章的全部内容请认真阅读。

朴素贝叶斯分类上机指导

一、实验目的:

1.掌握矩阵数据的输入,输出,以及矩阵和数据框数据的转换,认识一下list型数据。

2.理解并掌握朴素贝叶斯分类原理。

3.会使用klaR包中的NaiveBayes()函数实现贝叶斯分类算法。

二、实验内容:

本实验利用朴素贝叶斯分类方法对课本P144页play tennis数据集建立模型并预测。

三、实验步骤:

1.将课本P144页playtennis数据以矩阵形式输入,注意理解下面红色代码。

data <- matrix(c(\

\ \ \ \ \

\ \ \ \ \ \ \

\ byrow = TRUE, dimnames = list(day = c(),

condition = c(\

\); #上网查询dimnames的用法

#输出一下data数据:

#将矩阵转化成数据框

> data1<-data.frame(data) > data1

outlook temperature humidity wind playtennis

1 sunny hot high weak no 2 sunny hot high strong no 3 overcast hot high weak yes 4 rain mild high weak yes 5 rain cool normal weak yes 6 rain cool normal strong no 7 overcast cool normal strong yes 8 sunny mild high weak no 9 sunny cool normal weak yes 10 rain mild normal weak yes 11 sunny mild normal strong yes 12 overcast mild high strong yes 13 overcast hot normal weak yes 14 rain mild high strong no

#将手动输入的数据保存成txt文件

>write.table(data1,file=\

#可以重新读入保存的txt文件

data2<-read.table(\

2.理解并掌握朴素贝叶斯分类原理,读懂下列代码

#算出去玩与不玩的先验概率

prior.yes<-sum(data2[,5] ==\

prior.no<-sum(data2[,5] ==\ #建立朴素贝叶斯分类函数

bayespre<- function(condition) { post.yes <-

sum((data2[,1]==condition[1])&(data2[,5]==\\

sum((data2[,2]==condition[2])&(data2[,5]==\\

sum((data2[,3]==condition[3])&(data2[,5]==\\

sum((data2[,4]==condition[4])&(data2[,5]==\\ prior.yes;

post.no <-

sum((data2[,1]==condition[1])&(data2[,5]==\*

sum((data2[,2]==condition[2])&(data2[,5]==\*

sum((data2[,3]==condition[3])&(data2[,5]==\*

sum((data2[,4]==condition[4])&(data2[,5]==\* prior.no;

return(list(prob.yes=post.yes,prob.no=post.no, prediction =ifelse(post.yes>=post.no,\ }