我有以下问题:我想用贝叶斯分类器使用两个变量“性别”和“年龄组”来描述因子变量“癌症”(是或否)。 这些是我的(虚构的)样本数据:朴素贝叶斯分类与R - 奇怪的结果
install.packages("e1071")
install.packages("gmodels")
library(e1071)
library(gmodels)
data<-read.csv("http://www.reduts.net/cancer.csv", sep=";", stringsAsFactors = T)
## Sex and Agegroup ##
######################
# classification
testset<-data[,c("sex", "agegroup")]
cancer<-data[,"cancer"]
model<-naiveBayes(testset, cancer)
model
# apply model on testset
testset$predicted<-predict(model, testset)
testset$cancer<-cancer
CrossTable(testset$predicted, testset$cancer, prop.chisq=F, prop.r=F, prop.c=F, prop.t = F)
结果表明我,根据我的数据男性和年轻人更容易得癌症。与真实的癌症分类相比,我的模型对200例病例中的147例(= 88 + 59)进行了正确分类(73.5%)。
| testset$original
testset$predicted | no | yes | Row Total |
------------------|-----------|-----------|-----------|
no | 88 | 12 | 100 |
------------------|-----------|-----------|-----------|
yes | 54 | 46 | 100 |
------------------|-----------|-----------|-----------|
Column Total | 142 | 58 | 200 |
------------------|-----------|-----------|-----------|
不过,当时我做的只使用一个分类变量(性别)同样的事情:
## Sex only ##
######################
# classification
testset2<-data[,c("sex")]
cancer<-data[,"cancer"]
model2<-naiveBayes(testset2, cancer)
model2
模型如下:
Naive Bayes Classifier for Discrete Predictors
Call:
naiveBayes.default(x = testset2, y = cancer)
A-priori probabilities:
cancer
no yes
0.645 0.355
Conditional probabilities:
x
cancer f m
no 0.4573643 0.5426357
yes 0.5774648 0.4225352
显然,男性是与女性相比,患癌症的可能性更高(54%vs 46%)。
# apply model on testset
testset2$predicted<-predict(model2, testset2)
testset2$cancer<-cancer
CrossTable(testset2$predicted, testset2$cancer, prop.chisq=F, prop.r=F, prop.c=F, prop.t = F)
现在,当我申请我的模型对原始数据,所有病例被列为同一类:
Total Observations in Table: 200
| testset2$cancer
testset2$predicted | no | yes | Row Total |
-------------------|-----------|-----------|-----------|
no | 129 | 71 | 200 |
-------------------|-----------|-----------|-----------|
Column Total | 129 | 71 | 200 |
-------------------|-----------|-----------|-----------|
谁能请解释我为什么女性和男性被分配到同类?