随机森林 运行

Random Forest run

我很难理解“randomForest”包中 RF 代码输入之间的差异。此参考建议使用

  ## 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,

,

据我了解,x 是带有预测变量的数据框,y 是响应变量。但是,我看到从同一篇论文生成此代码的示例首先使用响应变量,然后使用数据,

 iris.rf <- randomForest(Species ~ ., data=iris, importance=TRUE,
proximity=TRUE)

所以,我编写的代码有两种选择,但我不确定哪一种适合分类,为什么?

Here is my code: 

I am basically comparing the two codes for rf.




## create data frame 
 n   <- 199
  z   <- seq(-10, 10, length=n)
x<-sin(x)/x       
  y <-  rnorm(n, 0, 0.1)
  xy <- data.frame(x,y)


## create classes
 xy$Y<-sample(1:2,  n, replace = T)
   XY<-xy
   n <- nrow(XY)
   p <- ncol(XY)-1
   colnames(XY)[p+1]<-'Y'




## create trining and test sets
s     <- sample(sample(n)) 
    ntr   <- round(ptr*n) 
    id.tr <- s[1:ntr]
    id.te <- s[(ntr+1):n]
    XY.tr <- XY[id.tr, ]
    XY.te <- XY[id.te, ]
    y.te  <- XY[id.te, p+1]

    XY.tr$Y<-as.factor(XY.tr$Y)

##run Random forest
rf1 <- randomForest(XY.tr, data=XY.tr$Y, proximity=TRUE,importance=T) 
rf2<-randomForest(formula = XY.tr$Y ~ .,  data=XY.tr, proximity = TRUE, importance = T) 

非常感谢您的任何见解

两者都会给你相同的答案:

data(iris)                                                    #load data

在第一种方法中,您明确提供响应向量 y(但相应地更正您的代码):

set.seed(131)
rf1 <- randomForest(y= iris$Species, x=iris[1:4], proximity=TRUE, importance=T)  

在第二种方法中,您通过 公式 隐含地告知响应向量 y 并提供整个数据矩阵。

set.seed(131)
rf2<-randomForest(formula = Species ~ ., data=iris, importance=TRUE, proximity=TRUE)

请参阅 randomForest 的 R 文档:

Argument: x, formula:
a data frame or a matrix of predictors, or a formula describing the model
to be fitted (for the print method, an randomForest object).