计算RandomForestClassifier和IsolationForest的内存使用量

问题描述 投票:0回答:2

我想评估一下两者都用了多少内存

sklearn.ensemble.IsolationForest
sklearn.ensemble.RandomForestClassifier

但是

sys.sizeof(my_isolation_forest_model)
sys.sizeof(my_random_forest_classifier_model)

无论模型如何拟合,始终返回值 48。

你能帮我看看我的模型使用了多少内存空间吗?

scikit-learn random-forest isolation-forest
2个回答
3
投票

Scikit-Learn 树使用 Cython 数据结构表示,它不会以有意义的方式与 Python 的

sizeof
函数交互 - 您只是看到指针的大小。

作为解决方法,您可以将这些 Cython 数据结构转储到 Pickle 文件(或任何替代序列化协议/数据格式)中,然后测量该文件的大小。来自 Cython 数据结构的数据都会在那里。

使用 Pickle 时,请务必禁用任何数据压缩!


0
投票

我发现使用

sizeof
和其他内存分析库(如 pympler)的方法产生的结果与预期不同(即比腌制的大小小得多)。

由于酸洗可能很耗时,所以我决定使用一种更快但稍微间接的方法;测量模型创建之前和之后进程的内存使用情况。

下面是我在脚本中使用的代码,用于测量我正在创建的模型的大小:

import psutil as ps
from sklearn.ensemble import RandomForestClassifier

model_sz = -ps.Process().memory_info().vms  # memory usage before building model

rfo = RandomForestClassifier(min_samples_leaf=2, max_depth=20, n_estimators=100)
rfo.fit(x_values, y_values)

model += ps.Process().memory_info().vms  # memory usage after building model

print(f"Model used { model_sz/1024 :,.2f} KiB of memory")

虽然这种方法是间接的,但它至少提供了接近于任务管理器中观察到的内存使用情况和 pickle 对象大小的输出。它也非常快,开销很小。

© www.soinside.com 2019 - 2024. All rights reserved.