2016-06-06 2 views
0

다음과 같이 아주 간단한 임의의 포리 스트를 시도하고 있습니다.이 코드는 완전히 독립적이며 실행 가능합니다. 그것은 나에게 그 오류를 제공 왜 이해가 안R에서 Random Forest Regression이 입력 데이터를 좋아하지 않는 이유는 무엇입니까?

...The response has five or fewer unique values. Are you sure you want to do regression? 

: 그것은 나에게 오류를 제공

library(randomForest) 
n = 1000 

factor=10 
x1 = seq(n) + rnorm(n, 0, 150) 
y = x1*factor + rnorm(n, 0, 550) 

x_data = data.frame(x1) 
y_data = data.frame(y) 

k=2 
for (nfold in seq(k)){ 
    fold_ids <- cut(seq(1, nrow(x_data)), breaks=k, labels=FALSE) 
    id_indices <- which(fold_ids==nfold) 
    fold_x <- x_data[id_indices,] 
    fold_y <- y_data[id_indices,] 
    fold_x_df = data.frame(x=fold_x) 
    fold_y_df = data.frame(y=fold_y) 
    print(paste("number of rows in fold_x_df is ", nrow(fold_x_df), sep=" ")) 
    print(paste("number of rows in fold_y_df is ", nrow(fold_y_df), sep=" ")) 
    rf = randomForest(fold_x_df, fold_y_df, ntree=1000) 
    print(paste("mse for fold number ", " is ", sum(rf$mse))) 
} 

rf = randomForest(x_data, y_data, ntree=1000) 

.

나는이 소스를 확인했습니다 사람들의

Use of randomforest() for classification in R? RandomForest error code https://www.kaggle.com/c/15-071x-the-analytics-edge-competition-spring-2015/forums/t/13383/warning-message-in-random-forest

아무도 내 문제를 해결하지 않습니다. 당신은 인쇄 진술을 볼 수 있습니다, 분명히 5 개 이상의 고유 한 레이블이 있습니다. 말할 것도없이, 여기서는 분류가 아니라 회귀 분석을하고 있습니다. 그래서 "라벨"이라는 단어가 오류에 사용 된 이유를 모르겠습니다.

+0

'randomForest'은 벡터가 아닌 데이터 프레임 수 있어야에'y' 인수입니다. 'fold_y_df' 대신'fold_y'를 사용하면 괜찮을 것입니다. (또는'x'와'y'를 같은 데이터 프레임에 넣고'data'와'formula' 메쏘드를 사용하십시오.) – Gregor

+0

그냥'y' 인자입니까? – buzzinolops

+0

맞음! 직접 체험 해보십시오! – Gregor

답변

0

이 문제는 응답을 데이터 프레임으로 제공합니다. 응답은 1 차원이어야하므로 벡터가되어야합니다. 여기에 내가 완전히 문제를 방지하기 위해 formula 방법 randomForestdata 인수를 사용하도록 코드를 단순화 할 방법은 다음과 같습니다

## simulation: unchanged (but seed set for reproducibility) 
library(randomForest) 
n = 1000 
factor=10 
set.seed(47) 
x1 = seq(n) + rnorm(n, 0, 150) 
y = x1*factor + rnorm(n, 0, 550) 

    ## use a single data frame 
all_data = data.frame(y, x1) 

    ## define the folds outside the loop 
fold_ids <- cut(seq(1, nrow(x_data)), breaks = k, labels = FALSE) 

for (nfold in seq(k)) { 
    id_indices <- which(fold_ids == nfold) 
     ## sprintf can be nicer than paste for "filling in blanks" 
    print(sprintf("number of rows in fold %s is %s", nfold, length(id_indices))) 
     ## just pass the subset of the data directly to randomForest 
     ## no need for extracting, subsetting, putting back in data frames... 
    rf <- randomForest(y ~ ., data = all_data[id_indices, ], ntree = 1000) 
     ## sprintf also allows for formatting 
     ## the %g will use scientific notation if the exponent would be >= 3 
    print(sprintf("mse for fold %s is %g", nfold, sum(rf$mse))) 
}