【问题标题】:Pandas, Memory error when trying to substract two arraysPandas,尝试减去两个数组时出现内存错误
【发布时间】:2020-04-30 18:51:05
【问题描述】:

我一直在处理一个形状为 (345602,12) 的大型数据集,使用 scikitlearn 进行各种分析。在我运行 RandomForestRegressor 之前,我没有遇到任何问题:

from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    test_size=0.4,
                                                    random_state=1)

forest = RandomForestRegressor(n_estimators=100,
                               criterion='mse',
                               random_state=1,
                                n_jobs=-1)

forest.fit(X_train, y_train)
y_train_pred = forest.predict(X_train)
y_test_pred = forest.predict(X_test)

这部分有效,导致:

print(y_train.shape, y_train_pred.shape)
(207361,1) (207361,)   

print(y_test.shape, y_test_pred.shape)
(138241,1) (138241,)  

然后,当我尝试简单地减去它们时:

A=y_train_pred - y_train
B=y_test_pred - y_test

这就是它崩溃的地方。

MemoryError: Unable to allocate 320. GiB for an array with shape (207361, 207361) 和数据类型 float64

我觉得这很奇怪,因为我使用这个工具的数据集较小,没有任何问题。

【问题讨论】:

    标签: python pandas scikit-learn


    【解决方案1】:

    嗯,我找到了问题,这是一个简单的问题。问题在于数组的形状。

    RandomForestRegressor 将预测作为 r 行返回,将非数据作为 c 列之一返回。因此,在减法时,pandas 正在创建一个 rxc 矩阵而不是一维数组。 该错误通过转置一对值来解决。

    A=y_train_pred - np.transpose(y_train)
    B=y_test_pred - np.transpose(y_test)
    

    【讨论】:

    • 嗯,错误信息明显是在报告array with shape (207361, 207361)
    • 是的,但我对 python 还很陌生,所以我花了很长时间才理解它的含义。
    猜你喜欢
    • 1970-01-01
    • 2021-06-06
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多