2017-10-18 14 views
1

바이너리 예/아니오 클래스 응답이있는 데이터가 있습니다. RF 모델을 실행하기 위해 다음 코드를 사용합니다. 나는 혼란 행렬 결과를 얻는데 문제가있다.R 캐럿의 임의 포리스트에 대한 혼용 행렬

dataR <- read_excel("*:/*.xlsx") 
Train <- createDataPartition(dataR$Class, p=0.7, list=FALSE) 
training <- dataR[ Train, ] 
testing <- dataR[ -Train, ] 

model_rf <- train( Class~., tuneLength=3, data = training, method = 
"rf", importance=TRUE, trControl = trainControl (method = "cv", number = 
5)) 

결과 :

Random Forest 

3006 samples 
82 predictor 
2 classes: 'NO', 'YES' 

No pre-processing 
Resampling: Cross-Validated (5 fold) 
Summary of sample sizes: 2405, 2406, 2405, 2404, 2404 
Addtional sampling using SMOTE 

Resampling results across tuning parameters: 

mtry Accuracy Kappa  
    2 0.7870921 0.2750655 
    44 0.7787721 0.2419762 
87 0.7767760 0.2524898 

Accuracy was used to select the optimal model using the largest value. 
The final value used for the model was mtry = 2. 

지금까지 좋은,하지만이 코드를 실행하면 내가 경우 감사

Error in model_rf[, 1] : incorrect number of dimensions 

:

# Apply threshold of 0.50: p_class 
class_log <- ifelse(model_rf[,1] > 0.50, "YES", "NO") 

# Create confusion matrix 
p <-confusionMatrix(class_log, testing[["Class"]]) 

##gives the accuracy 
p$overall[1] 

을 나는이 오류 친구들이 혼란 행렬 결과를 얻도록 도와 줄 수 있습니다.

+0

'model_rf [, 1]'을 콘솔에 출력하고 살펴 봅니다. – jsb

+0

질문에 [최소 재현 가능한 예] (https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)를 포함하면 도움이 될 것입니다. – jsb

답변

1

class_log <- ifelse(prediction.rf > 0.50, "YES", "NO")을한다.

savePredictionstrainControl에 지정해야합니다. "final"으로 설정하면 최상의 모델에 대한 예측이 저장됩니다. 각 클래스에 대해 classProbs = T 확률을 지정하면 저장됩니다.

model_rf$pred 

CV의 fols 따라 정렬, 원래의 데이터 프레임과 정렬 :

confusionMatrix(model_rf$pred[order(model_rf$pred$rowIndex),2], iris_2$Species) 
#output 
Confusion Matrix and Statistics 

      Reference 
Prediction versicolor virginica 
    versicolor   46   6 
    virginica   4  44 

       Accuracy : 0.9    
       95% CI : (0.8238, 0.951) 
    No Information Rate : 0.5    
    P-Value [Acc > NIR] : <2e-16   

        Kappa : 0.8    
Mcnemar's Test P-Value : 0.7518   

      Sensitivity : 0.9200   
      Specificity : 0.8800   
     Pos Pred Value : 0.8846   
     Neg Pred Value : 0.9167   
      Prevalence : 0.5000   
     Detection Rate : 0.4600   
    Detection Prevalence : 0.5200   
     Balanced Accuracy : 0.9000   

     'Positive' Class : versicolor 
:

model_rf$pred[order(model_rf$pred$rowIndex),2] 

는 혼동 행렬을 획득하기

data(iris) 
iris_2 <- iris[iris$Species != "setosa",] #make a two class problem 
iris_2$Species <- factor(iris_2$Species) #drop levels 

library(caret) 
model_rf <- train(Species~., tuneLength = 3, data = iris_2, method = 
         "rf", importance = TRUE, 
        trControl = trainControl(method = "cv", 
              number = 5, 
              savePredictions = "final", 
              classProbs = T)) 

예측은에

두 클래스 설정에서 종종 지정됩니다. 문턱 확률이 0.5보다 작 으면 최적의 임계 값은 Kappa 또는 Youden의 J 통계 (또는 다른 선호되는 값)를 확률의 함수로 최적화하여 학습 한 후에 찾을 수 있습니다. 여기서 높은 카파 threshold == 0.5 에서뿐만 0.1 얻어지지

sapply(1:40/40, function(x){ 
    versicolor <- model_rf$pred[order(model_rf$pred$rowIndex),4] 
    class <- ifelse(versicolor >=x, "versicolor", "virginica") 
    mat <- confusionMatrix(class, iris_2$Species) 
    kappa <- mat$overall[2] 
    res <- data.frame(prob = x, kappa = kappa) 
    return(res) 
}) 

다음은 예이다. 이것은 과도한 피팅으로 이어질 수 있으므로 신중하게 사용해야합니다.

+0

고마워요. 단 하나의 문제,이 코드에서 cm pred 모델은 열차를 데이터 세트로 정의 할 때만 작동합니다. 나는 pred에 대해 테스트 데이터 세트를 정의해야한다고 생각합니다. 코드 $ test를 테스트 할 때 다음 오류가 발생합니다. 테이블의 오류 (데이터, 참조, dnn = dnn, ...) : 모든 인수의 길이는 동일해야합니다. – Mike

+0

이 코드는 캐럿의 교차 유효성 검사 폴드 . 교차 검증은 열차 세트에서 수행되기 때문에 열차 세트에만 적합합니다. 테스트 세트에서 혼동 행렬을 얻으려면 먼저 테스트 세트 샘플의 클래스를 예측하고이를 'confusionMatrix' 함수에 의해 실제 클래스와 비교해야합니다. – missuse

1

당신은

m <- table(class_log, testing[["Class"]]) 
m #confusion table 

#Accuracy 
(sum(diag(m)))/nrow(testing) 
+0

감사합니다.하지만 class_log 부분을 실행할 때 오류가 발생합니다. 내 질문을 편집 – Mike

0

코드 조각 class_log <- ifelse(model_rf[,1] > 0.50, "YES", "NO")는 다음과 같은 시험을 수행하는 경우 - 다른 진술의 정확성을 혼동 행렬을 작성 및 확인이 시도 할 수 있습니다 :

In the first column of model_rf , if the number is greater than 0.50, return "YES", else return "NO", and save the results in object class_log .

그래서 코드가 기본적으로 생성을 수치표에 근거 해, 클래스 label의 문자 벡터 「YES」및 「NO」

0

테스트 세트에 모델을 적용해야합니다. 난 당신이 캐럿의 교차 검증을 위해 혼란 행렬을 얻을 좀하고 싶습니다 알고있는 것처럼

prediction.rf <- predict(model_rf, testing, type = "prob")

그런 다음

+0

감사합니다. 이진 Y/N 응답 클래스에 대한 class_log 코드가 작동합니까? – Mike

+0

'prediction.rf'는 실제 값을 가질 것입니다 ('type = "prob"에주의하십시오). 'type = "raw"'를 사용하여 바로 바이너리를 얻을 수도 있지만, 임계 값을 제어 할 수는 없습니다. '? predict.train'을보십시오 –