预测函数返回错误的预测数,并且不会获得混淆矩阵

时间:2015-07-28 18:09:23

标签: r predict confusion-matrix

在我有一个名为dtab的数据框中,我在这里报告了一小部分:

structure(list(ID = 1:10, X9Profit = c(21L, -6L, -49L, -4L, -61L, 
-38L, -19L, 59L, 493L, -158L), X9Online = c(0L, 0L, 1L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L), X9Age = c(NA, 6L, 5L, NA, 2L, NA, 3L, 5L, 
4L, 6L), X9Inc = c(NA, 3L, 5L, NA, 9L, 3L, 1L, 8L, 9L, 8L), X9Tenure =c(6.33, 
29.5, 26.41, 2.25, 9.91, 2.33, 8.41, 7.33, 15.33, 4.33), X9District =c(1200L, 
1200L, 1100L, 1200L, 1200L, 1300L, 1300L, 1200L, 1200L, 1100L
), X0Profit = c(NA, -32L, -22L, NA, -4L, 14L, 0L, -65L, 855L, 
-20L), X0Online = c(NA, 0L, 1L, NA, 0L, 0L, 0L, 0L, 0L, 0L), 
X9Billpay = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), X0Billpay = c(NA, 
0L, 0L, NA, 0L, 0L, 0L, 0L, 0L, 0L)), .Names = c("ID", "X9Profit", 
"X9Online", "X9Age", "X9Inc", "X9Tenure", "X9District", "X0Profit", 
"X0Online", "X9Billpay", "X0Billpay"), row.names = c(NA, 10L), class ="data.frame")

我重命名了一些变量(这部分是正确的):

N=dim(dtab)[1]
Profit9=dtab$X9Profit
Online9=dtab$X9Online
Age=dtab$X9Age
Income=dtab$X9Inc
Tenure=dtab$X9Tenure
District=dtab$X9District
Profit0=dtab$X0Profit
Online0=dtab$X0Online
District1100 = ifelse(District==1100,1,0)
District1200 = ifelse(District==1200,1,0)
AgeGiven = ifelse(is.na(Age),0,1)
AgeZero = ifelse(is.na(Age),0,Age)
IncomeZero = ifelse(is.na(Income),0,Income)
IncomeGiven = ifelse(is.na(Income),0,1)
Retain=ifelse(is.na(Profit0),0,1)
Retain=as.factor(Retain)

Retain是一个虚拟变量,可以假设0或1作为值。 我想要这个逻辑模型的混淆矩阵(我们有N个观察结果)

Retain~Profit9+Online9+AgeZero+IncomeZero+Tenure

所以我已经完成了

set.seed(1)
x=sample(1:N, N/2,replace = FALSE)
training=dtab$ID %in% x 

这会生成一个逻辑向量来设置列车,这似乎没问题。

testing=!(training)

Retain_testing=dtab$Retain[testing]

model=glm(Retain~Profit9+Online9+AgeZero+IncomeZero+Tenure,
data=dtab[training,],family=binomial)
  • 现在我发出了警告,但这不是一个问题,因为这个数据的子集很少(因为没有它我应该进行大约100次观察)

    Warning message:
    glm.fit: fitted probabilities numerically 0 or 1 occurred 
    

    model_pred_probs = predict(model,newdata = dtab [testing,],type ='response')

  • 1°问题:预测太多

    Warning message:'newdata' had 5 rows but variables found have 10 rows 
    

我要制作混淆矩阵,所以我已经完成了:

model_pred_Retain=rep(0,N/2)
model_pred_Retain[model_pred_probs>0.5]=1
table(model_pred_Retain, Retain_testing)
  • 2°问题:(可能与第一个相关)

    Error in table(model_pred_Retain, Retain_testing) : all argoments should have the same length
    

我到处检查过,但我看不出有什么问题。

0 个答案:

没有答案