R语言决策树建模计算混淆矩阵报因子水平不匹配错误的问题咨询
报错成因定位
第一类报错:data 和 reference 需为同水平因子
- 你在mutate步骤主动将
Customer type字段转为character类型,而rpart设置type='class'输出的预测结果默认是因子类型,两者类型不匹配 - 若测试集存在训练集未覆盖的标签类别,即使类型统一,因子水平不对齐也会触发该报错
第二类报错:!all.equal(nrow(data), ncol(data)) 参数无效
- 样本拆分代码存在本质错误:
caTools::sample.split()第一个参数需要传入待拆分的标签向量,你直接传入了字符串'Customer type'而非df$Customer type``,导致生成的sample逻辑向量长度仅为1,拆分得到的训练/测试集要么为空要么完全错乱,最终列联表维度不匹配 - 决策树公式写法错误:你写为
rpart(df$Customer type~., data = train),公式内引用了全量df的字段,和指定的data=train不匹配,导致模型训练用的标签/特征长度不匹配,预测结果分布异常 - Time字段强制转numeric逻辑错误:原始Time为时分秒格式的字符,直接
as.numeric会生成全NA值,引入无效特征干扰模型训练
可落地修复步骤
1. 修正数据处理逻辑
- 去掉
Customer type转character的逻辑,将分类字段显式转为因子,避免自动转换出错:df <- df %>% mutate( `Customer type` = factor(`Customer type`), City = factor(City), Gender = factor(Gender), Payment = factor(Payment) ) - 处理/删除冗余无效字段:
# 不需要Date、Time的话直接排除,避免无效转换 df <- select(df, City, `Customer type`, Gender, Quantity, Total, Payment, Rating) # 若需要用Time特征,拆分出小时数后再删除原Time字段: df <- df %>% mutate(Hour = as.numeric(substr(Time, 1, 2))) %>% select(-Time, -Date)
2. 修正样本拆分代码
- 给
sample.split()传入正确的标签向量,保证拆分后训练/测试集均有足够样本:set.seed(123) # 注意这里传的是df的Customer type列,不是字符串 sample <- sample.split(Y = df$`Customer type`, SplitRatio = 0.7) train <- subset(df, sample == TRUE) test <- subset(df, sample == FALSE)
3. 修正决策树训练公式
- 公式内直接引用字段名,不要加df前缀,和
data参数匹配:tree <- rpart(`Customer type` ~ ., data = train)
4. 统一预测值与真实标签的因子水平
- 以训练集的标签水平为统一标准,对齐测试集真实标签、预测值的因子类型与水平:
# 先完成预测 tree.customertype.predicted <- predict(tree, test, type = 'class') # 提取训练集的标签水平作为参照 ref_levels <- levels(train$`Customer type`) # 预测结果转因子并对齐水平 pred <- factor(tree.customertype.predicted, levels = ref_levels) # 测试集真实标签转因子并对齐水平 true <- factor(test$`Customer type`, levels = ref_levels)
5. 正确调用confusionMatrix
- 两种调用方式均合法,优先直接传入对齐后的因子:
# 直接传入对齐后的因子(推荐) confusionMatrix(data = pred, reference = true) # 或传入对齐后生成的方阵列联表 confusionMatrix(table(pred, true))
内容的提问来源于stack exchange,提问作者Nicolas Duaut
相关产品推荐
相关产品推荐

