【问题标题】:Names for Feature Selection特征选择的名称
【发布时间】:2020-07-27 10:04:47
【问题描述】:

我想知道我的 RF 模型中的功能名称。我读到heregs.best_estimator_.named_steps["stepname"].feature_importances_ 的输出会从我的数据中镜像我的列。但是,gs.best_estimator_.... 的长度是 10,我有 13 列。有些列并不重要。从周围的其他答案(answer1answer2)来看,我必须在我的管道中声明一些东西。但我对声明什么感到困惑,因为这两个答案都涉及 PCA,而不是 RF。

这是我目前所拥有的。

from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import GridSearchCV
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn import datasets

# use iris as example
iris = datasets.load_iris()
X = iris.drop(['sepal_length'],axis=1)
y = iris.sepal_length
cats_feats = ['species']
X_train, X_test, y_train, y_test = \
        train_test_split(X, y, train_size=0.8, test_size=0.2, random_state=13)
# Pipeline
categorical_transformer = Pipeline(steps=[
                ('onehot', OneHotEncoder(handle_unknown='ignore',sparse=False))
                                    ])
# Bundle any preprocessing
preprocessor = ColumnTransformer(
    transformers=[
        ('cat', categorical_transformer, cat_feats)
    ])
rf = RandomForestRegressor(random_state = 13)
mymodel = Pipeline(steps = [('preprocessor', preprocessor),
                            ('model', rf)
                            ])
# For this example, I used default values. In reality I do use a dictionary of parameters
gs = GridSearchCV(mymodel
                           ,n_jobs = -1
                           ,cv = 5
                           )
gs.fit(X_train,y_train)

【问题讨论】:

    标签: python scikit-learn feature-selection grid-search


    【解决方案1】:

    为什么特征列表的长度不匹配

    您的特征长度不匹配,因为当您使用 ColumnTransformer 时,所有非分类列都被丢弃。默认情况下,它只保留指定了转换的列。因此,如果您不希望这种情况发生,则需要这样做

    preprocessor = ColumnTransformer(transformers=[('cat', OneHotEncoder(), cat_feats)],
                                     remainder='passthrough')
    

    (我删除了你的分类管道,这里没有必要)

    另外请记住,应用 OHE 将添加功能,因此功能的总数将比您一开始拥有的更多。

    如何获取特征名称

    安装完所有内容后,您需要为 OHE 的结果和剩余的数字列检索特征名称。

    对于 OHE 列:

    cat_features = gs.best_estimator_["preprocessor"].named_transformers_["cat"].get_feature_names()
    

    对于数字列,您需要声明 num_feats,其中所有数字特征的顺序与原始数据框中的顺序相同。

    那就这样吧:

    feature_names = np.concatenate((cat_features, num_feats))
    

    PS:这有点麻烦,可能会在以后的sklearn版本中改进,但到目前为止,这是程序

    【讨论】:

    • 像这样:num_feats = ['sepeal_width','petal_length',petal_width']
    • 另外,如果我将数据框中的数据排序为 cat1、num1、cat2、cat3、num2、num3 等,那么分类变量 1、数值变量 1、分类变量 2... .. 你的方法还能用吗?还是您会建议先组织数据框?
    • 为了完整起见,我确实重新组织了我的数据框,并且没有任何差异。似乎只要先是分类变量,然后是数据框顺序中的数字变量,用户应该是好的。
    • 没关系。重要的是,在创建 feature_name 数组时,您将按照上面计算的方式放置分类特征,然后所有数字特征按照它们在数据框中从左到右出现的顺序相同。
    猜你喜欢
    • 2012-12-17
    • 2017-02-10
    • 2017-06-03
    • 2020-08-13
    • 2016-01-27
    • 2014-09-20
    • 2019-01-06
    • 2022-07-06
    • 1970-01-01
    相关资源
    最近更新 更多