Python中的反向标签编码器功能

时间:2019-04-18 20:42:02

标签: python machine-learning regression random-forest

请考虑以下示例表,我正在此表上进行预测

enter image description here

如您所见,我混合使用数字(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的数字以再次显示原始类别,以便像这样导出预测结果

enter image description here

我了解我需要使用 labelEncoder.inverse_transform ,但是,我似乎无法正确使用语法来检索类别文本以与结果配合使用。

感谢您的帮助!

1 个答案:

答案 0 :(得分: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循环来创建映射字典,然后在开始和结束时一次全部应用列的fit和inverse。