2017-01-25 3 views
0

을 scikit 배우기 : 나는 다음 (및 기타)의 추정과 파이프 라인을 만들나는이 같은 추정이 GridSearchCV

from sklearn.base import BaseEstimator, TransformerMixin 
    import numpy as np 

    class customEstimator(BaseEstimator, TransformerMixin): 
     def __init__(self, estimator_var): 
      self.estimator_var = estimator_var 
     def transform(self, X): 
      self.tmpVar = np.random.randn(estimator_var, estimator_var) 
      return np.hstack((self.tmpVar, X)) # this is just an example 
     def fit(self, X, y=None): 
      return self 
     def get_params(self, deep=False): 
      return {'estimator_var': self.estimator_var, 'tmpVar': tmpVar} 

및 K-배에 대한 GridSearchCV로 공급 교차 검증. 케이 - 배 교차 검증은 이런 식입니다 :

for all possible params combination: 
    for every fold split 
    compute score(mini_train, mini_test) 
    compute average score 
pick best combination 
문제는 매개 변수의 특정 조합에 대한, 내가 한 번만 (계산이 느려질 수 있습니다) self.tmpVar을 계산하고자하는, 그리고 그것을 사용하는 것입니다

동일한 매개 변수 조합을 공유하는 모든 폴드 분할.

scikit-learn에서 가능할까요, 아니면 해결 방법이 있습니까?

답변

1

이 변수를 클래스의 정적 속성또는 다른 모든 전역 이름 범위로 저장하기 만하면됩니다. 당신이 다른 데이터와 함께, 귀하의 추정 여러 번 재사용 할 경우 물론

from sklearn.base import BaseEstimator, TransformerMixin 
import numpy as np 

class customEstimator(BaseEstimator, TransformerMixin): 

    tmpVar = None 

    def __init__(self, estimator_var): 
     self.estimator_var = estimator_var 
    def transform(self, X): 
     if customEstimator.tmpVar is None: 
      customEstimator.tmpVar = np.random.randn(estimator_var, estimator_var) 
     return np.hstack((customEstimator.tmpVar, X)) # this is just an example 
    def fit(self, X, y=None): 
     return self 
    def get_params(self, deep=False): 
     return {'estimator_var': self.estimator_var} 

여기서 문제는 때로는 재설정 할 할 이다. 그런 다음 각 견적 자에 대한 이름을 간단히 지정하고이 이름을 키로 사용하여 맵 (사전)에 이러한 tmpVars를 저장할 수 있습니다. 당신이 customEstimator의 새 인스턴스를 만들 경우 새 이름을 얻을 것이다,

from sklearn.base import BaseEstimator, TransformerMixin 
import numpy as np 

class customEstimator(BaseEstimator, TransformerMixin): 

    tmpVars = {} 
    estimators = 0 

    def __init__(self, estimator_var, name=None): 
     if name is None: 
      customEstimator.estimators = customEstimator.estimators + 1 
      name = 'Estimator %d' % customEstimator.estimators 
     self.name = name 
     self.estimator_var = estimator_var 
    def transform(self, X): 
     if self.name not in customEstimator.tmpVar: 
      customEstimator.tmpVar[self.name] = np.random.randn(estimator_var, estimator_var) 
     return np.hstack((customEstimator.tmpVar[self.name], X)) # this is just an example 
    def fit(self, X, y=None): 
     return self 
    def get_params(self, deep=False): 
     return {'estimator_var': self.estimator_var, 'name': self.name} 

이 방법은 있지만 scikit-에 의해 복제 된 경우 : 당신은의 라인 사이에 무언가에 의해 자동으로 생성되는 이름을 만들 수 있습니다 배우면 같은 이름 (결과적으로 데이터)을 공유하게됩니다.

+0

대단히 감사합니다! 하나의 질문 : __init__ 메소드가 매번 호출되기 때문에, 나는 그들이 다른 물리적 인 객체라고 가정한다. 그러나 Scickit은 GridSearchCV에서 동일한 매개 변수 집합을 사용하여 작업 할 때 __init__을 호출 할 때 같은 이름 변수를 사용할 것이라고 생각합니다. 그것이 맞을까요? – Bob

+0

customEstimator의 각 인스턴스는 다른 개체이지만 내 예제의 "tmpVars"는 ** 정적 **입니다. 즉, 모든 인스턴스에서 공유됩니다. 이것은 scikit-learn의 기능이 아닙니다. 정적 속성이 모든 프로그래밍 언어에서 일반적으로 작동하는 방식입니다. 그리고 예, 생각은 scikit-learn의 복제를 사용하면 동일한 이름을 가지게되고 동일한 메모리 부분을 검색 할 수있게하는 것입니다. – lejlot