본문 바로가기

dev_AI_framework

sklearn : _validate_date ( 데이터 검증 )

BaseEstimator 클래스의 _validate_date,

파라미터

 """
 X : {array-like, sparse matrix, dataframe} of shape \
                (n_samples, n_features), default='no validation'
            The input samples.
            If 'no_validation', no validation is performed on X. This is
            useful for meta-estimator which can delegate input validation to
            their underlying estimator(s). In that case y must be passed and
            the only accepted check_params are multi_output and
            y_numeric.
"""​

X

  • array-like : 리스트, 넘파이 배열 등 배열처럼 사용할 수 있는 데이터 구조
  • sparse matrix, 희소 행렬
  • dataframe : 판다스 데이터 프레임
  •  
  • (샘플 수, 특성 수) 의 크기
  •  
  • 기본값은 no_validation, X 에 대한 유효성 검사는 수행되지 않는다. 이러한 기본값은 유효성 검사를 생략하려는 의도
  • 허용된 check_params 
    • multi_output : 다중 출력이 필요한 경우를 처리하기 위해 사용
    • y_numericc : y 가 숫자형 데이터를 포함해야 함을 지정, 
더보기

메타 추정기와 하위 추정기, 유효성 검사

 

메타 추정기 meta-estimator : 다른 추정기(모델)를 포함하거나 이를 조합하여 사용하며, 이들을 제어하고 결과를 처리하는 상위 수준의 추정기, ex) Pipeline, GridSearchCV, RandomForestClassifier

하위 추정기 underlying estimator : 메타 추정기 내에서 실제로 데이터를 학습하고 예측을 수행하는 개별적인 추정기들, ex) Pipeline 안에 포함된 standardScaler, LinearRegression

 

유효성 검사

validation 은 데이터가 특정 요구 사항을 충족하는지 확인하는 과정

  • 데이터 형식 확인 
  • 차원 확인
  • 값 범위 확인

 

하위 추정기에서의 유효성 검사

하위 추정기(LinearRegression 은 일반적으로 입력 데이터와 타겟 값에 대해 자체적으로 유효성 검사를 수행한다. 

 

메타 추정기에서의 유효성 검사

메타 추정기는 여러 하위 추정기를 포함하나 이들을 조합하여 사용하는 상위 개념의 추정기, 유효성 검사의 작업을 하위 추정기에게 위임할 때도 있음,

 

"""
y : array-like of shape (n_samples,), default='no_validation'
            The targets.

            - If `None`, `check_array` is called on `X`. If the estimator's
              requires_y tag is True, then an error will be raised.
            - If `'no_validation'`, `check_array` is called on `X` and the
              estimator's requires_y tag is ignored. This is a default
              placeholder and is never meant to be explicitly set. In that case
              `X` must be passed.
            - Otherwise, only `y` with `_check_y` or both `X` and `y` are
              checked with either `check_array` or `check_X_y` depending on
              `validate_separately`.
"""

y

  • array-like 형태, 크기는 n_samples 이다. 입력 데이터 x 와 동일한 샘플 수를 의미
  • 특정 조건에 따라 y 의 검증 여부가 결정된다.
  • y 가 None 인 경우
    • x 에 대해서만 check_array 가 호출된다. y 에 대한 검증이 수행되지 않음 
    • 그러나 특정 추정기에서는 y 가 반드시 필요, 이 경우 오류가 발생
      • y 가 none 이고 추정기가 y 를 필요로 할 경우 오류가 발생
  • y 가 no_validation 인 경우
    • x 에 대해서만 check_array 가 호출, y 는 미검증
  • y 가 None 도 아니고 no_validation 도 아닌 경우, y 는 _check_y 로 검증된다. 

 

"""
reset : bool, default=True
            Whether to reset the `n_features_in_` attribute.
            If False, the input will be checked for consistency with data
            provided when reset was last True.
            .. note::
               It is recommended to call reset=True in `fit` and in the first
               call to `partial_fit`. All other methods that validate `X`
               should set `reset=False`.
"""

reset

입력 데이터의 특성 수를 설정하거나 유지하는 역할을 한다. 

  • n_features_in_ :  속성을 재설정할지 여부를 결정, 이는 입력 데이터 x 의 특성 수를 추적하는 속성, 
  • reset = True 인 경우, 이 속성이 현재 데이터에 맞게 재설정된다. fit 메서드에서 사용된다.
    • reset = True 일 경우
      • 초기화 
        • n_feature_in_ 속성이 현재 입력 데이터 x 에 맞게 초기화된다.
        • 이는 주로 fit 메서드에서 사용, 보통 모델을 처음 학습시킬 때 호출되므로 이 시점에서 특성 수를 초기화하는 것이 중요
    • reset = False 일 경우
      • 일관성 검사
        • 이전에 설정된 n_feature_in_ 속성과 현재 입력된 데이터의 특성 수를 비교하여 일관성의 확인
        • 모델이 학습된 이후에 제공된 데이터가 학습 시 사용된 데이터와 같은 특성 수를 가지는지 검증한다.
  • 권장 사항
    • reset = True
      • fit, partial_fit 의 경우 reset = True 가 권장, (당연한 이치)
    • reset = False
      • predict, transform 의 경우 False 가 권장 ,기존 학습 데이터와 새로운 데이터의 일관성 확인을 위해 필요

 

"""
        validate_separately : False or tuple of dicts, default=False
            Only used if y is not None.
            If False, call validate_X_y(). Else, it must be a tuple of kwargs
            to be used for calling check_array() on X and y respectively.

            `estimator=self` is automatically added to these dicts to generate
            more informative error message in case of invalid input data.

"""

validate_separately

x 와 y 의 유효성 검사를 어떻게 수행할지를 결정하는 역할을 한다. y 가 None 이 아닌 경우에만 사용, X, y 를 함께 혹은 별도로 검증할지를 결정한다.

유효성 검사 세부 제어 파랄미터, X, y 를 개별적으로 처리해야 하는 경우 유용

  • False (default)
    • x, y 를 함께 검증
    • validate_X_y() 함수의 호출, 일관성을 동시에 확인한다.
    • x, y 가 서로 일치하는지 확인하고 함께 처리되는 데이터인 경우에 유용
  • tuple of dicts
    • validate_separately 가 False 가 아닌 튜플로 설정된 경우 X, y 를 별도로 검증한다.
    • 튜플의 첫 번째 딕셔너리는 x 에 대한 검증 파라미터를, 두 번째 딕셔너리는 y 에 대한 검증 파라미터를 포함한다.
    • 각각의 딕셔너리에는 check_array() 함수에 전달될 추가 파람리터들이 포함, 이를 통해 X, y 를 개별적으로 검증할 때 더 세부적인 제어가 가능, ( 데이터 타입 등등? )
"""
        cast_to_ndarray : bool, default=True
            Cast `X` and `y` to ndarray with checks in `check_params`. If
            `False`, `X` and `y` are unchanged and only `feature_names_in_` and
            `n_features_in_` are checked.
"""​

cast_to_ndarray

입력 데이터 X, 타겟 값 y 를 numpy 의 ndarray 형식으로 변환할지 여부를 제어한다. 데이터 유효성을 검사하고, 필요한 경우 형식을 유지할 수 있다.

  • True (default)
    • 변환 수행 : X, y 가 numpy 의 ndarray 형식으로 변환
    • 유효성 검사 : check_params 에 지정된 추가 검사 수행, 
    • 데이터를 일관되게 처리하고, 이후 계산에서 오류가 발생하지 않도록 보장하기 위해 사용
  • False 
    • 변환의 미수행 : X, y 의 원래 데이터 형식이 유지된다. 
    • x, y 에 대한 추가적인 변환이나 검사는 수행되지 않고, 단지 feature_name_in_, n_feature_in_ 속성만 확인

 

"""
       **check_params : kwargs
            Parameters passed to :func:`sklearn.utils.check_array` or
            :func:`sklearn.utils.check_X_y`. Ignored if validate_separately
            is not False.

            `estimator=self` is automatically added to these params to generate
            more informative error message in case of invalid input data.
"""

**check_params

가변 키워드 인자 kwargs, 입력 데이터, X 와 타겟 값, y 에 대한 유효성 검사를 수행할 때 사용되는 추가적인 파라미터들을 전달하는 데 사용된다. 

  • 동작 방식
    • 파라미터 전달
      • 전달된 모든 키워드 인자는 check_array, check_X_y 함수에 전달되어, 데이터 검사의 세부 사항을 설정한다.
    • 자동 추가되는 estimator = self
      • 오류 발생 시 어느 추정기에서 오류가 발생했는지 명확하게 알리기 위해 사용된다.

 

self._validate_data 끝