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

How to convert a continuous variable to a categorical variable?

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

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 行应该可以很好地代表整个数据集。也许这就是要走的路。只是在这里大声思考。

One-hot 编码是一种方法。

https://www.ritchieng.com/machinelearning-one-hot-encoding/

https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html

看起来像这样: 资料来源:https://towardsdatascience.com/natural-language-processing-count-vectorization-with-scikit-learn-e7804269bb5e

分类器在您面对 类 解释变量并且价格不是 类 的情况下很好,除非您使总和精确 类:

df['CLASS'] = np.where( df.PRICE > 1000, 1, 0) # Classify price above 1000 or less

在使用连续解释变量的情况下,回归方法是非常可取的。

from sklearn import linear_model
reg = linear_model()
reg.fit(df[features], df['CLASS'])

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)

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

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

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

完成这些步骤后,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()

from sklearn.preprocessing import LabelEncoder
label_encoder = LabelEncoder()
n_bins = 10
dseries, return_bins = pd.qcut(train['price'], n_bins, retbins=True)

n_bins=n_bins+2
return_bins[0]=return_bins[0]*.99
return_bins[-1]=return_bins[-1]*0.99
return_bins_lst=[r for r  in return_bins]
return_bins_lst.insert(0,return_bins[0]*1000)
return_bins_lst.append(return_bins[-1]*1000)
return_bins=np.array(return_bins_lst)
 
train['label']=label_encoder.fit_transform(pd.cut(train['price'], return_bins, 
labels=range(n_bins)))
test['label']=label_encoder.transform(pd.cut(test['price'], return_bins, 
labels=range(n_bins)))

几乎使用了 Jarad 给出的示例,但进行了一些概括,以便您可以在 train/test 个数据集之间保持编码一致

除了许多其他方法之外,实现分箱的简单方法是:按距离或按频率分箱。

import pandas as pd
df = pd.read_csv('Tax_Calculation.csv')
min = df['Direct_Tax'].min()
max = df['Direct_Tax'].max()

假设所需的 bin 数量为:4,因此我们需要 5 条边(边 = number_of_bin + 1)。 edge1 Bin1 edge2 Bin2 edge3 Bin3 edge4 Bin4 edge5

import numpy as np
bins = np.linspace(min,max, 5)

按距离分箱(将值分组为分箱数):

df['bins_dist'] = pd.cut(df['Direct_Tax'], bins=bins, labels=[ExSmall, Small, Medium, Large], include_lowest=True)

按频率分箱(按观察次数分箱):每个分箱将包含几乎相同数量的观察结果

df['bin_freq'] = pd.qcut(df['Direct_Tax'], q=4, precision=1, labels=[ExSmall, Small, Medium, Large])