gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:43:32 25 4
gpt4 key购买 nike

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

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,但是,我似乎无法获得正确的语法来获取类别文本以与结果相结合。

感谢任何帮助!

最佳答案

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

# 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

您可以在列上创建一个 LabelEncoder 字典,然后在开头和结尾同时应用列的拟合和逆运算,而不是在类别列上使用 for 循环来创建映射字典。

关于python - Python 中的反向标签编码器功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55753470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com