R言語によるランダム森林の実現

22143 ワード

簡単なリンクから:http://www.jianshu.com/p/ca09dedb0541
1、2つ以上の組み合わせ木を1つの木にする:combine()
combine(...)

...:ランダムフォレストオブジェクトごと
data(iris)
rf1 50, norm.votes=FALSE)
rf2 50, norm.votes=FALSE)
rf3 50, norm.votes=FALSE)
rf.all 

2、森から木を抽出する:getTree()
getTree(rfobj, k=1, labelVar=FALSE)

rfobj:ランダムフォレストオブジェクトk:抽出ツリーの個数labelVar:FALSE or TRUE,より良いラベルは,分裂変数と予測のカテゴリが数値予測に用いられ,データと変数の値は分裂点から左サブノードに向かう以下である.分類の予測では、分裂点は整数を表し、そのバイナリ拡張に基づいてカテゴリが左サブノードに行くか右サブノードに行くかを判断することができる.たとえば、予測の4つのクラスの場合、分裂点は13です.13のバイナリ拡張は(1,0,1,1)(13=1(2^0)+0(2^1)+1(2^2)+1(2^3))であるため、カテゴリ1,3または4は左サブノードに予測され、残りは右サブノードに予測される.1つのマトリクス(またはlabelvar=trueの場合)6列6行で、合計はツリー内のノード数に等しい.6列は次のとおりです.
左の子:左の子ノードがある行;ノードが端末であれば0右子:右サブノードが存在する行;ノードが端末であれば0分割の変数:分割に用いられるノード;ノードが端末である場合、0分裂点:最良の分裂点状態:ノード端末(-1)または(1)予測なし:ノードの予測;ノードが端末でない場合は0
## Look at the third trees in the forest.
getTree(randomForest(iris[,-5], iris[,5], ntree=10), 3, labelVar=TRUE)

3、木の数を増やす:grow()
grow(x, how.many, ...)

x:ランダム森林オブジェクトhow.many:ツリーの数を増やす
data(iris)
iris.rf 50, norm.votes=FALSE)
iris.rf 50)
print(iris.rf)

4、特徴抽出の重要性:importance()
importance(x, type=NULL, class=NULL, scale=TRUE, ...)

x:ランダム森林オブジェクトtype:1または2、重要度メトリックタイプ、1は平均降順精度、2は平均降順ノード純度class:カテゴリメトリック
set.seed(4543)
data(mtcars)
mtcars.rf 1000,
keep.forest=FALSE, importance=TRUE)
importance(mtcars.rf)
importance(mtcars.rf, type=1)

5、図面:plot()
plot(x, sort=TRUE, ...)
set.seed(1)
data(iris)
iris.rf FALSE)
plot(margin(iris.rf))

6、分類図:MDSplot()
MDSplot(rf, fac, k=2, palette=NULL, pch=20, ...)

rf:ランダム森林オブジェクトfac:ランダム森林を訓練する因子k:次元数palette:色
set.seed(1)
data(iris)
iris.rf TRUE,
keep.forest=FALSE)
MDSplot(iris.rf, iris$Species)
## Using different symbols for the classes:
MDSplot(iris.rf, iris$Species, palette=rep(1, 3), pch=as.numeric(iris$Species))

7、欠落した値を埋める中位数:na.roughfix()
na.roughfix(object, ...)

数値変数すうちへんすう:欠落した値は中位数の置換因子を使用して引数を置換ちゅうけいちのちかんすうを使用します:欠落した値は最も一般的な置換を使用します
data(iris)
iris.na 111)
iris.na
## artificially drop some data values.
for (i in 1:4) iris.na[sample(150, sample(20)), i] NA
iris.roughfix 

8、異常値(群外点):outlier()
outlier(x, ...)
set.seed(1)
iris.rf 5], iris[,5], proximity=TRUE)
plot(outlier(iris.rf), type="h",
col=c("red", "green", "blue")[as.numeric(iris$Species)])

9.変数をグラフィカルに記述する境界効果(分類または回帰):partialPlot()
partialPlot(x, pred.data, x.var, which.class,
w, plot = TRUE, add = FALSE,
n.pt = min(length(unique(pred.data[, xname])), 51),
rug = TRUE, xlab=deparse(substitute(x.var)), ylab="",
main=paste("Partial Dependence on", deparse(substitute(x.var))),
...)

x:ランダム森林オブジェクトpred.data:予測データx.var:変数名which.class:分類データw:重み
data(iris)
set.seed(543)
iris.rf "versicolor")
## Looping over variables ranked by importance:
data(airquality)
airquality 131)
ozone.rf TRUE)
imp 1], decreasing=TRUE)]
op 2, 3))
for (i in seq_along(impvar)) {
  partialPlot(ozone.rf, airquality, impvar[i], xlab=impvar[i],
              main=paste("Partial Dependence on", impvar[i]),
              ylim=c(30, 70),col='blue')
}
par(op)

10、画平均分散:Plot()
plot(x, type="l", main=deparse(substitute(x)), ...)
data(mtcars)
plot(randomForest(mpg ~ ., mtcars, keep.forest=FALSE, ntree=100), log="y",col='red')

11、予測テストデータ:predict()
predict(object, newdata, type="response",
norm.votes=TRUE, predict.all=FALSE, proximity=FALSE, nodes=FALSE,
cutoff, ...)

object:ランダム森林オブジェクトnewdata:予測新しいデータtype:確率行列を使用するかカウント投票行列normを使用するか.votes:カウント投票マトリクス標準化predict.all:すべてのツリーを使用してnodesを予測するかどうか:最端末のノードcutoff:
data(iris)
set.seed(111)
ind 2, nrow(iris), replace = TRUE, prob=c(0.8, 0.2))
iris.rf 1,])
iris.pred 2,])
table(observed = iris[ind==2, "Species"], predicted = iris.pred)
## Get prediction for all trees.
predict(iris.rf, iris[ind == 2,], predict.all=TRUE)
## Proximities.
predict(iris.rf, iris[ind == 2,], proximity=TRUE)
## Nodes matrix.
str(attr(predict(iris.rf, iris[ind == 2,], nodes=TRUE), "nodes"))

12、ランダム森林モデル:randomForest()
## S3 method for class ’formula’
randomForest(formula, data=NULL, ..., subset, na.action=na.fail)
## Default S3 method:
randomForest(x, y=NULL, xtest=NULL, ytest=NULL, ntree=500,
mtry=if (!is.null(y) && !is.factor(y))
max(floor(ncol(x)/3), 1) else floor(sqrt(ncol(x))),
replace=TRUE, classwt=NULL, cutoff, strata,
sampsize = if (replace) nrow(x) else ceiling(.632*nrow(x)),
nodesize = if (!is.null(y) && !is.factor(y)) 5 else 1,
maxnodes = NULL,
importance=FALSE, localImp=FALSE, nPerm=1,
proximity, oob.prox=proximity,
norm.votes=TRUE, do.trace=FALSE,
keep.forest=!is.null(y) && is.null(xtest), corr.bias=FALSE,
keep.inbag=FALSE, ...)

## S3 method for class ’randomForest’
print(x, ...)

分類:
> data(iris)
> set.seed(71)
> iris.rf TRUE,
+ proximity=TRUE)
> print(iris.rf)
Call:
 randomForest(formula = Species ~ ., data = iris, importance = TRUE,      proximity = TRUE) 
               Type of random forest: classification
                     Number of trees: 500
No. of variables tried at each split: 2

        OOB estimate of  error rate: 5.33%
Confusion matrix:
           setosa versicolor virginica class.error
setosa         50          0         0        0.00
versicolor      0         46         4        0.08
virginica       0          4        46        0.08
> round(importance(iris.rf), 2)
             setosa versicolor virginica MeanDecreaseAccuracy
Sepal.Length   6.04       7.85      7.93                11.51
Sepal.Width    4.40       1.03      5.44                 5.40
Petal.Length  21.76      31.33     29.64                32.94
Petal.Width   22.84      32.67     31.68                34.50
             MeanDecreaseGini
Sepal.Length             8.77
Sepal.Width              2.19
Petal.Length            42.54
Petal.Width             45.77
> iris.mds 1 - iris.rf$proximity, eig=TRUE)
> op "s")
> pairs(cbind(iris[,1:4], iris.mds$points), cex=0.6, gap=0,
+ col=c("red", "green", "blue")[as.numeric(iris$Species)],
+ main="Iris Data: Predictors and MDS of Proximity Based on RandomForest")
> par(op)

監視ケースなし:
> set.seed(17)
> iris.urf 5])
> MDSplot(iris.urf, iris$Species)
> ## stratified sampling: draw 20, 30, and 20 of the species to grow each tree.
> (iris.rf2 1:4], iris$Species,
+ sampsize=c(20, 30, 20)))

Call:
 randomForest(x = iris[1:4], y = iris$Species, sampsize = c(20,      30, 20)) 
               Type of random forest: classification
                     Number of trees: 500
No. of variables tried at each split: 2

        OOB estimate of  error rate: 5.33%
Confusion matrix:
           setosa versicolor virginica class.error
setosa         50          0         0        0.00
versicolor      0         47         3        0.06
virginica       0          5        45        0.10

回帰:
data(airquality)
set.seed(131)
ozone.rf 3,
                         importance=TRUE, na.action=na.omit)
print(ozone.rf)
## Show "importance" of variables: higher value mean more important:
round(importance(ozone.rf), 2)
## "x" can be a matrix instead of a data frame:
set.seed(17)
x 5e2), 100)
y 2, 50)
(myrf ## "complicated" formula:
(swiss.rf 50),
                          data=swiss))
(predict(swiss.rf, swiss))
## Test use of 32-level factor as a predictor:
set.seed(1)
x 53, 10), x2=runif(530), y=rnorm(530))
(rf1 3], x[[3]], ntree=10))
## Grow no more than 4 nodes per tree:
(treesize(randomForest(Species ~ ., data=iris, maxnodes=4, ntree=30)))
## test proximity in regression
iris.rrf 1], iris[[1]], ntree=101, proximity=TRUE, oob.prox=FALSE)
str(iris.rrf$proximity)

13、クロス検証による特徴選択:rfcv()
rfcv(trainx, trainy, cv.fold=5, scale="log", step=0.5,
mtry=function(p) max(1, floor(sqrt(p))), recursive=FALSE, ...)
trainx:   
trainy:   
cv.fold:      
set.seed(647)
myiris 1:4], matrix(runif(96 * nrow(iris)), nrow(iris), 96))
result 3)
with(result, plot(n.var, error.cv, log="x", type="o", lwd=2))
## The following can take a while to run, so if you really want to try
## it, copy and paste the code into R.
## Not run:
result 5, rfcv(myiris, iris$Species), simplify=FALSE)
error.cv "[[", "error.cv")
matplot(result[[1]]$n.var, cbind(rowMeans(error.cv), error.cv), type="l",
lwd=c(2, rep(1, ncol(error.cv))), col=1, lty=1, log="x",
xlab="Number of variables", ylab="CV Error")
## End(Not run)

14、ランダム森林充填欠損値:rfImpute()
## Default S3 method:
rfImpute(x, y, iter=5, ntree=300, ...)

## S3 method for class ’formula’
rfImpute(x, data, ..., subset)

x:引数y:因変数
data:   
data(iris)
iris.na 111)
## artificially drop some data values.
for (i in 1:4) iris.na[sample(150, sample(20)), i] NA
set.seed(222)
iris.imputed 333)
iris.rf 

15、最適サンプリング:rfImpute()
tuneRF(x, y, mtryStart, ntreeTry=50, stepFactor=2, improve=0.05,
trace=TRUE, plot=TRUE, doBest=FALSE, ...)
data(fgl, package="MASS")
fgl.res 10], fgl[,10], stepFactor=1.5)

16、変数の重要性:varImpPlot()
arImpPlot(x, sort=TRUE, n.var=min(30, nrow(x$importance)),
type=NULL, class=NULL, scale=TRUE,
main=deparse(substitute(x)), ...)
set.seed(4543)
data(mtcars)
mtcars.rf 1000, keep.forest=FALSE,
                          importance=TRUE)
varImpPlot(mtcars.rf)

ランダム森林における決定木分裂方法
https://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm Gini importance Every time a split of a node is made on variable m the gini impurity criterion for the two descendent nodes is less than the parent node. Adding up the gini decreases for each individual variable over all trees in the forest gives a fast variable importance that is often very consistent with the permutation importance measure.
変数重要性評価
ランダム森林変数の重要性の計算方法は,Gini指数とテストセット(OOB)誤り率の2つである.R语言实现随机森林_第1张图片 R语言实现随机森林_第2张图片 R语言实现随机森林_第3张图片
importance(mtcars.rf)
       %IncMSE IncNodePurity
cyl  16.799437     173.03496
disp 18.946107     241.43741
hp   17.282802     186.55081
drat  6.961155      70.14317
wt   19.012343     248.53222
qsec  5.179746      30.64678
vs    5.147341      31.76982
am    5.357654      18.35507
gear  4.324805      16.00897
carb  9.825615      27.77433

ここで、%IncMSEおよびIncNodePurityはそれぞれ相対的重要度およびノード純度であり、相対的重要度はOOB誤り率に基づいており、ノード純度はGini指数に基づいている.