python - 如何在 Python 中使用 factorize() 后获取原始值?

标签 python pandas random-forest prediction

我是一名初学者,尝试使用 Python 中的随机森林,使用训练和测试数据集创建预测模型。 train["ALLOW/BLOCK"] 可以取 4 个预期值中的 1 个(所有字符串)。 test["ALLOW/BLOCK"] 是需要预测的。

y,_ = pd.factorize(train["ALLOW/BLOCK"])

y
Out[293]: array([0, 1, 0, ..., 1, 0, 2], dtype=int64)

我使用 predict 进行预测。

clf.predict(test[features])

clf.predict(test[features])[0:10]
Out[294]: array([0, 0, 0, 0, 0, 2, 2, 0, 0, 0], dtype=int64)

如何获取原始值而不是数字值?以下代码实际上是在比较实际值和预测值吗?

z,_= pd.factorize(test["AUDIT/BLOCK"])

z==clf.predict(test[features])
Out[296]: array([ True, False, False, ..., False, False, False], dtype=bool) 

最佳答案

首先需要将pd.factorize返回的label保存如下:

y, label = pd.factorize(train["ALLOW/BLOCK"])

然后在你得到数字预测后,你可以通过label[pred]提取相应的标签:

pred = clf.predict(test[features])
pred_label = label[pred]

pred_label 包含具有原始值的预测。


不,您不应该重新分解测试预测,因为标签很可能会有所不同。考虑以下示例:

pd.factorize(['a', 'b', 'c'])
# (array([0, 1, 2]), array(['a', 'b', 'c'], dtype=object))

pd.factorize(['c', 'a', 'b'])
# (array([0, 1, 2]), array(['c', 'a', 'b'], dtype=object))

所以标签取决于元素的顺序。

关于python - 如何在 Python 中使用 factorize() 后获取原始值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46134201/

相关文章:

python - 如何使用随机森林分类器确定用于预测类别的特征值范围

machine-learning - 随机森林: how to favor false negatives over false positives

python - 组合和的记忆化与非记忆化时间复杂度分析

python - 如何在 python 中创建文件存在的 if 循环?

用于税收计算的 Python 原始输入函数

python - 机器学习: Getting error in Confusion Matrix

python - Pandas Dataframe 如何提取特定行之前的数据行?

python - 使用 groupby 和名称列表合并两个数据框

Python Pandas 使用日期时间数据按日期分组

python - Pandas :检查列的子集中的任何值是否符合条件