关于 r:Confusion Matrix Error: Error: `data` 和 `reference` 应该是相同级别的因子

Confusion Matrix Error: Error: `data` and `reference` should be factors with the same levels

我目前正在尝试构建一个神经网络来预测人们在数据中的排名。

等级系统为:A,B,C,D,E

在我到达我的混淆矩阵之前,一切都运行得非常顺利。我收到错误"错误:datareference 应该是具有相同级别的因素。"。我在其他帖子上尝试了许多不同的方法,但似乎都没有。

NNPredicitions 和 test$Rank 中的级别都相同。我用 table() 检查了它们。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
library(readxl)
library(caret)
library(neuralnet)
library(forecast)
library(tidyverse)
library(ggplot2)



Indirect <-read_excel("C:/Users/Abdulazizs/Desktop/Projects/Indirect/FIltered Indirect.xlsx",
    n_max = 500)

Indirect$Direct_or_Indirect <- NULL


Indirect$parentaccount <- NULL


sum(is.na(Indirect))


counts <- table(Indirect$Rank)



barplot(counts)

summary(counts)



part2 <- createDataPartition(Indirect$Rank, times = 1, p = .8, list = FALSE, groups = min(5, length(Indirect$Rank)))

train <- Indirect[part2, ]
test <- Indirect[-part2, ]

set.seed(1234)

TrainingParameters <- trainControl(method ="repeatedcv", number = 10, repeats=10)

as.data.frame(train)
as.data.frame(test)

NNModel <- train(train[,-7], train$Rank,
                  method ="nnet",
                  trControl= TrainingParameters,
                  preProcess=c("scale","center"),
                  na.action = na.omit
)

NNPredictions <-predict(NNModel, test, type ="raw")



summary(NNPredictions)





confusionMatrix(NNPredictions, test$Rank)

长度(NNPredictions)
长度(测试$排名)

length(NNPredictions)
[1] 98
length(test$Rank)
[1] 98

table(NNPredictions, test$Rank, useNA="ifany")
NN预测 A B C D E
一个 1 0 0 0 0
乙 0 6 0 0 0
C 0 0 11 0 0
D 0 0 0 18 0
E 0 0 0 0 62


还将方法 = "prob" 更改为方法 = "raw"

Table1 <- table(NNPredictions, test$Rank, useNA = "ifany")

cnf1 <-confusionMatrix(Table1)

dclarson 提供回答