> # Check results
> model_knn$results
k Accuracy Kappa AccuracySD KappaSD
1 5 0.9632391 0.9439746 0.02452539 0.03727995
2 7 0.9699800 0.9544974 0.02451292 0.03708112
3 9 0.9677304 0.9509734 0.02617121 0.03986928
> # Predict the labels of the test set
> predictions<-predict.train(object=model_knn,iris_norm.test[,1:4], type="raw")
>
> # Evaluate the predictions
> table(predictions)
predictions
Iris-setosa Iris-versicolor Iris-virginica
12 14 10
>
> #confusion matrix
>
> # ENTER YOUR CODE HERE
> confusionMatrix(predictions,iris_norm.test[,5])
Error: `data` and `reference` should be factors with the same levels.
Asked
Active
Viewed 94 times
0
-
the `data` and `reference` arguments to `confusionMatrix` should be factors with the same levels, as the error says. This is apparently not the case with `predictions` and `iris_norm.test[,5]`. – Calum You Sep 18 '20 at 00:23
-
Hey Missy, welcome to SO! It would help if you can share just a little more detail about how you arrived at `model_knn`, what packes you used and where your `iris_norm.test` is from. That all helps to make the above code snipped [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Moreover, if you can share the output of `str(predictions)` and `str(iris_norm.test)` or more specifically, `levels(predictions)` and `levels(iris_norm.test[,5])`, you'll get more helpful responses. – alex_jwb90 Sep 18 '20 at 12:16
1 Answers
0
Without the model or data to reproduce your case, I can only suggest to align the factor levels using forcats::fct_unify
before passing the two vectors into confusionMatrix
:
library(forcats)
library(caret)
do.call(
confusionMatrix,
fct_unify(list(
data = predictions,
reference = iris_norm.test[,5]
))
)
fct_unify
works on a list of factor vectors and makes sure they all share the same set of levels. Constructing that list with names corresponding to the expected arguments of confusionMatrix
, I can pass it right into with do.call
.

alex_jwb90
- 1,663
- 1
- 11
- 20