‘факторы с одинаковыми уровнями’ в матрице путаницы

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

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

Вот мой код:

library(rpart)
library(caret)
library(dplyr)
library(rpart.plot)
library(xlsx)
library(caTools)
library(data.tree)
library(e1071)

#Loading the Excel File
library(readxl)
FINALDATA <- read_excel("Desktop/FINALDATA.xlsm")
View(FINALDATA)
df <- FINALDATA
View(df)

#Selecting the meaningful columns for prediction
#df <- select(df, City, df$`Customer type`, Gender, Quantity, Total, Date, Time, Payment, Rating)
df <- select(df, City, `Customer type`, Gender, Quantity, Total, Date, Time, Payment, Rating)

#making sure the data is in the right format 
df <- mutate(df, City= as.character(City), `Customer type`= as.character(`Customer type`), Gender= as.character(Gender), Quantity= as.numeric(Quantity), Total= as.numeric(Total), Time= as.numeric(Time), Payment = as.character(Payment), Rating= as.numeric(Rating))

#Splitting into training and testing data
set.seed(123)
sample = sample.split('Customer type', SplitRatio = .70)
train = subset(df, sample==TRUE)
test = subset(df, sample == FALSE)

#Training the Decision Tree Classifier
tree <- rpart(df$`Customer type` ~., data = train)

#Predictions
tree.customertype.predicted <- predict(tree, test, type= 'class')

#confusion Matrix for evaluating the model
confusionMatrix(tree.customertype.predicted, test$`Customer type`)

Итак, я попытался сделать это, как сказано в другой теме:

confusionMatrix(table(tree.customertype.predicted, test$`Customer type`))

Но у меня все равно ошибка:

Error in !all.equal(nrow(data), ncol(data)) : argument type is invalid

Просто чтобы следить. В случаях, когда у вас есть большой файл данных, можно создать образец набора данных, который воспроизводит вашу проблему. Вот некоторые рекомендации о том, как люди это делают. Наличие данных облегчает сообществу помощь вам.   —  person Nicolas Duaut    schedule 26.02.2021

Спасибо ! Я буду применять руководство   —  person Nicolas Duaut    schedule 26.02.2021

См. также:  Ошибка в данных $ update_params (params = params): [LightGBM] [Fatal] Невозможно изменить max_bin после созданного дескриптора набора данных
Понравилась статья? Поделиться с друзьями:
IT Шеф
Комментарии: 2
  1. Nicolas Duaut

    Я сделал игрушечный набор данных и изучил ваш код. Возникла пара проблем:

    1. R легче справляется с именами переменных, которые соответствуют определенному стилю. В переменной «Тип клиента» есть пробел. Как правило, писать код проще, если избегать пробелов. Поэтому я переименовал его в Customer_type. Для вашего data.frame вы можете просто перейти в исходный файл или использовать names(df) <- gsub("Customer type", "Customer_type", names(df)).
    2. Я указал «Customer_type» как фактор. Для вас это будет выглядеть df$Customer_type <- factor(df$Customer_type)
    3. В документации для sample.split() сказано, что первый аргумент «Y» должен быть вектором меток. Но в вашем коде вы указали имя переменной. Ярлыки — это названия уровней фактора. В моем примере это уровни High, Med и Low. Чтобы увидеть уровни вашей переменной, вы можете использовать levels(df$Customer_type). Введите их в sample.split() как вектор символов.
    4. Настройте вызов rpart(), как показано ниже.

    С этими настройками ваш код может быть в порядке.

    # toy data
    df <- data.frame(City = factor(sample(c("Paris", "Tokyo", "Miami"), 100, replace = T)),
                     Customer_type = factor(sample(c("High", "Med", "Low"), 100, replace = T)),
                     Gender = factor(sample(c("Female", "Male"), 100, replace = T)),
                     Quantity = sample(1:10, 100, replace = T),
                     Total = sample(1:10, 100, replace = T),
                     Date = sample(seq(as.Date('2020/01/01'), as.Date('2020/12/31'), by="day"), 100),
                     Rating = factor(sample(1:5, 100, replace = T)))
    
    library(rpart)
    library(caret)
    library(dplyr)
    library(caTools)
    library(data.tree)
    library(e1071)
    
    #Splitting into training and testing data
    set.seed(123)
    sample = sample.split(levels(df$Customer_type), SplitRatio = .70) # ADJUST YOUR CODE TO MATCH YOUR FACTOR LABEL NAMES
    train = subset(df, sample==TRUE)
    test = subset(df, sample == FALSE)
    
    #Training the Decision Tree Classifier
    tree <- rpart(Customer_type ~., data = train) # ADJUST YOUR CODE SO IT'S LIKE THIS
    
    #Predictions
    tree.customertype.predicted <- predict(tree, test, type= 'class')
    
    #confusion Matrix for evaluating the model
    confusionMatrix(tree.customertype.predicted, test$Customer_type)
    

    Большое спасибо за Ваш ответ. Я сделал то, что ты сказал. Перед разделением / обучением данных я извлек метки из данных, чтобы создать вектор меток данных, например: customerlabel ‹- c (df $ Customer_type, recursive = FALSE, use.names = TRUE). Я ввожу его в функцию sample.split: sample = sample.split (customerlabel, SplitRatio = .70), test $ Customer_type). Несмотря на то, что точность всего 0,47, все в порядке, спасибо! person Nicolas Duaut; 26.02.2021

  2. Nicolas Duaut

    Постарайтесь сохранить уровни факторов train и test такими же, как df.

    train$`Customer type` <- factor(train$`Customer type`, unique(df$`Customer type`))
    test$`Customer type` <- factor(test$`Customer type`, unique(df$`Customer type`))
    

    Спасибо за ваш ответ ! Я помещаю эти строки после: ‘train = subset (df, sample == TRUE) test = subset (df, sample == FALSE)’ Однако, когда я делаю свою матрицу путаницы, у меня есть 4 нуля и точность ‘NaN’ person Nicolas Duaut; 26.02.2021

Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: