Python中sklearn随机森林分类的内存分配错误

3
我正在尝试在具有5个属性和1个类的2,79,900个实例上运行sklearn随机森林分类。但是,在运行fit线时,我遇到了内存分配错误,它无法训练分类器本身。有什么建议可以解决这个问题吗?
数据为:
x,y,day,week,Accuracy
其中,x和y是坐标,day是月份中的哪一天(1-30),week是星期中的哪一天(1-7),accuracy是整数。
代码:
import csv
import numpy as np
from sklearn.ensemble import RandomForestClassifier


with open("time_data.csv", "rb") as infile:
    re1 = csv.reader(infile)
    result=[]
    ##next(reader, None)
    ##for row in reader:
    for row in re1:
        result.append(row[8])

    trainclass = result[:251900]
    testclass = result[251901:279953]


with open("time_data.csv", "rb") as infile:
    re = csv.reader(infile)
    coords = [(float(d[1]), float(d[2]), float(d[3]), float(d[4]), float(d[5])) for d in re if len(d) > 0]
    train = coords[:251900]
    test = coords[251901:279953]

print "Done splitting data into test and train data"

clf = RandomForestClassifier(n_estimators=500,max_features="log2", min_samples_split=3, min_samples_leaf=2)
clf.fit(train,trainclass)

print "Done training"
score = clf.score(test,testclass)
print "Done Testing"
print score

错误:

line 366, in fit
    builder.build(self.tree_, X, y, sample_weight, X_idx_sorted)
  File "sklearn/tree/_tree.pyx", line 145, in sklearn.tree._tree.DepthFirstTreeBuilder.build
  File "sklearn/tree/_tree.pyx", line 244, in sklearn.tree._tree.DepthFirstTreeBuilder.build
  File "sklearn/tree/_tree.pyx", line 735, in sklearn.tree._tree.Tree._add_node
  File "sklearn/tree/_tree.pyx", line 707, in sklearn.tree._tree.Tree._resize_c
  File "sklearn/tree/_utils.pyx", line 39, in sklearn.tree._utils.safe_realloc
MemoryError: could not allocate 10206838784 bytes
3个回答

1
来自scikit-learn文档: "控制树的大小的参数(例如: max_depth,min_samples_leaf等)的默认值会导致生长和未修剪的树在某些数据集上可能非常大。为了减少内存消耗,应该通过设置这些参数值来控制树的复杂度和大小。" 我建议您尝试调整这些参数。此外,如果您的计算机内存不足,您可以尝试使用内存分析器或在GoogleCollaborator上运行它。

我尝试使用max_features="log2",min_samples_split=3,min_samples_leaf=2作为我的参数,但仍然面临相同的问题,我可能会尝试max depth。我有16GB的内存。 - Labeo
根据我拥有的功能数量,深度永远不可能太大了,对吧? - Labeo
我一定会设置max_depth。决策树在高深度处极易过拟合。通常深度为6就足够了,但这当然取决于您的模型。 - jubueche
能否分块运行数据?我尝试过在25000个点上运行,它可以运行。但我认为最终结果是相同的,所以不需要这样做。 - Labeo
我认为你可以这样做。但是,如果在不同的数据块上训练两个模型,结果会不同。你尝试过使用max_depth吗? - jubueche

1
请尝试使用Google Colaboratory。您可以连接本地主机或托管运行时。对于n_estimators = 10000,它对我有用。

0
我最近也遇到了类似的MemoryErr问题。但是我通过减少训练数据量而不是修改模型参数来解决了这个问题。我的OOB值为0.98,这意味着该模型非常不可能出现过拟合情况。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接