R 中 F_meas 中的错误 'input data must have the same two levels'?

Error 'input data must have the same two levels' in F_meas in R?

set.seed(1)
library(caret)
library(dslabs)
library(dplyr)

data("tissue_gene_expression")
y_<-tissue_gene_expression$y

test_index <- createDataPartition(y_, times = 1, ,p=0.5, list = FALSE)

x_train<-tissue_gene_expression$x[-test_index,]
y_train<-tissue_gene_expression$y[-test_index]

x_test<-tissue_gene_expression$x[test_index,]
y_test<-tissue_gene_expression$y[test_index]

fit<-knn3(x_train,y_train,k=1)
y_test_hat<-predict(fit,x_test,type = 'class')

F_meas(data = y_test_hat,reference = y_test)

以上是我的代码,它总是return错误:

Error in F_meas.default(data = y_test_hat, reference = y_test, ) :
 input data must have the same two levels

虽然我已经检查了这两个数据的水平(y_test_haty_test_hat)并且它们具有相同的7个水平

在这种情况下,二表示 2,而不是 7。因此,为了正确使用 F_meas,您需要置换小脑、结肠、子宫内膜、海马体、肾脏、肝脏、胎盘并提供 F_meas 有两个级别,否则它不会工作。

#' @rdname recall
#' @importFrom stats complete.cases
#' @export
recall.default <- function(data, reference, relevant = levels(reference)[1], 
                       na.rm = TRUE, ...) {
  if (!is.factor(reference) | !is.factor(data)) 
stop("input data must be a factor")
  if (length(unique(c(levels(reference), levels(data)))) != 2) 
stop("input data must have the same two levels") # where we see two means 2
  if (na.rm) {
cc <- complete.cases(data) & complete.cases(reference)
    if (any(!cc)) {
  data <- data[cc]
  reference <- reference[cc]
}
}
  xtab <- table(data, reference)
 recall.table(xtab, relevant = relevant)
}  

希望这能说明问题。