为什么sklearn RandomForest模型在保存后需要占用大量磁盘空间?

ppl*_*ski 7 python random-forest scikit-learn

我正在从sklearn库中保存RandomForestClassifier模型,代码如下

with open('/tmp/rf.model', 'wb') as f:
    cPickle.dump(RF_model, f)
Run Code Online (Sandbox Code Playgroud)

我的硬盘需要很大的空间.模型中只有50棵树,但它在磁盘上占用超过50 MB(分析的数据集大约为20MB,具有21个功能).有人知道为什么吗?我观察到ExtraTreesClassifier的类似行为.

编辑:射频参数:

"n_estimators": 50,
"max_features": 0.2,
"min_samples_split": 20,
"criterion": "gini",
"min_samples_leaf": 11
Run Code Online (Sandbox Code Playgroud)

正如@dooms所建议的,我检查了sys.getsizeof并返回64 - 我认为这只是指针大小.

我尝试了其他方式来保存模型:

from sklearn.externals import joblib
joblib.dump(RF_model, 'filename.pkl') 
Run Code Online (Sandbox Code Playgroud)

通过使用这种方式,我得到1*.pkl文件和201*.npy文件,总大小为14.9 MB,比以前的53 MB小.这些201 npy文件中有一个模式 - Forest中每棵树有4个文件:

第一个文件(231 KB)内容:

array([(1, 1062, 20, 0.2557438611984253, 0.4997574055554296, 29168, 46216.0),
       (2, 581, 12, 0.5557271242141724, 0.49938159451291675, 7506, 11971.0),
       (3, 6, 14, 0.006186043843626976, 0.4953095968671224, 4060, 6422.0),
       ...,
       (4123, 4124, 15, 0.6142271757125854, 0.4152249134948097, 31, 51.0),
       (-1, -1, -2, -2.0, 0.495, 11, 20.0),
       (-1, -1, -2, -2.0, 0.3121748178980229, 20, 31.0)], 
      dtype=[('left_child', '<i8'), ('right_child', '<i8'), ('feature', '<i8'), ('threshold', '<f8'), ('impurity', '<f8'), ('n_node_samples', '<i8'), ('weighted_n_node_samples', '<f8')])
Run Code Online (Sandbox Code Playgroud)

第二个文件(66 kB)内容:

array([[[  2.25990000e+04,   2.36170000e+04]],

       [[  6.19600000e+03,   5.77500000e+03]],

       [[  3.52200000e+03,   2.90000000e+03]],

       ..., 
       [[  3.60000000e+01,   1.50000000e+01]],

       [[  1.10000000e+01,   9.00000000e+00]],

       [[  2.50000000e+01,   6.00000000e+00]]])
Run Code Online (Sandbox Code Playgroud)

第三个文件(88B):

array([2])
Run Code Online (Sandbox Code Playgroud)

组(96B)中的最后一个文件:

array([ 0.,  1.])
Run Code Online (Sandbox Code Playgroud)

有什么想法是什么?我试着在sklearn中查看Tree代码,但这很难.任何想法如何保存sklearn树,它存储更少的磁盘?(只是指出xgboost类似大小的整体占用了大约200KB)

adr*_*rin 0

您无法将 aRandomForestXGBoost模型进行比较,因为 a 中的树XGBoost非常浅,而 a 中的树RandomForest则更深。这意味着随机森林中的每棵树也更大。如果您想比较尺寸,或者您想要一个占用更少空间的模型,您应该使用HistGradientBoostingClassifieror a HistGradientBoostingRegressorfromsklearn代替。