1

我正在尝试在 R 中执行随机森林回归并且遇到了几个问题并且我自己已经修复了其中的大部分但是我无法解决最后一个问题。我有一个我想读入的文件列表,这没问题(我使用 for 循环)。

library(randomForest)
set.seed(51)

file<- c("file1","file2","file3")
targets<- c("X1.ts","ts2","ts3")

for (i in 1:length(file)){
d_names<-paste("C:\\location\folder\",drugs[i],".txt",sep="")
dataset<- read.table(d_names, header=TRUE, row.names=1)
ind<-sample(2,nrow(dataset), replace=TRUE)

#TRAINING DATASET1 PREDICTING DATASET2
train_one.rf<- randomForest(dataset[ind==1,][[1]] ~ .-targets[i], data=dataset[ind==1,], prob=c(0.7,0.3))
dset2.pred<- predict(train_one.rf, newdata=dataset[ind==2,])

#TRAINING DATASET2 PREDICTING DATASET1
train_two.rf<- randomForest(dataset[ind==2,][[1]] ~ .-targets[i], data=dataset[ind==2,], prob=c(0.7,0.3))
dset1.pred<- predict(train_two.rf, newdata=dataset[ind==1,])

}

随机森林的本质是我必须对不包括我希望预测的列的数据进行建模。为此,我必须使用:

dataset[ind==1,][[1]] ~ .-target[i]

这是我希望为每次运行随机森林添加列的名称(来自目标)的目标 [i] 。我曾尝试将其分配给一个变量,并将循环变量也放入其中,但无济于事。我想 R 中的公式部分需要一些比我更优雅的知识。

提前感谢,

乌鸦

4

1 回答 1

1

这是使用 mtcars 数据分成两个数据集作为 data1 和 data2 的解决方案。(这里没有 R for loop

data1<-mtcars[1:15,]
data2<-mtcars[16:nrow(mtcars),]
mydata<-list(data1,data2)

targets<-list("mpg~.","cyl~.")

Map(function(x) Map(function(y) randomForest(as.formula(y),data=x,importance=TRUE,proximity=TRUE), targets),mydata)

[[1]]
[[1]][[1]]

Call:
 randomForest(formula = as.formula(y), data = x, importance = TRUE,      proximity = TRUE) 
               Type of random forest: regression
                     Number of trees: 500
No. of variables tried at each split: 3

          Mean of squared residuals: 4.637522
                    % Var explained: 63.98

[[1]][[2]]

Call:
 randomForest(formula = as.formula(y), data = x, importance = TRUE,      proximity = TRUE) 
               Type of random forest: regression
                     Number of trees: 500
No. of variables tried at each split: 3

          Mean of squared residuals: 0.2455641
                    % Var explained: 89.04


[[2]]
[[2]][[1]]

Call:
 randomForest(formula = as.formula(y), data = x, importance = TRUE,      proximity = TRUE) 
               Type of random forest: regression
                     Number of trees: 500
No. of variables tried at each split: 3

          Mean of squared residuals: 10.90303
                    % Var explained: 78.93

[[2]][[2]]

Call:
 randomForest(formula = as.formula(y), data = x, importance = TRUE,      proximity = TRUE) 
               Type of random forest: regression
                     Number of trees: 500
No. of variables tried at each split: 3

          Mean of squared residuals: 0.1623937
                    % Var explained: 95.69


Warning messages:
1: In randomForest.default(m, y, ...) :
  The response has five or fewer unique values.  Are you sure you want to do regression?
2: In randomForest.default(m, y, ...) :
  The response has five or fewer unique values.  Are you sure you want to do regression?

注意:内部Map函数对目标的不同元素重复回归,而外部Map函数对 mydata 的不同元素重复回归。

于 2013-08-21T15:03:26.853 回答