【发布时间】:2019-09-02 09:14:08
【问题描述】:
我想对一些打包为 numpy.ndarray 的数据运行 sklearn 的 RandomForestClassifier,而这些数据恰好是稀疏的。
调用fit 会得到ValueError: setting an array element with a sequence.。从其他帖子中我了解到随机森林无法处理稀疏数据。
我希望该对象具有todense 方法,但它没有。
>>> X_train
array(<1443899x1936774 sparse matrix of type '<class 'numpy.float64'>'
with 141256894 stored elements in Compressed Sparse Row format>,
dtype=object)
>>> type(X_train)
<class 'numpy.ndarray'>
我尝试用 SciPy csr_matrix 包装它,但这也会产生错误。
有没有办法让随机森林接受这些数据? (不确定密集是否真的适合内存,但这是另一回事......)
编辑 1
产生错误的代码是这样的:
X_train = np.load('train.npy') # this returns a ndarray
train_gt = pd.read_csv('train_gt.csv')
model = RandomForestClassifier()
model.fit(X_train, train_gt.target)
至于使用toarray()的建议,ndarray没有这种方法。
AttributeError: 'numpy.ndarray' object has no attribute 'toarray'
此外,如前所述,对于这个特定的数据,我需要 TB 的内存来保存数组。是否可以选择使用稀疏数组运行 RandomForestClassifier?
编辑 2
似乎应该使用 SciPy 的 sparse 保存数据,如此处Save / load scipy sparse csr_matrix in portable data format 所述。 当使用 NumPy 的保存/加载时,应该保存更多数据。
【问题讨论】:
-
请提供minimal reproducible example,以便我们查看导致错误的代码。现在,您只显示
X_train的类型,但既不显示它的形状,也不显示您将其输入RandomForestClassifier的方式。可能是数据形状不正确,请参阅this related question 的答案。
标签: python numpy scikit-learn