【发布时间】:2018-09-25 14:18:38
【问题描述】:
我已经阅读了许多关于机器学习分类变量特征散列的在线文章。不幸的是,我仍然无法掌握这个概念并理解它是如何工作的。我将通过我从另一个站点获取的示例数据集和散列函数来说明我的困惑:
>>>data
pop state year
0 1.5 Ohio 2000
1 1.7 Ohio 2001
2 3.6 New York 2002
3 2.4 Nevada 2001
4 2.9 Nevada 2002
5 1.8 Oregon 2003
>>> def hash_col(df, col, N):
cols = [col + "_" + str(i) for i in range(N)]
def xform(x): tmp = [0 for i in range(N)]; tmp[hash(x) % N] = 1; return pd.Series(tmp,index=cols)
df[cols] = df[col].apply(xform)
return df.drop(col,axis=1)
以下函数用于通过指定不同的维数(或换句话说,散列特征)打印出不同的转换输出:
>>> print(hash_col(data, 'state',4))
pop year state_0 state_1 state_2 state_3
0 1.5 2000 0 0 1 0
1 1.7 2001 0 0 1 0
2 3.6 2002 0 0 0 1
3 2.4 2001 0 1 0 0
4 2.9 2002 0 1 0 0
5 1.8 2003 0 0 0 1
>>> print(hash_col(data, 'state',5))
pop year state_0 state_1 state_2 state_3 state_4
0 1.5 2000 1 0 0 0 0
1 1.7 2001 1 0 0 0 0
2 3.6 2002 1 0 0 0 0
3 2.4 2001 0 0 1 0 0
4 2.9 2002 0 0 1 0 0
5 1.8 2003 0 0 0 0 1
>>> print(hash_col(data, 'state',6))
pop year state_0 state_1 state_2 state_3 state_4 state_5
0 1.5 2000 0 0 0 0 1 0
1 1.7 2001 0 0 0 0 1 0
2 3.6 2002 0 0 0 0 0 1
3 2.4 2001 0 0 0 1 0 0
4 2.9 2002 0 0 0 1 0 0
5 1.8 2003 0 0 0 0 0 1
我无法理解的是 'state_0'、'state_1'、'state_2' 等列分别代表什么。另外,由于我的数据集中有 4 个独特的州(俄亥俄州、纽约州、内华达州、俄勒冈州),为什么所有的 '1' 只分配给 3 个 'state_n'列而不是 4 作为一种热编码?例如,当我将维度数设置为 6 时,输出在 state_3、state_4 和 state_5 中有两个 '1',但是有在 state_0、state_1 和 state_2 中没有“1”。任何反馈将不胜感激!
【问题讨论】:
标签: pandas machine-learning hash scikit-learn string-hashing