[R - ml] 分类

OneR 单条规则

利用One R 规则 对mushroom 分类

数据准备

首先下载mushroom 数据

library(utils)
mushrooms = read.csv('E:/rpath/mushroom.data', stringsAsFactors = TRUE, header = F)
str(mushrooms)
names(mushrooms) = c('type','cap_shape','cap_surface','cap_color','bruises','odor','gill_attachment','gill_spacing','gill_size','gill_color','stalk_shape','stalk_root','stalk_surface_above_ring','stalk_surface_below_ring','stalk_color_above_ring','stalk_color_below_ring','veil_type','veil_color','ring_number','ring_type','spore_print_color','population','habitat')
summary(mushrooms)
mushrooms$veil_type = NULL # 只有一种值, 直接把这个变量去掉
table(mushrooms$type)
install.packages('RWeka', dependencies = T)
require(RWeka)
mushroom_lR = OneR(type ~ . , data = mushrooms)
mushroom_lR

这里只用了一条rule,即odor,分别对应的含义为
almond=a,anise=l,creosote=c,fishy=y,foul=f,musty=m,none=n,pungent=p,spicy=s

OneR 的说明:

m = OneR(class~predictors, data = mydata)
p = predict(m, test)

模型的结果

summary(mushroom_lR)

98.5% 正确分类, confusion matrix 里面列为实际值, 行为预测值。
因为120个本来无毒的蘑菇样本呗分类为有毒,而没有任何有毒的蘑菇被分类为无毒。

模型改进

前面我们使用的是OneR, 那么可以考虑更复杂一点的算法, 比如RIPPER
这里利用Rweka里面的JRip().

Repeated Incremental Pruning to Produce Error Reduction (RIPPER),

mushroom_JRip = JRip(type~. , data = mushrooms)
mushroom_JRip

JRip 使用了多条规则,比如如果odor = f 那么有毒, gill_size = n 并且 gill_colol = b 那么有毒。。
显然JRip 完美完成了对蘑菇的分类4208个样本没有一个错误。

注意前面我们把所有的数据都用作训练数据集,显然不对,还是老办法
用createDataPartition 去 80% 为训练数据

require(caret)
set.seed(2014)
inTrain = createDataPartition(y = mushrooms$type, p = 0.8, list = FALSE)
mushroom_train = mushrooms[inTrain, ]
mushroom_test = mushrooms[-inTrain, ]
prop.table(table(mushroom_train$type))
prop.table(table(mushroom_test$type))

mushroom_JRip = JRip(type~. , data = mushroom_train)
mushroom_predict = predict(mushroom_JRip, mushroom_test)
require(gmodels)
CrossTable(mushroom_test$type, mushroom_predict)

你可能感兴趣的:([R - ml] 分类)