分类错误新数据因素中的水平与原始数据不匹配

时间:2018-09-25 07:24:37

标签: r decision-tree

我有这个数据集:

"chr","start","stop","strand","num_probes","segment_mean","is_nocnv"
chr18,52502759,52502887,*,2,-2.387,YES
chr18,52508963,68598272,*,9546,-0.3843,YES
chrX,17018571,63154896,*,18479,-0.0448,YES
chrX,63161754,63812965,*,265,-0.5375,YES
chrX,63816350,66632343,*,1071,0.1047,YES
chrX,66632547,67941468,*,558,-0.5452,YES
chrX,67947143,94288567,*,10251,-0.0625,YES
chr1,5902314,10246654,*,2415,-0.1312,NO
chr1,10249962,10255256,*,4,-1.4639,NO
chrX,66632547,67941468,*,605,-0.5472,NO
chrX,67947143,90967744,*,11378,-0.0608,NO
chrX,90968512,90971771,*,9,-0.9191,NO
chrX,90971889,92325108,*,520,-0.088,NO
etc...

我写这段代码:

mydata= read.csv("prova.csv")
str(mydata)
set.seed(1234)
ind <- sample(2,nrow(mydata),replace=TRUE, prob= c(0.7,0.3))
trainData <- mydata[ind==1,]
testData <- mydata[ind==2,]

myFormula <- is_nocnv ~ chr + start + stop + strand + num_probes +     segment_mean
albero <- ctree(myFormula, data=trainData)
#check the prediction
table(predict(albero),trainData$is_nocnv)

然后我有一行新的测试数据集:

"chr","start","stop","strand","num_probes","segment_mean","is_nocnv"
chr18,52502759,52502887,*,2,-2.387,a

我想预测该测试数据集的值“ is_nocnv”(“ a”不是一个真正的值)

出于我的目标,我插入以下代码:

testData= read.csv("TEST_DATA.csv")
testPred <- predict(albero,newdata= testData)
table(testPred,testData$is_nocnv)

这里: 我有错误:

> testPred <- predict(albero,newdata= testData)
 Error in checkData(oldData, RET) : 
  Levels in factors of new data do not match original data

我不知道为什么?

1 个答案:

答案 0 :(得分:0)

您的 testDatatrainData变量上没有factor级别(在您的示例chr和{ {1}}。

使用is_nocnvlevels(testData$is_nocnv)进行检查。 (与levels(trainData$is_nocnv)相同)。

$chr必须相等。

通过此字符串:

levels

似乎是chr18,52502759,52502887,*,2,-2.387,a ,但在火车上只有is_nocnv = a标签。

请确保具有相同标签和相同的YES/NO

levels

或更好:

testData$is_nocnv <- factor("YES", levels = c("NO","YES")) # or "NO"

其他变量testData$is_nocnv <- factor("YES", levels = levels(trainData$is_nocnv)) 相同:

chr