数据在scikit-learn变换器中不是持久的

时间:2017-01-24 19:23:48

标签: python machine-learning scikit-learn

我想在scikit-learn中将其他数据传递给变压器:

from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.ensemble import RandomForestClassifier

from sklearn.pipeline import Pipeline
import numpy as np
from sklearn.model_selection import GridSearchCV

class myTransformer(BaseEstimator, TransformerMixin):
    def __init__(self, my_np_array):
        self.data = my_np_array
        print self.data

    def transform(self, X):
        return X

    def fit(self, X, y=None):
        return self

data = np.random.rand(20,20)
data2 = np.random.rand(6,6)
y = np.array([1, 2, 3, 1, 2, 3, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 3, 3, 3, 3])

pipe = Pipeline(steps=[('myt', myTransformer(data2)), ('randforest', RandomForestClassifier())])
params = {"randforest__n_estimators": [100, 1000]}
estimators = GridSearchCV(pipe, param_grid=params, verbose=True)
estimators.fit(data, y)

然而,当在scikit-learn管道中使用时,它似乎消失了

我从init方法中的print中得到None。我该如何解决?

1 个答案:

答案 0 :(得分:3)

这是因为sklearn以非常具体的方式处理估算器。通常,它将为网格搜索等事物创建一个新的实例,并将参数传递给构造函数。这是因为sklearn有自己的克隆操作(defined in base.py) 获取估算器类,获取参数(由get_params返回)并将其传递给类的构造函数

klass = estimator.__class__
new_object_params = estimator.get_params(deep=False)
for name, param in six.iteritems(new_object_params):
    new_object_params[name] = clone(param, safe=False)
new_object = klass(**new_object_params) 

为了支持您的对象必须覆盖get_params(deep=False)方法,该方法应该返回字典,这将传递给构造函数

from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
class myTransformer(BaseEstimator, TransformerMixin):
    def __init__(self, my_np_array):
        self.data = my_np_array
        print self.data

    def transform(self, X):
        return X

    def fit(self, X, y=None):
        return self

    def get_params(self, deep=False):
        return {'my_np_array': self.data}

将按预期工作。