首页 > 解决方案 > randomForest 模型大小取决于训练集大小:避免的方法?

问题描述

我正在训练一个 randomForest 模型,目的是保存它以进行预测(它将被下载并在外部环境中使用)。我希望这个模型尽可能小。

我读过有许多选项可以减少模型的内存大小。

不过,我不明白为什么训练集的大小与模型的大小有关?毕竟,一旦有了森林的系数,为什么还需要保留原始数据集呢?

df <- iris
model <- randomForest::randomForest(Species ~ ., data = df, 
                 localImp = FALSE,
                 importance = FALSE,
                 keep.forest = TRUE,
                 keep.inbag = FALSE,
                 proximity=FALSE,
                 ntree = 25)
object.size(model)/1000
#> 73.2 bytes

df <- df[sample(nrow(df), 50), ]
model <- randomForest::randomForest(Species ~ ., data = df, 
                 localImp = FALSE,
                 importance = FALSE,
                 keep.forest = TRUE,
                 keep.inbag = FALSE,
                 proximity=FALSE,
                 ntree = 25)
object.size(model)/1000
#> 43 bytes

reprex 包(v0.2.1)于 2019 年 5 月 21 日创建

我已经尝试过上面提到的技巧来减小大小,但与训练集大小的作用相比,它们的效果是微不足道的。有没有办法删除这些信息?

标签: rmachine-learningmemory-managementclassificationrandom-forest

解决方案


我认为您可以在适合后删除模型的某些部分:

object.size(model)/1000
# 70.4 bytes

model$predicted <- NULL # remove predicted
model$y <- NULL # remove y
#.. possibly other parts aren't needed
object.size(model)/1000
# 48.3 bytes

我检查了predict(model, df)它是否仍然有效,并且确实有效。

用来names(model)检查里面的元素model

看起来$votes很大,你不需要它,这里有更多我安全删除的项目:

model$predicted <- NULL
model$y <- NULL
model$err.rate <- NULL
model$test <- NULL
model$proximity <- NULL
model$confusion <- NULL
model$localImportance <- NULL
model$importanceSD <- NULL
model$inbag <- NULL
model$votes <- NULL
model$oob.times <- NULL


object.size(model)/1000
# 32.3 bytes

例子:

df <- iris
model <- randomForest::randomForest(Species ~ ., data = df, 
                 localImp = FALSE,
                 importance = FALSE,
                 keep.forest = TRUE,
                 keep.inbag = FALSE,
                 proximity=FALSE,
                 ntree = 25)

推荐阅读