python - 如何将连续变量转换为分类变量?

标签 python python-3.x scikit-learn random-forest

请用这个给我指出正确的方向。如何将包含连续变量的列转换为离散变量?我有金融工具的价格,我正试图将其转换为某种分类值(value)。我以为我可以做到以下几点。

labels = df['PRICE'].astype('category').cat.categories.tolist()
replace_map_comp = {'PRICE' : {k: v for k,v in zip(labels,list(range(1,len(labels)+1)))}}
print(replace_map_comp)

但是,当我尝试对数据子集运行 RandomForestClassifier 时,出现错误。
from sklearn.ensemble import RandomForestClassifier
features = np.array(['INTEREST',
'SPREAD',
'BID',
'ASK',
'DAYS'])
clf = RandomForestClassifier()
clf.fit(df[features], df1['PRICE'])

错误消息为:ValueError: Unknown label type: 'continuous'
我很确定这很接近,但这里肯定有一些东西。

下面的代码更新:
# copy only numerics to new DF
df1 = df.select_dtypes(include=[np.number])

from sklearn import linear_model
features = np.array(['INTEREST',
'SPREAD',
'BID',
'ASK',
'DAYS'])
reg = linear_model.LinearRegression()
reg.fit(df1[features], df1['PRICE'])

# problems start here...
importances = clf.feature_importances_
sorted_idx = np.argsort(importances)

padding = np.arange(len(features)) + 0.5
plt.barh(padding, importances[sorted_idx], align='center')
plt.yticks(padding, features[sorted_idx])
plt.xlabel("Relative Importance")
plt.title("Variable Importance")
plt.show()

错误:AttributeError:'LinearRegression' 对象没有属性 'feature_importances_'

以下概念来自这里:

http://blog.yhat.com/tutorials/5-Feature-Engineering.html

仅供引用,我尝试了 one-hot 编码,代码转换使列变得太大,我遇到了错误。也许处理这个问题的方法是取一小部分数据。有 250k 行,我猜也许 100k 行应该足以代表整个数据集。也许这就是要走的路。只是在这里大声思考。

最佳答案

Pandas 有一个 cut可以为您尝试做的事情工作的功能:

import pandas as pd
import numpy as np
from scipy.stats import norm
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import LabelEncoder

label_encoder = LabelEncoder()
n_bins = 5
df = pd.DataFrame(data=norm.rvs(loc=500, scale=50, size=100),
                  columns=['PRICE'])
y = label_encoder.fit_transform(pd.cut(df['PRICE'], n_bins, retbins=True)[0])
rfc = RandomForestClassifier(n_estimators=100, verbose=2)
rfc.fit(df[['PRICE']], y)

这是一个示例示例。首先要知道有一百种不同的方法可以做到这一点,所以这不一定是“正确”的方法;这只是一种方式。

主要思想:使用 Pandas cut函数为连续数据创建桶。桶的数量由您决定。我选择了n_bins5在这个例子中。

有了 bins 后,可以使用 sklearn 的 LabelEncoder() 将它们转换为类。 .这样,您就可以更轻松地引用这些类。它就像您的类(class)的存储系统,因此您可以跟踪它们。使用 label_encoder.classes_看类(class)。

完成这些步骤后,y看起来像这样:
array([1, 2, 2, 0, 2, 2, 0, 1, 3, 1, 1, 2, 1, 4, 4, 2, 3, 1, 1, 3, 2, 3,
       2, 2, 2, 0, 2, 2, 4, 1, 3, 2, 1, 3, 3, 2, 1, 4, 3, 1, 1, 4, 2, 3,
       3, 2, 1, 1, 3, 4, 3, 3, 3, 2, 1, 2, 3, 1, 3, 1, 2, 0, 1, 1, 2, 4,
       1, 2, 2, 2, 0, 1, 0, 3, 3, 4, 2, 3, 3, 2, 3, 1, 3, 4, 2, 2, 2, 0,
       0, 0, 2, 2, 0, 4, 2, 3, 2, 2, 2, 2])

您现在已经将连续数据转换为类,现在可以传递给 RandomForestClassifier() .

关于python - 如何将连续变量转换为分类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57047429/

相关文章:

java - 如何从图像中获取 EXIF 或元数据?

python - 强制命令打开时 paramiko 不起作用

python-3.x - 在python3中导入时间模块

python - 精度为 0% 的 SVC 分类器

python - 测试依赖于硬件的 Python 代码

javascript - Jupyter 笔记本 : How do I execute only cells that have a particular tag

python - 修复 python 中的 %s sql 查询

Django - 用作表达式的子查询返回不止一行

python - 为什么 AdaBoost 不能与 DecisionTree 一起工作?

python - 如何在 Scikit-Learn (sklearn) 中将 `log_loss` 中的 `GridSearchCV` 与多类标签一起使用?