2016-05-31 2 views
0

내 데이터 집합에 대해 Random Forest 분류를 여러 번 실행하는 R 스크립트를 작성했습니다. 보다 견고한 결과를 얻으려면 평균 10 회 이상의 평균을 사용하고 싶습니다. 그래서 나는 for 루프를 가지고 Random Forest 분류자를 여러 번 실행하고있다. (n = iterations).R 임의의 포리스트 결과를 파일로 작성

iterateRandomForest <- function (samples,iterations,output_text,outname,pVSURF,b) { 
    for (i in (1: iterations)) { 

    cat("\n Loop starts", "\n", file=output_text,append=TRUE)  
    time <- toString(Sys.time()) 
    cat(time,"\n", file=output_text,append=TRUE) 
    cat("Iteration number ",i," for variable set: ", outname, "\n", sep="",file=output_text,append=TRUE) 

    load(pVSURF) 
    sel.vars <- x$varselect.pred + 1 
    colnames(samples[,sel.vars]) 

    ptm <- proc.time()                # Start timer to calculate processing length 
    (rf.final_ntree501 = randomForest(samples[,"species_na"], x=samples[,sel.vars], 
         ntree=b, importance=TRUE, norm.votes=TRUE, proximity=TRUE)) # Run randomForest 

    ### PROBLEM HERE 
    cat(rf.final_ntree501,file=output_text,append=TRUE) 
    ### PROBLEM ENDS 

    cat("Processing time: ",proc.time() - ptm, "\n", file=output_text,append=TRUE)  # Stop timer 
    cat("Loop ends\n", file=output_text,append=TRUE) 
    } 
} 

보통은 다음과 같은 결과를 인쇄하기 위해 만든 임의의 숲 개체 (rf.final_ntree501)의 이름을 쓸 수 있습니다 :

Call: 
    randomForest(x = samples[, sel.vars], y = samples[, "species_na"],  ntree = b, importance = TRUE, proximity = TRUE, norm.votes = TRUE) 
      Type of random forest: classification 
       Number of trees: 501 
No. of variables tried at each split: 4 

    OOB estimate of error rate: 45.43% 
Confusion matrix: 
       Acacia mearnsii Cupressus lusitanica Eucalyptus sp. Euphorbia sp. Ficus sp. Grevillea robusta Maesa lanceolata other Persea americana class.error 
Acacia mearnsii     34     1    3    0   0     7    0 28    0 0.5342466 
Cupressus lusitanica    4     3    8    0   0    13    0 16    0 0.9318182 
Eucalyptus sp.      5     0    35    0   0    15    0  8    0 0.4444444 
Euphorbia sp.      0     0    1   16   0     2    0 15    0 0.5294118 
Ficus sp.       0     0    0    1   1     5    0 17    0 0.9583333 
Grevillea robusta     5     2    3    0   1    91    0 29    1 0.3106061 
Maesa lanceolata     4     0    0    0   0     2    0 14    0 1.0000000 
other        16     0    3    4   1    27    1 189    1 0.2190083 
Persea americana     5     1    0    0   0     6    0 33    1 0.9782609 

그래서 내가 원하는 이 정보를 루프 내부의 파일에 씁니다 (여기의 문제 참조). RF 객체를 직접 목록으로 작성할 수는 없다는 것을 알고 있습니다. 고양이와 rf.final_ntree501 $ 혼동으로 혼란 행렬을 따로 저장하려고하면. 정보를 저장하지만 행렬의 공식을 엉망으로 만들고 모든 정보를 클래스 이름을 제외한 한 행에 넣습니다.

아무에게도이 문제를 올바르게 처리하는 데 유용한 아이디어가 있습니까?

건배, 라미

답변

1

대신 사용 cat()capture.output()는 파일로가 콘솔에 표시되는 방식을 결과를 작성합니다.

# generate random data 
samples <- matrix(runif(675), ncol = 9) 
resp <- as.factor(sample(LETTERS[1:9], 75, replace = TRUE)) 

# random forest 
rf <- randomForest(x = samples, y = resp, ntree = 501, 
    importance = TRUE, norm.votes = TRUE, proximity = TRUE) 

# save desired information into a file 
capture.output(rf, file = output_text, append = TRUE) 

혼란 행렬을 따로 저장하면 write.table()을 사용할 수 있습니다. 결과는 선택한 구분 기호 (예제의 탭)를 사용하여 기계로 읽을 수있는 형식으로 형식이 지정됩니다.

write.table(rf$confusion, file = "filename.txt", sep = "\t") 
+0

이 문제가 해결되었습니다. 고마워요 :) – RaimoGIS

+0

다음 대답을 받아 들일 것을 고려하십시오 :) – nya

+1

오, 그래, 미안. :). – RaimoGIS