Случайный лес в R - Применение к тестированию / проверке набора - PullRequest
2 голосов
/ 14 апреля 2020

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

#Import Data
url <- "http://groupware.les.inf.puc-rio.br/static/WLE/WearableComputing_weight_lifting_exercises_biceps_curl_variations.csv"
df <- read.csv(url, header = TRUE, na.strings=c("NA","#DIV/0!",""))

#Remove columns containing ALL NA values
df <- df[,colSums(is.na(df)) == 0]

#Remove all irrelevant columns that you will not need as predictors 
df <- subset(df, select = -c(1:7))

#Create training and testing datasets
library(caret)
inTrain <- createDataPartition(y = df$classe,
                               p=0.7, list = FALSE)
training <- df[inTrain,]
testing <- df[-inTrain,]

set.seed(2020)

rfmodel <- randomForest(classe ~ ., data = training, method="rf", ntree=100, importance = TRUE)
print(rfmodel) #Error rate of 0.17% = good!

#validating that this method works on training set
prediction_train <- predict(rfmodel, data = training, type = "class")
table(prediction_train, training$classe)

#Cannot figure out what is going wrong here
prediction_test <- predict(rfmodel, data = testing)
length(prediction_test) #27472
length(testing$classe) #11770
table(prediction_test, testing$classe) #ERROR (see below)
#Error in table(prediction_test, testing$classe) : all arguments must have the same length

Пакеты, которые я использую:

version $ version.string [1] "R version 3.5.3 (2019-03-11)" packageVersion ("caret") , lib.lo c = NULL) [1] '6.0.85' packageVersion ("rattle", lib.lo c = NULL) [1] '5.3.0' packageVersion ("randomForest", lib.lo c = NULL) [1] '4.6.14' packageVersion ("randomForestExplainer", lib.lo c = NULL) [1] '0.10.0'

Ответы [ 2 ]

1 голос
/ 14 апреля 2020

Проблема была в data = при проведении тестирования. Приветствия.

rfmodel <- randomForest(training$classe ~ ., data = training[,-51], method="rf", ntree=100, importance = TRUE)
prediction_test <- predict(rfmodel, testing[,-51])
table(prediction_test, testing$classe) 

prediction_test    A    B    C    D    E
              A 3346    3    0    0    0
              B    1 2274    4    0    0
              C    0    0 2049   15    0
              D    0    0    0 1913    0
              E    0    0    0    1 2164


0 голосов
/ 14 апреля 2020

Используйте newdata = в функции predict как для обучения, так и для тестирования данных, таких как

#validation using training data
prediction_train <- predict(rfmodel, newdata = training, type = "class")
table(prediction_train, training$classe)

prediction_train    A    B    C    D    E
           A 7812    0    0    0    0
           B    0 5316    0    0    0
           C    0    0 4791    0    0
           D    0    0    0 4503    0
           E    0    0    0    0 5050

#validation using testing data
prediction_test <- predict(rfmodel, newdata = testing, type = "class")
length(prediction_test) 
length(testing$classe)
table(prediction_test, testing$classe)

prediction_test    A    B    C    D    E
              A 3346    7    0    0    0
              B    1 2269    1    0    0
              C    0    1 2052    4    0
              D    0    0    0 1924    1
              E    0    0    0    1 2163
...