如何在Python中进行热编码?

发布于 2021-02-02 23:09:00

我有一个80%分类变量的机器学习分类问题。如果要使用一些分类器进行分类,是否必须使用一种热编码?我可以在没有编码的情况下将数据传递给分类器吗?

我正在尝试进行以下功能选择:

我读了火车文件:

num_rows_to_read = 10000
train_small = pd.read_csv("../../dataset/train.csv",   nrows=num_rows_to_read)

我将类别特征的类型更改为“类别”:

non_categorial_features = ['orig_destination_distance',
                          'srch_adults_cnt',
                          'srch_children_cnt',
                          'srch_rm_cnt',
                          'cnt']

for categorical_feature in list(train_small.columns):
    if categorical_feature not in non_categorial_features:
        train_small[categorical_feature] = train_small[categorical_feature].astype('category')

我使用一种热编码:

train_small_with_dummies = pd.get_dummies(train_small, sparse=True)

问题是,尽管我使用的是坚固的机器,但第3部分经常卡住。

因此,没有一种热编码,我就无法进行任何特征选择来确定特征的重要性。

你有什么建议吗?

关注者
0
被浏览
73
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    方法1:你可以在pandas数据框上使用get_dummies

    范例1:

    import pandas as pd
    s = pd.Series(list('abca'))
    pd.get_dummies(s)
    Out[]: 
         a    b    c
    0  1.0  0.0  0.0
    1  0.0  1.0  0.0
    2  0.0  0.0  1.0
    3  1.0  0.0  0.0
    

    范例2:

    下面将把给定的列转换为热点。使用前缀具有多个虚拟变量。

    import pandas as pd
    
    df = pd.DataFrame({
              'A':['a','b','a'],
              'B':['b','a','c']
            })
    df
    Out[]: 
       A  B
    0  a  b
    1  b  a
    2  a  c
    
    # Get one hot encoding of columns B
    one_hot = pd.get_dummies(df['B'])
    # Drop column B as it is now encoded
    df = df.drop('B',axis = 1)
    # Join the encoded df
    df = df.join(one_hot)
    df  
    Out[]: 
           A  a  b  c
        0  a  0  1  0
        1  b  1  0  0
        2  a  0  0  1
    

    方法2:使用Scikit学习

    给定具有三个特征和四个样本的数据集,我们让编码器找到每个特征的最大值,并将数据转换为二进制的一键编码。

    >>> from sklearn.preprocessing import OneHotEncoder
    >>> enc = OneHotEncoder()
    >>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])   
    OneHotEncoder(categorical_features='all', dtype=<class 'numpy.float64'>,
       handle_unknown='error', n_values='auto', sparse=True)
    >>> enc.n_values_
    array([2, 3, 4])
    >>> enc.feature_indices_
    array([0, 2, 5, 9], dtype=int32)
    >>> enc.transform([[0, 1, 1]]).toarray()
    array([[ 1.,  0.,  0.,  1.,  0.,  0.,  1.,  0.,  0.]])
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看