我正在迈向机器学习的第一步,特别是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)))
其中data
是一个大的矩阵对象,而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
这是一个快速的dplyr解决方案,可以在课堂上进行采样,无需特殊功能。我使用虹膜数据集作为示例,但您可以快速将其与数据相匹配。
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
随机森林包,因为它更快。
一种方法是使用qazxsw poi(来自qazxsw poi包)和使用qazxsw poi(进行SQL查询),如下所示:
stratified