基于.coef_u值百分位的SVC的ScikitLearn特征选择

2024-10-01 07:34:14 发布

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

我试图编写一个Python类,以便使用.coef_属性值来选择scikitlearn0.17.1中的特性。我只想选择其.coef_值在第10个百分位及以上(第10、11、12、13、14、15、16、…、94、95、96、97、98、99、100)的特征。在

我无法使用SelectFromModels()完成这项工作,因此我尝试为这个特性选择编写一个名为ChooseCoefPercentile()的自定义类。我尝试使用以下函数根据.coef_的百分位数选择功能:

from sklearn.datasets import load_iris
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(load_iris().data,
                                   load_iris().target, test_size=0.33, random_state=42)

def percentile_sep(coefs,p):
    from numpy import percentile as pc
    gt_p = coefs[coefs>pc(coefs,p)].argsort()
    return list(gt_p)

from sklearn.base import BaseEstimator, TransformerMixin
class ChooseCoefPercentile(BaseEstimator, TransformerMixin):
    def __init__(self, est_, perc=50):
        self.perc = perc
        self.est_ = est_
    def fit(self, *args, **kwargs):
        self.est_.fit(*args, **kwargs)
        return self
    def transform(self, X):
        perc_i = percentile_sep(self.est_.coef_,self.perc)
        i_ = self.est_.coef_.argsort()[::-1][perc_i[:]]
        X_tr = X[:,i_]
        self.coef_ = self.est_.coef_[i_]
        return X_tr

# Import modules
from sklearn import svm,ensemble,pipeline,grid_search

# Instantiate feature selection estimator and classifier
f_sel = ChooseCoefPercentile(svm.SVC(kernel='linear'),perc=10)
clf = ensemble.RandomForestClassifier(random_state=42,oob_score=False)

CustPipe = pipeline.Pipeline([("feat_s",f_sel),("Clf",clf)])
bf_est = grid_search.GridSearchCV(CustPipe,cv=2,param_grid={'Clf__n_estimators':[100,200]})
bf_est.fit(X_train, y_train)

我得到以下错误:

^{pr2}$

下一行中.coef_值的NumPy数组似乎有问题:

i_ = self.est_.coef_.argsort()[::-1][perc_i[:]]

在这一行中,我试图根据索引只选择那些位于10%以上的.coef_值。索引存储在列表perc_i中。我似乎无法使用此列表正确索引.coef_数组。在

发生此错误是因为数组需要分成行吗?或者我应该使用其他方法来提取基于百分位的.coef_值吗?在


Tags: fromtestimportselfirisdefloadtrain
1条回答
网友
1楼 · 发布于 2024-10-01 07:34:14

我建议使用基于行数的模运算来计算系数矩阵的相关列:

def transform(self, X):
    perc_i = percentile_sep(self.est_.coef_,self.perc)
    nclass=self.est_.coef_.shape[0]
    i_ = list(set(map(lambda x:x%nclass,perc_i)))
    X_tr = X[:,i_]
    self.coef_ = self.est_.coef_[i_]
    return X_tr

相关问题 更多 >