I have the following problem: I'd like to pedict a factor-variable "cancer" (yes or no) using two variables "sex" and "agegroup" with a bayes classifier. These are my (fictional) sample data:
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)
The result shows me that according to my data males and younger people are more likely to have cancer. Compared to the real cancer-classification my model classifies 147 (=88+59) out of 200 cases correctly (73.5%).
| testset$original
testset$predicted | no | yes | Row Total |
------------------|-----------|-----------|-----------|
no | 88 | 12 | 100 |
------------------|-----------|-----------|-----------|
yes | 54 | 46 | 100 |
------------------|-----------|-----------|-----------|
Column Total | 142 | 58 | 200 |
------------------|-----------|-----------|-----------|
However, then I was doing the same thing using only one classification-variable (sex):
## Sex only ##
######################
# classification
testset2<-data[,c("sex")]
cancer<-data[,"cancer"]
model2<-naiveBayes(testset2, cancer)
model2
The model is as follows:
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
Obviously, males are more likely to have cancer compared to females (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)
Now, when I apply my model to the original data, all cases are classified as the same class:
Total Observations in Table: 200
| testset2$cancer
testset2$predicted | no | yes | Row Total |
-------------------|-----------|-----------|-----------|
no | 129 | 71 | 200 |
-------------------|-----------|-----------|-----------|
Column Total | 129 | 71 | 200 |
-------------------|-----------|-----------|-----------|
Can anyone please explain me, why both females and males are assigned to the same class?