我正在尝试训练二元分类器
我的训练数据由图中的路径组成,其中每个节点都有一个名称。
例如,我的训练数据中可能包含以下内容:
["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,...等。但这不是我想要的。我希望第一条路径有一个数字,第二条路径有一个数字,等等。我可以做什么来实现这个目标?
再次强调,路径中项目的顺序很重要。
最佳答案
您需要 reshape 测试
:
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]
关于python - 使用 Sklearn featurehasher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35096996/