【问题标题】:How to correctly encode categorical for sklearn - memory error for decision tree如何正确编码 sklearn 的分类 - 决策树的内存错误
【发布时间】:2020-07-22 04:44:45
【问题描述】:

这是我第一次接触 sklearn 库,老实说,由于我在互联网上找到了许多“做事的方法”,我脑子里一片混乱。 所以我有我清理过的数据库,看起来像这样:

<class 'pandas.core.frame.DataFrame'>
Int64Index: 246858 entries, 2 to 371527
Data columns (total 11 columns):
name                  246858 non-null object
price                 246858 non-null int64
vehicleType           246858 non-null object
yearOfRegistration    246858 non-null int64
gearbox               246858 non-null object
powerPS               246858 non-null int64
model                 246858 non-null object
kilometer             246858 non-null int64
fuelType              246858 non-null object
brand                 246858 non-null object
notRepairedDamage     246858 non-null object
dtypes: int64(4), object(7)
memory usage: 22.6+ MB

所以我想对价格变量进行分类。显然我必须对分类进行编码:

categorical = ['name', 'vehicleType', 'gearbox', 'model', 'fuelType', 'brand', 'notRepairedDamage']

这就是问题所在。我总是遇到内存错误。我尝试使用数据框映射器:

encoding = DataFrameMapper([
    (['name', 'vehicleType', 'gearbox', 'model', 'fuelType', 'brand', 'notRepairedDamage'], 
      OneHotEncoder(handle_unknown='ignore')),    
    (["price", "yearOfRegistration", "powerPS", "kilometer"], None)
])
encoding_target = DataFrameMapper([
    (['price'], none)
])

现在这很好,假设我想尝试一个分类树,我必须创建训练和测试,但在我必须应用转换之前:

X = encoding.transform(data.loc[:, data.columns != "price"])

此时我得到一个内存错误。我也想不通

【问题讨论】:

    标签: python encoding scikit-learn decision-tree


    【解决方案1】:

    试试这个:

    for cat in categorical:
        data[cat] = data[cat].astype('category')
        data[cat] = data[cat].cat.codes
    

    【讨论】:

    • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
    • 所以,我设法避免了内存错误。我刚刚删除了名称列。我认为型号和品牌就足够了。我已经尝试过为猫分配代码。变量。它确实有效,但算法质量的差异没有改变。此外,通过这种方法,一旦汽车是一个数字,您就无法返回。除非你不建立一个字典并在每次你想知道什么车是某个数字时检查它。
    猜你喜欢
    • 2015-04-07
    • 2020-10-23
    • 2018-09-15
    • 2020-05-19
    • 2019-03-04
    • 2018-08-14
    • 2023-04-08
    • 2017-10-05
    • 2018-08-14
    相关资源
    最近更新 更多