【问题标题】:Reverse Label Encoder Features in PythonPython中的反向标签编码器功能
【发布时间】:2019-09-09 05:31:45
【问题描述】:

考虑以下我试图对其进行预测的示例表

如你所见,我混合了数值 (Num1 & Num2) 和分类特征 (Cat1 & Cat2) 来预测一个值,我是使用随机森林回归来做到这一点

读入文件后,我正在使用 LabelEncoder 将分类特征转换为数值特征,就像这样

category_col =['Cat1', 'Cat2'] 
labelEncoder = preprocessing.LabelEncoder()

# creating a map of all the numerical values of each categorical labels.
mapping_dict={}
for col in category_col:
    df[col] = labelEncoder.fit_transform(df[col])
    le_name_mapping = dict(zip(labelEncoder.classes_, labelEncoder.transform(labelEncoder.classes_)))
    mapping_dict[col]=le_name_mapping

转换后,我将数据框拆分为训练和测试集并进行预测,就像这样

train_features, test_features, train_labels, test_labels = train_test_split(df, labels, test_size = 0.30)

rf = RandomForestRegressor(n_estimators = 1000)
rf.fit(train_features, train_labels)
predictions = rf.predict(test_features)

我的问题是,如何更改 Cat1 和 Cat2 的数字以再次显示原始类别,以便我可以将预测导出回来,就像这样

我知道我需要使用 labelEncoder.inverse_transform,但是,我似乎无法获得正确的语法来获取与结果相关的类别文本。

感谢任何帮助!

【问题讨论】:

    标签: python machine-learning regression random-forest


    【解决方案1】:

    快速解决方案,基于您已有的代码:

    # Invert the mapping dictionary you created
    inv_mapping_dict = {cat: {v: k for k, v in map_dict.items()} for cat, map_dict in mapping_dict.items()}
    
    # Assuming `predictions` is your resulting dataframe.
    # Replace the predictions with the inverted mapping dictionary.
    predictions.replace(inv_mapping_dict)
    

    为了获得更好的方法,您也可以在创建初始映射字典时考虑此处的答案:

    Label encoding across multiple columns in scikit-learn

    您可以在列上创建一个 LabelEncoders 字典,然后在开始和结束处同时应用列的拟合和反转,而不是在类别列上使用 for 循环来创建映射字典。

    【讨论】:

    • 谢谢,我确实对您发布的那个链接有疑问,那里显示的方法对我的数据框中的所有变量进行编码。如何挑选出我需要的两列并使用该方法对它们进行编码?
    猜你喜欢
    • 1970-01-01
    • 2021-02-17
    • 2020-11-30
    • 1970-01-01
    • 2019-09-22
    • 2018-04-14
    • 1970-01-01
    • 2019-09-07
    • 2016-10-10
    相关资源
    最近更新 更多