Ошибка: «data» и «reference» должны быть факторами с одинаковыми уровнями. Матрица ошибок для Logisti c Регрессия - PullRequest
0 голосов
/ 29 мая 2020

Я видел множество ответов по поводу этой конкретной ошибки. Я не нашел на него ответа, касающегося моей конкретной проблемы. Поэтому моя проблема

Это то, что я делаю:

    shortness_breath_data <- data_categ_nosev %>%
dplyr::select(shortness_breath, obesity, asthma, diabetes_type_one, diabetes_type_two, obesity, hypertension, heart_disease, lung_condition, liver_disease, kidney_disease, Covid_tested, Gender) 

А это put(head(shortness_breath_data)):

structure(list(shortness_breath = structure(c(1L, 2L, 1L, 1L, 
1L, 2L), .Label = c("No", "Yes"), class = "factor"), obesity = structure(c(1L, 
1L, 2L, 2L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"), 
    asthma = structure(c(2L, 1L, 1L, 1L, 1L, 1L), .Label = c("No", 
    "Yes"), class = "factor"), diabetes_type_one = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"), 
    diabetes_type_two = structure(c(2L, 1L, 1L, 1L, 1L, 1L), .Label = c("No", 
    "Yes"), class = "factor"), hypertension = structure(c(1L, 
    1L, 1L, 2L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"), 
    heart_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No", 
    "Yes"), class = "factor"), lung_condition = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"), 
    liver_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No", 
    "Yes"), class = "factor"), kidney_disease = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"), 
    Covid_tested = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("negative", 
    "positive"), class = "factor"), Gender = structure(c(2L, 
    1L, 2L, 1L, 1L, 2L), .Label = c("Female", "Male", "Other"
    ), class = "factor")), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"), problems = structure(list(row = c(2910L, 
35958L), col = c("how_unwell", "how_unwell"), expected = c("a double", 
"a double"), actual = c("How Unwell", "How Unwell"), file = c("'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'", 
"'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'"
)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
)))

И я делю это на набор данных для обучения и тестирования .

shortness_breath_data$shortness_breath <- as.factor(shortness_breath_data$shortness_breath)

n <- nrow(shortness_breath_data)
set.seed(22)
trainingdx <- sample(1:n, 0.7 * n)

train <- shortness_breath_data[trainingdx,]
validate <- shortness_breath_data[-trainingdx,]

train %>% distinct(shortness_breath)
validate %>% distinct(shortness_breath)

И чтобы сделать то же самое на случай, если это упростит вам работу по поиску проблемы, я предоставил dput(head(train)) и dput(head(validate))

набор данных поезда:

structure(list(shortness_breath = structure(c(1L, 1L, 1L, 1L, 
1L, 1L), .Label = c("No", "Yes"), class = "factor"), obesity = structure(c(2L, 
1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"), 
    asthma = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No", 
    "Yes"), class = "factor"), diabetes_type_one = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"), 
    diabetes_type_two = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No", 
    "Yes"), class = "factor"), hypertension = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"), 
    heart_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No", 
    "Yes"), class = "factor"), lung_condition = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"), 
    liver_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No", 
    "Yes"), class = "factor"), kidney_disease = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"), 
    Covid_tested = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("negative", 
    "positive"), class = "factor"), Gender = structure(c(1L, 
    1L, 1L, 2L, 1L, 2L), .Label = c("Female", "Male", "Other"
    ), class = "factor")), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"), problems = structure(list(row = c(2910L, 
35958L), col = c("how_unwell", "how_unwell"), expected = c("a double", 
"a double"), actual = c("How Unwell", "How Unwell"), file = c("'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'", 
"'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'"
)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
)))

проверить набор данных:

structure(list(shortness_breath = structure(c(1L, 2L, 2L, 1L, 
1L, 1L), .Label = c("No", "Yes"), class = "factor"), obesity = structure(c(1L, 
1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"), 
    asthma = structure(c(2L, 1L, 1L, 1L, 1L, 1L), .Label = c("No", 
    "Yes"), class = "factor"), diabetes_type_one = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"), 
    diabetes_type_two = structure(c(2L, 1L, 1L, 1L, 1L, 1L), .Label = c("No", 
    "Yes"), class = "factor"), hypertension = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"), 
    heart_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No", 
    "Yes"), class = "factor"), lung_condition = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"), 
    liver_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No", 
    "Yes"), class = "factor"), kidney_disease = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"), 
    Covid_tested = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("negative", 
    "positive"), class = "factor"), Gender = structure(c(2L, 
    1L, 2L, 2L, 1L, 1L), .Label = c("Female", "Male", "Other"
    ), class = "factor")), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"), problems = structure(list(row = c(2910L, 
35958L), col = c("how_unwell", "how_unwell"), expected = c("a double", 
"a double"), actual = c("How Unwell", "How Unwell"), file = c("'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'", 
"'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'"
)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
)))

И затем я построил свою логистическую c регрессионную модель с пошаговым прямым методом.

null_model <- glm(shortness_breath ~ 1, data = train, family = "binomial")

fm_shortness_breath <- glm(shortness_breath ~., data = train, family = "binomial")

stepmodel <- step(null_model, scope = list(lower = null_model, upper = fm_shortness_breath), direction = "forward")

Затем я получаю свою сводную модель и сохраняю прогнозы во фрейме исходных данных.

summary(stepmodel)

validate$pred <- predict(stepmodel, validate, type = "response")

validate$real <- validate$shortness_breath

train$pred <- predict(stepmodel, train, type = "response")
train$real <- train$shortness_breath

Затем я без проблем строю свою кривую RO C:

plot.roc(validate$real, validate$pred, col = "red", main = "ROC Validation Set", percent = TRUE, print.auc = TRUE)

Тем не менее, когда я пытаюсь получить свою матрицу путаницы, именно здесь я получаю свою ошибку . Но это мой код:

cm_stepmodel <- confusionMatrix(stepmodel, validate)

А потом появляется ошибка:

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

With Show Traceback:

3.
stop("`data` and `reference` should be factors with the same levels.", call. = FALSE)
2.
confusionMatrix.default(stepmodel, validate)
1.
confusionMatrix(stepmodel, validate)

Я просто не вижу эта проблема. И попробовал несколько других вариантов, но не сработало. Я воспроизвел шаг за шагом точный подход, которым придерживаюсь. И я не получаю ответа. Кроме того, на всякий случай я пометил эту проблему с помощью RMarkdown вместе с курсором и R.

Также используются следующие библиотеки:

library(tidyverse)
library(conflicted)
library(tidymodels)
library(ggrepel)
library(corrplot)
library(dplyr)
library(corrr) 
library(themis)
library(rsample)
library(caret)
library(forcats)
library(rcompanion)
library(MASS)
library(pROC)
library(ROCR)
library(data.table)

1 Ответ

1 голос
/ 29 мая 2020

Попробуйте преобразовать ваши предсказанные вероятности в метки, а затем запустите свою confusionMatrix на этом:

validate$pred <- predict(stepmodel, validate, type = "response")
validate$pred_label <- as.factor(ifelse(validate$pred >= 0.5, "Yes", "No"))
confusionMatrix(validate$real, validate$pred) # Error
confusionMatrix(validate$real, validate$pred_label) # This will work

Убедитесь, что вы правильно назначаете метки, как в исходном наборе данных в операторе validate$pred_label.

Я не особо знаком с confusionMatrix, но общая идея состоит в том, что вы делаете прогнозы меток и сравниваете их с фактическими метками ваших данных. Это выдало ошибку, потому что вы сравнивали метки с вероятностями - вам нужно было назначить метки. Пожалуйста, поправьте меня, если я допустил концептуальную ошибку или ошибку кодирования выше.

...