首页 > 解决方案 > 随机森林分类和训练/测试分割

问题描述

我正在迈出机器学习的第一步,特别是 R。我以前使用过 python 的 sklearn,但我对 R 完全陌生。对于一个大学项目,我正在出于教育目的在基因表达数据集上尝试一个随机森林。我正在尝试使用各种脑细胞的基因表达来预测精神障碍(双相情感障碍、抑郁症或精神分裂症)。我的脚本目前看起来像这样:

library(randomForest)

train_ind <- sample.int(n = nrow(GSMdata),
                         size = floor(0.75*nrow(GSMdata)),
                         replace = F)
RFtrainSet <- data[,train_ind]
RFtestSet <- data[,-train_ind]
RFtrainLabel <- GSMdata$Disease_State[train_ind]
RFtestLabel <- GSMdata$Disease_State[-train_ind]

RFmodel <- randomForest(x = t(RFtrainSet),
                        y = RFtrainLabel,
                        ntree = 100)

table(RFtestLabel, predict(object = RFmodel, 
                           newdata = t(RFtestSet)))

wheredata是一个大矩阵对象,GSMdata是一个具有每个样本特征的数据框(matrx 中的每一列代表每个样本的基因表达)。该table函数的输出如下所示:

RFtestLabel                 bipolar disorder control major depressive disorder schizophrenia
  bipolar disorder                         0       7                         6             7
  control                                  0       7                         6             0
  major depressive disorder                0       5                         2             2
  schizophrenia                            0       1                         7             2

正如您在上面的示例中所见,当我对数据进行采样时,测试数据集中经常不会出现一个类。这是一个问题吗?如果是,是否有帮助我获得同质测试样本的功能?

数据示例

data矩阵:

          GSM1304852  GSM1304853  GSM1304854 GSM1304855 GSM1304856
1007_s_at  2.3945368  2.27518369  2.16116298  1.9641833  2.1322526
1053_at    0.1051084  0.06160802  0.34217618  0.3593916  0.2235696
117_at    -0.4597124 -0.52310349 -0.44360591 -0.6370277 -0.3511470
121_at     0.9333566  1.13180904  0.99756999  1.0079778  0.9720455
1255_g_at -0.2399138  0.10112324 -0.04087979 -0.2185137 -0.2991786

GSMdata例子:

                   title geo_accession Age    Disease_State Gender  pH  PMI Race RIN      tissue
GSM1304852 bipolar_hip_10    GSM1304852  52 bipolar disorder      M 6.7 23.5    W 6.3 hippocampus
GSM1304853 bipolar_hip_11    GSM1304853  50 bipolar disorder      F 6.4 11.7    W 6.8 hippocampus
GSM1304854 bipolar_hip_12    GSM1304854  28 bipolar disorder      F 6.3 22.3    W 7.7 hippocampus
GSM1304855 bipolar_hip_13    GSM1304855  55 bipolar disorder      F 6.4 17.5    W 7.6 hippocampus
GSM1304856 bipolar_hip_14    GSM1304856  58 bipolar disorder      M 6.8 27.7    W 7.0 hippocampus

标签: rmachine-learningrandom-forest

解决方案


这是一个在类内采样的快速 dplyr 解决方案,不需要特殊功能。我以 iris 数据集为例,但您可以快速调整它以适应您的数据。

library(dplyr)
data(iris)
labels <- iris %>% dplyr::select(Species) %>% 
    sample_frac(1) %>% 
    group_by(Species) %>% 
    mutate(set = rep(c(rep("train",3),"test"), length.out=n()))

table(labels$Species, labels$set)

             test train
  setosa       12    38
  versicolor   12    38
  virginica    12    38

另外,我会推荐ranger随机森林包,因为它更快。


推荐阅读