Python SKLearn:如何在一个hotecoder之后获取特性名称?

2024-05-18 00:46:23 发布

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

我想在数据集被SKLearn onehotecoder转换后获取它的特征名称。

active_features_ attribute in OneHotEncoder中,我们可以看到一个很好的解释:在执行transform()之后,feature_indices_active_features_属性是如何被填充的。

我的问题是:

例如,对于基于数据帧的输入数据:

data = pd.DataFrame({"a": [0, 1, 2,0], "b": [0,1,4, 5], "c":[0,1,4, 5]}).as_matrix()

代码是如何从原始的特征名abc获得转换后的特征名列表的 (例如:

a-0a-1a-2b-0b-1b-2b-3c-0c-1c-2c-3

或者

a-0a-1a-2b-0b-1b-2b-3b-4b-5b-6b-7,^}

或任何有助于查看编码列分配给原始列的内容)。

背景:我想了解一些算法的特性重要性,以了解哪些特性对所用算法的影响最大。


Tags: 数据in名称算法transformattribute特征特性
3条回答

如果我理解正确,您可以使用feature_indices_来标识哪些列对应于哪个功能。

例如

import pandas as pd
from sklearn.preprocessing import OneHotEncoder
data = pd.DataFrame({"a": [0, 1, 2,0], "b": [0,1,4, 5], "c":[0,1,4, 5]}).as_matrix()
ohe = OneHotEncoder(sparse=False)
ohe_fitted = ohe.fit_transform(data)
print(ohe_fitted)
print(ohe.feature_indices_) # [ 0  3  9 15]

从上面的feature_indices_我们知道如果我们拼接来自0:3的一个热编码数据,我们将得到与data中第一列对应的特征,如下所示:

print(ohe_fitted[:,0:3])

拼接数据中的每一列表示第一个要素中的值。第一列是0,第二列是1,第三列是2。为了在拼接数据上演示这一点,列标签如下所示:

  a_0 a_1 a_2
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]
 [ 1.  0.  0.]]

请注意,在对特征进行编码之前,首先对其进行排序。

您可以使用pd.get_dummies()

pd.get_dummies(data["a"],prefix="a")

会给你:

    a_0 a_1 a_2
0   1   0   0
1   0   1   0
2   0   0   1
3   1   0   0

它可以自动生成列名。您可以将此应用于所有列,然后获取列名称。不需要将它们转换为numpy矩阵。

因此:

df = pd.DataFrame({"a": [0, 1, 2,0], "b": [0,1,4, 5], "c":[0,1,4, 5]})
data = df.as_matrix()

解决方案如下:

columns = df.columns
my_result = pd.DataFrame()
temp = pd.DataFrame()
for runner in columns:
    temp = pd.get_dummies(df[runner], prefix=runner)
    my_result[temp.columns] = temp
print(my_result.columns)

>>Index(['a_0', 'a_1', 'a_2', 'b_0', 'b_1', 'b_4', 'b_5', 'c_0', 'c_1', 'c_4',
       'c_5'],
      dtype='object')

您可以使用开源软件包功能引擎来实现这一点:

import pandas as pd
from sklearn.model_selection import train_test_split
from feature_engine.categorical_encoders import OneHotCategoricalEncoder

# load titanic data from openML
pd.read_csv('https://www.openml.org/data/get_csv/16826755/phpMYEkMl')

# divide into train and test
X_train, X_test, y_train, y_test = train_test_split(
    data[['sex', 'embarked']],  # predictors for this example
    data['survived'],  # target
    test_size=0.3,  # percentage of obs in test set
    random_state=0)  # seed to ensure reproducibility

ohe_enc = OneHotCategoricalEncoder(
    top_categories=None,
    variables=['sex', 'embarked'],
    drop_last=True)

ohe_enc.fit(X_train)

X_train = ohe_enc.transform(X_train)
X_test = ohe_enc.transform(X_test)

X_train.head()

您应该看到返回的输出:

   sex_female  embarked_S  embarked_C  embarked_Q
501            1           1           0           0
588            1           1           0           0
402            1           0           1           0
1193           0           0           0           1
686            1           0           0           1

有关功能引擎的更多详细信息,请参见:

https://www.trainindata.com/feature-engine

https://github.com/solegalli/feature_engine

https://feature-engine.readthedocs.io/en/latest/

相关问题 更多 >