请用这个给我指明正确的方向。如何将包含连续变量的列转换为离散变量?我有一些金融工具的价格,我正试图将其转换成某种绝对值。我以为我可以做到以下几点。
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
仅供参考,我尝试了单热编码,代码转换使列太大,我得到了一个错误。也许处理这个问题的方法是获取一小部分数据。对于 250k 行,我猜 100k 行应该可以很好地代表整个数据集。也许这就是要走的路。只是在这里大声思考。
原文由 ASH 发布,翻译遵循 CC BY-SA 4.0 许可协议
Pandas 有一个 cut 函数,可以用于你正在尝试做的事情:
这是一个示例。首先要知道有一百种不同的方法可以做到这一点,所以这不一定是“正确”的方法;这只是一种方式。
主要思想:使用 Pandas
cut
函数为连续数据创建桶。桶的数量由您决定。在本例中,我选择了n_bins
作为5
。有了垃圾箱后,可以使用 sklearn 的
LabelEncoder()
将它们转换为类。这样,您就可以更轻松地回顾这些类。它就像是您课程的存储系统,因此您可以跟踪它们。使用label_encoder.classes_
查看课程。完成这些步骤后,
y
将如下所示:您现在已将连续数据转换为类,现在可以传递给
RandomForestClassifier()
。