【问题标题】:Using Sklearn's feature hasher使用 Sklearn 的特征散列器
【发布时间】:2016-01-30 20:01:12
【问题描述】:

我正在尝试训练一个二元分类器

我的训练数据由图中的路径组成,其中每个节点都有一个名称。

例如,我的训练数据中可能包含以下内容:

["thing_a","cats_are_cool","blah"] 可能属于 0 类。

订单很重要。所以 ["node_a","node_b","node_c"] != ["node_c","node_b","node_a"]

由于我的路径可以有不同的长度,我想我需要对训练数据进行哈希处理,因为用零填充较短的路径听起来很危险。我想使用 sci kit learn 的功能散列器。在以下示例中,测试变量由三个路径组成:

h = FeatureHasher(n_features=2**20,non_negative=True,input_type = 'string')
test = [["unit_a","unit_b","unit_c"],["unit_c","unit_d","unit_c"],["unit_f","unit_aa"]]
X_new = h.transform(test)
print X_new.nonzero()

这给了我:

(array([0, 0, 0, 1, 1, 2, 2], dtype=int32), array([ 211168,  221554,  875718,  211168, 1009892,  765479,  838855], dtype=int32))

我认为哈希器正在制作“unit_a”= 211168,“unit_b”= 221554,...等。但这不是我想要的。我希望第一条路径有一个数字,第二条路径有一个数字,等等。我该怎么做才能做到这一点?

再一次,路径中的项目顺序很重要。

【问题讨论】:

    标签: python hash machine-learning scikit-learn


    【解决方案1】:

    你需要重塑test

    In [608]:
    from sklearn.feature_extraction import FeatureHasher
    h = FeatureHasher(n_features=2**20,non_negative=True,input_type = 'string')
    test = [["unit_a","unit_b","unit_c"],["unit_c","unit_d","unit_c"],["unit_f","unit_aa"]]
    test = [[','.join(x) for x in test]] # join and reshape
    X_new = h.transform(test)
    test,X_new.nonzero()
    
    Out[608]:
    ([['unit_a,unit_b,unit_c', 'unit_c,unit_d,unit_c', 'unit_f,unit_aa']],
     (array([0, 0, 0], dtype=int32), array([231648, 410028, 497899], dtype=int32)))
    

    不过,我可能会建议您保持简单:

    In [610]:
    test = [["unit_a","unit_b","unit_c"],["unit_c","unit_d","unit_c"],["unit_f","unit_aa"]]
    test_hash = [hash(tuple(x))%2**20 for x in test]
    test_hash
    
    Out[610]:
    [736062, 345078, 521256]
    

    【讨论】:

      猜你喜欢
      • 2017-04-01
      • 2019-06-13
      • 2014-04-11
      • 2012-01-30
      • 2018-12-25
      • 2017-04-06
      • 2018-05-04
      • 2018-06-08
      • 2014-09-03
      相关资源
      最近更新 更多