Home > Net >  "Error: Matrix must have equal dimensions" despite seemingly equal dimensions
"Error: Matrix must have equal dimensions" despite seemingly equal dimensions

Time:01-26

pred <- predict(fit, x, type="response", s=cv$lambda.min)

confusion_matrix <- confusionMatrix(data = pred, reference = testXsp) 

Error in confusionMatrix.matrix(data = pred, reference = testXsp) : matrix must have equal dimensions

dim(pred)
[1] 751864 1

dim(testXsp)
[1] 751864 1

dim(testXsp) == dim(pred)
[1] TRUE TRUE

The dimensions seem to be the same, then why am I getting this error message?

CodePudding user response:

confusionMatrix argument data must be square if it is a matrix.

> caret:::confusionMatrix.matrix
function (data, positive = NULL, prevalence = NULL, mode = "sens_spec", 
    ...) 
{
    if (length(unique(dim(data))) != 1) {
        stop("matrix must have equal dimensions")
    }
    classTable <- as.table(data, ...)
    confusionMatrix(classTable, positive, prevalence = prevalence, 
        mode = mode)
}
<bytecode: 0x126452f88>
<environment: namespace:caret>

Note that the method for class matrix does not even take a reference argument. It is the default method that uses reference. Perhaps you should review the help page for confusionMatrix?

CodePudding user response:

One possibility here is that there are one or more NA values contained in your prediction matrix. Try using the following command:

    na.omit(pred)

Afterwards, rerun the above code. If this does not work, please post the package you are using to fit your model. This will allow for a more detailed solution!

Best wishes, -Matt

  • Related