具有递归特征的网格搜索在scikit-learn管道中消除会返回错误

hub*_*i86 11 python scikit-learn

我正在尝试使用scikit-learn在管道中链接网格搜索和递归特征消除.

具有"裸"分类器的GridSearchCV和RFE工作正常:

from sklearn.datasets import make_friedman1
from sklearn import feature_selection
from sklearn.grid_search import GridSearchCV
from sklearn.svm import SVR

X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)

est = SVR(kernel="linear")

selector = feature_selection.RFE(est)
param_grid = dict(estimator__C=[0.1, 1, 10])
clf = GridSearchCV(selector, param_grid=param_grid, cv=10)
clf.fit(X, y)
Run Code Online (Sandbox Code Playgroud)

将分类器放在管道中会返回错误:RuntimeError:分类器不公开"coef_"或"feature_importances_"属性

from sklearn.datasets import make_friedman1
from sklearn import feature_selection
from sklearn import preprocessing
from sklearn import pipeline
from sklearn.grid_search import GridSearchCV
from sklearn.svm import SVR

X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)

est = SVR(kernel="linear")

std_scaler = preprocessing.StandardScaler()
pipe_params = [('std_scaler', std_scaler), ('clf', est)]
pipe = pipeline.Pipeline(pipe_params)

selector = feature_selection.RFE(pipe)
param_grid = dict(estimator__clf__C=[0.1, 1, 10])
clf = GridSearchCV(selector, param_grid=param_grid, cv=10)
clf.fit(X, y)
Run Code Online (Sandbox Code Playgroud)

编辑:

我意识到我并不清楚这个问题.这是更清晰的片段:

from sklearn.datasets import make_friedman1
from sklearn import feature_selection
from sklearn import pipeline
from sklearn.grid_search import GridSearchCV
from sklearn.svm import SVR

X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)

# This will work
est = SVR(kernel="linear")
selector = feature_selection.RFE(est)
clf = GridSearchCV(selector, param_grid={'estimator__C': [1, 10]})
clf.fit(X, y)

# This will not work
est = pipeline.make_pipeline(SVR(kernel="linear"))
selector = feature_selection.RFE(est)
clf = GridSearchCV(selector, param_grid={'estimator__svr__C': [1, 10]})
clf.fit(X, y)
Run Code Online (Sandbox Code Playgroud)

如您所见,唯一的区别是将估算器放在管道中.但是,管道隐藏了"coef_"或"feature_importances_"属性.问题是:

  1. 在scikit-learn中有一个很好的处理方法吗?
  2. 如果没有,出于任何原因,这种行为是否合适?

EDIT2:

根据@Chris提供的答案更新了工作片段

from sklearn.datasets import make_friedman1
from sklearn import feature_selection
from sklearn import pipeline
from sklearn.grid_search import GridSearchCV
from sklearn.svm import SVR


class MyPipe(pipeline.Pipeline):

    def fit(self, X, y=None, **fit_params):
        """Calls last elements .coef_ method.
        Based on the sourcecode for decision_function(X).
        Link: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py
        ----------
        """
        super(MyPipe, self).fit(X, y, **fit_params)
        self.coef_ = self.steps[-1][-1].coef_
        return self


X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)

# Without Pipeline
est = SVR(kernel="linear")
selector = feature_selection.RFE(est)
clf = GridSearchCV(selector, param_grid={'estimator__C': [1, 10, 100]})
clf.fit(X, y)
print(clf.grid_scores_)

# With Pipeline
est = MyPipe([('svr', SVR(kernel="linear"))])
selector = feature_selection.RFE(est)
clf = GridSearchCV(selector, param_grid={'estimator__svr__C': [1, 10, 100]})
clf.fit(X, y)
print(clf.grid_scores_)
Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 6

您在使用管道时遇到问题。

管道的工作方式如下:

当调用.fit(x,y)等时,第一个对象将应用于数据。如果该方法公开了.transform()方法,则将应用此对象,并且此输出将用作下一阶段的输入。

管道可以具有任何有效的模型作为最终对象,但是所有先前的模型必须公开.transform()方法。

就像管道一样,您要输入数据,管道中的每个对象都将获取先前的输出并对其进行另一个转换。

我们可以看到,

http://scikit-learn.org/stable/modules/generation/sklearn.feature_selection.RFE.html#sklearn.feature_selection.RFE.fit_transform

RFE公开了一种转换方法,因此应包含在管道本身中。例如

some_sklearn_model=RandomForestClassifier()
selector = feature_selection.RFE(some_sklearn_model)
pipe_params = [('std_scaler', std_scaler), ('RFE', rfe),('clf', est)]
Run Code Online (Sandbox Code Playgroud)

您的尝试有一些问题。首先,您正在尝试扩展一部分数据。想象一下,我有两个分区[1,1],[10,10]。如果我通过分区的均值进行归一化,则会丢失第二个分区明显高于均值的信息。您应该在开始时进行缩放,而不是在中间进行缩放。

其次,SVR没有实现转换方法,您不能将其作为非最终元素合并到管道中。

RFE引入一个适合数据的模型,然后评估每个特征的权重。

编辑:

如果需要,可以通过将sklearn管道包装在自己的类中来包含此行为。我们想要做的是当我们拟合数据时,检索最后的估算器.coef_方法,并将其以正确的名称本地存储在派生类中。我建议您查看github上的源代码,因为这只是一个开始,可能需要更多错误检查等。Sklearn使用了一个称为的函数修饰符@if_delegate_has_method,可以方便地添加它,以确保该方法具有通用性。我已经运行了这段代码以确保它可以运行,但仅此而已。

from sklearn.datasets import make_friedman1
from sklearn import feature_selection
from sklearn import preprocessing
from sklearn import pipeline
from sklearn.grid_search import GridSearchCV
from sklearn.svm import SVR

class myPipe(pipeline.Pipeline):

    def fit(self, X,y):
        """Calls last elements .coef_ method.
        Based on the sourcecode for decision_function(X).
        Link: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/pipeline.py
        ----------
        """

        super(myPipe, self).fit(X,y)

        self.coef_=self.steps[-1][-1].coef_
        return

X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)

est = SVR(kernel="linear")

selector = feature_selection.RFE(est)
std_scaler = preprocessing.StandardScaler()
pipe_params = [('std_scaler', std_scaler),('select', selector), ('clf', est)]

pipe = myPipe(pipe_params)



selector = feature_selection.RFE(pipe)
clf = GridSearchCV(selector, param_grid={'estimator__clf__C': [2, 10]})
clf.fit(X, y)

print clf.best_params_
Run Code Online (Sandbox Code Playgroud)

如果不清楚,请询问。