【问题标题】:How to pre-process ordinal feature where feature values are range of numbers and rank or encode them accordingly如何预处理特征值是数字范围的序数特征并相应地对它们进行排名或编码
【发布时间】:2018-07-16 04:55:14
【问题描述】:

我的数据集中有以下特征列:

+-----------+
|   size    |
+-----------+
| 10-90     |
| <10       |
| 100-200   |
| 10-90     |
| 500-800   |
| 10000+    |
| <10       |
| 1000-4999 |
+-----------+

我是机器学习的新手,我发现很难处理这样的功能集。

当我这样做时:

import pandas as pd

y = pd.Categorical(train['size'],ordered=True)

y 的输出是:

[10-90, <10, 100-200, 10-90, 500-800, 10000+, <10, 1000-4999]
Categories (6, object): [10-90 < 100-200 < 1000-4999 < 10000+ < 500-800 < <10]

这是错误的,因为 10000 或 10000+ 应该获得最高排名。

我需要相应地对这些数据进行排名或编码,这样如果我的测试数据获得值 5 或

python 或 R 中是否有任何方法/包可以帮助我实现这一目标? 请帮忙。

【问题讨论】:

  • 我不是r coder,但是y = factor(train$size, levels = c('&lt;10', '10-90' , '100-200','500-800', '1000-4999', '10000+')) 工作怎么样?

标签: python machine-learning categorical-data feature-engineering


【解决方案1】:

Pandas解决方案也是指定categories是预期顺序:

cats= ['<10', '10-90' , '100-200','500-800', '1000-4999', '10000+']
y = pd.Categorical(train['size'],ordered=True, categories=cats)
print (y)
[10-90, <10, 100-200, 10-90, 500-800, 10000+, <10, 1000-4999]
Categories (6, object): [<10 < 10-90 < 100-200 < 500-800 < 1000-4999 < 10000+]

【讨论】:

  • x = np.unique(train_data['size']) print(x) array(['10-90', '100-200', '1000-4999', '10000+' , '500-800', '
  • 你的代码错误,因为需要手动指定类别,因为print (x)创建错误的顺序,因为按字典顺序排序,就像字符串一样。
  • 和排名使用print (y.codes) - codes
  • 我的数据有很多层级。所以我想避免手动分类。我明白如果这是唯一的方法。有没有办法将看不见的数据(例如,
  • @rjdj - 很难的问题,理论上是的。给我一些时间。
【解决方案2】:

R解决方案:

cats = c('<10', '10-90' , '100-200','500-800', '1000-4999', '10000+')

 factor(train$size,levels = cats,ordered = TRUE)
[1] 10-90     <10       100-200   10-90     500-800   10000+    <10       1000-4999
Levels: <10 < 10-90 < 100-200 < 500-800 < 1000-4999 < 10000+

ordered(train[['size']], levels=cats)
[1] 10-90     <10       100-200   10-90     500-800   10000+    <10       1000-4999
Levels: <10 < 10-90 < 100-200 < 500-800 < 1000-4999 < 10000+

无论您使用 python 还是 R,您需要知道的一件事是您需要按照您想要的顺序放置类别。只能手动完成..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 2020-08-06
    相关资源
    最近更新 更多