【发布时间】:2018-02-12 03:39:19
【问题描述】:
我有以下问题:我想使用带有贝叶斯分类器的两个变量“性别”和“年龄组”来预测因子变量“癌症”(是或否)。 这些是我的(虚构的)样本数据:
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% 对 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 |
-------------------|-----------|-----------|-----------|
谁能解释一下,为什么女性和男性被分配到同一个班级?
【问题讨论】:
标签: r machine-learning classification naivebayes