对多个分类特征(列)进行特征哈希

2024-10-02 22:23:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想散列功能'流派'分为6列和单独功能'出版商'到另外6列。我想要下面这样的东西:

      Genre      Publisher  0    1    2    3    4    5      0    1    2    3    4    5 
0     Platform  Nintendo  0.0  2.0  2.0 -1.0  1.0  0.0    0.0  2.0  2.0 -1.0  1.0  0.0
1       Racing      Noir -1.0  0.0  0.0  0.0  0.0 -1.0   -1.0  0.0  0.0  0.0  0.0 -1.0
2       Sports     Laura -2.0  2.0  0.0 -2.0  0.0  0.0   -2.0  2.0  0.0 -2.0  0.0  0.0
3  Roleplaying      John -2.0  2.0  2.0  0.0  1.0  0.0   -2.0  2.0  2.0  0.0  1.0  0.0
4       Puzzle      John  0.0  1.0  1.0 -2.0  1.0 -1.0    0.0  1.0  1.0 -2.0  1.0 -1.0
5     Platform      Noir  0.0  2.0  2.0 -1.0  1.0  0.0    0.0  2.0  2.0 -1.0  1.0  0.0

下面的代码可以执行我想做的事情

^{pr2}$

这适用于上面两个特性,但是如果我有40个分类特性,那么这个方法将是乏味的。还有别的办法吗?在


Tags: 功能特性johnpublisherplatform出版商sportspuzzle
1条回答
网友
1楼 · 发布于 2024-10-02 22:23:58

哈希(更新)

假设新的类别可能会出现在一些特性中,散列是一种方法。只需2个注意事项:

  • 注意碰撞的可能性,并相应地调整功能的数量
  • 在您的情况下,您需要分别散列每个特性

一个热点向量

如果每个特性的类别数量是固定的且不太大,则使用一个热编码。在

我建议使用以下两种方法之一:

  1. sklearn.preprocessing.OneHotEncoder
  2. pandas.get_dummies

示例

import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.feature_extraction import FeatureHasher
from sklearn.preprocessing import OneHotEncoder

df = pd.DataFrame({'feature_1': ['A', 'G', 'T', 'A'],
                   'feature_2': ['cat', 'dog', 'elephant', 'zebra']})

# Approach 0 (Hashing per feature)
n_orig_features = df.shape[1]
hash_vector_size = 6
ct = ColumnTransformer([(f't_{i}', FeatureHasher(n_features=hash_vector_size, 
                        input_type='string'), i) for i in range(n_orig_features)])

res_0 = ct.fit_transform(df)  # res_0.shape[1] = n_orig_features * hash_vector_size

# Approach 1 (OHV)
res_1 = pd.get_dummies(df)

# Approach 2 (OHV)
res_2 = OneHotEncoder(sparse=False).fit_transform(df)

res_0

^{pr2}$

res_1

   feature_1_A  feature_1_G  feature_1_T  feature_2_cat  feature_2_dog  feature_2_elephant  feature_2_zebra
0            1            0            0              1              0                   0                0
1            0            1            0              0              1                   0                0
2            0            0            1              0              0                   1                0
3            1            0            0              0              0                   0                1

res_2

array([[1., 0., 0., 1., 0., 0., 0.],
       [0., 1., 0., 0., 1., 0., 0.],
       [0., 0., 1., 0., 0., 1., 0.],
       [1., 0., 0., 0., 0., 0., 1.]])

相关问题 更多 >