gpt4 book ai didi

python - 什么是特征哈希(hashing-trick)?

转载 作者:太空狗 更新时间:2023-10-29 17:19:48 29 4
gpt4 key购买 nike

我知道特征散列 (hashing-trick) 用于降低维度和处理位向量的稀疏性,但我不明白它是如何工作的。谁能给我解释一下。是否有任何 python 库可用于进行特征散列?

谢谢。

最佳答案

在 Pandas 上,你可以使用这样的东西:

import pandas as pd
import numpy as np

data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
'year': [2000, 2001, 2002, 2001, 2002],
'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}

data = pd.DataFrame(data)

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 1 0 0
1 1.7 2001 0 1 0 0
2 3.6 2002 0 1 0 0
3 2.4 2001 0 0 0 1
4 2.9 2002 0 0 0 1

同样在系列级别,您可以

将 numpy 导入为 np, os将 sys、pandas 导入为 pd

def hash_col(df, col, N):
df = df.replace('',np.nan)
cols = [col + "_" + str(i) for i in range(N)]
tmp = [0 for i in range(N)]
tmp[hash(df.ix[col]) % N] = 1
res = df.append(pd.Series(tmp,index=cols))
return res.drop(col)

a = pd.Series(['new york',30,''],index=['city','age','test'])
b = pd.Series(['boston',30,''],index=['city','age','test'])

print hash_col(a,'city',10)
print hash_col(b,'city',10)

这将适用于单个系列,列名将被假定为 Pandas 索引。它还用 nan 替换空白字符串,并 float 所有内容。

age        30
test NaN
city_0 0
city_1 0
city_2 0
city_3 0
city_4 0
city_5 0
city_6 0
city_7 1
city_8 0
city_9 0
dtype: object
age 30
test NaN
city_0 0
city_1 0
city_2 0
city_3 0
city_4 0
city_5 1
city_6 0
city_7 0
city_8 0
city_9 0
dtype: object

但是,如果有一个词汇表,而你只想单热编码,你可以使用

import numpy as np
import pandas as pd, os
import scipy.sparse as sps

def hash_col(df, col, vocab):
cols = [col + "=" + str(v) for v in vocab]
def xform(x): tmp = [0 for i in range(len(vocab))]; tmp[vocab.index(x)] = 1; return pd.Series(tmp,index=cols)
df[cols] = df[col].apply(xform)
return df.drop(col,axis=1)

data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
'year': [2000, 2001, 2002, 2001, 2002],
'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}

df = pd.DataFrame(data)

df2 = hash_col(df, 'state', ['Ohio','Nevada'])

print sps.csr_matrix(df2)

这将给

   pop  year  state=Ohio  state=Nevada
0 1.5 2000 1 0
1 1.7 2001 1 0
2 3.6 2002 1 0
3 2.4 2001 0 1
4 2.9 2002 0 1

我还添加了最终数据帧的稀疏化。在我们可能没有事先遇到所有值的增量设置中(但我们以某种方式获得了所有可能值的列表),可以使用上述方法。增量 ML 方法在每个增量需要相同数量的特征,因此单热编码必须在每个批处理产生相同数量的行。

关于python - 什么是特征哈希(hashing-trick)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8673035/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com