본문 바로가기

dev_AI_framework

sklearn : _rescale_data ( sparse_matrix, inplace )

def _rescale_data(X, y, sample_weight, inplace=False):
    """Rescale data sample-wise by square root of sample_weight.

    For many linear models, this enables easy support for sample_weight because

        (y - X w)' S (y - X w)

    with S = diag(sample_weight) becomes

        ||y_rescaled - X_rescaled w||_2^2

    when setting

        y_rescaled = sqrt(S) y
        X_rescaled = sqrt(S) X

    Returns
    -------
    X_rescaled : {array-like, sparse matrix}

    y_rescaled : {array-like, sparse matrix}
    """
    # Assume that _validate_data and _check_sample_weight have been called by
    # the caller.
    xp, _ = get_namespace(X, y, sample_weight)
    n_samples = X.shape[0]
    sample_weight_sqrt = xp.sqrt(sample_weight)

    if sp.issparse(X) or sp.issparse(y):
        sw_matrix = sparse.dia_matrix(
            (sample_weight_sqrt, 0), shape=(n_samples, n_samples)
        )

    if sp.issparse(X):
        X = safe_sparse_dot(sw_matrix, X)
    else:
        if inplace:
            X *= sample_weight_sqrt[:, None]
        else:
            X = X * sample_weight_sqrt[:, None]

    if sp.issparse(y):
        y = safe_sparse_dot(sw_matrix, y)
    else:
        if inplace:
            if y.ndim == 1:
                y *= sample_weight_sqrt
            else:
                y *= sample_weight_sqrt[:, None]
        else:
            if y.ndim == 1:
                y = y * sample_weight_sqrt
            else:
                y = y * sample_weight_sqrt[:, None]
    return X, y, sample_weight_sqrt

_rescale_data

입력 데이터 X 와 타겟값 y 를 샘플 가중치에 따라 재조정하는 역할을 한다. 샘플 가중치의 제곱근을 사용하여 데이터 조정

파라미터

  • X : 입력 데이터
  • y :  타겟 데이터
  • sample_weight : 각 샘플에 대한 가중치
  • inplace : 원본 데이터 수정 여부

 

코드

  • get_namespace : 네임스페이스 결정
  • n_sampels : 샘플 개수
  • sample_weight_sqrt : 샘플 가중치의 제곱을 계산, 각 샘플에 대해 가중치 적용 시 사용

 

  • if sp.issparse(X) or sp.issparse(y)
    • 희소 행렬의 경우 샘플 가중치의 제곱근을 대각 요소로 가지는 희소 행렬을 생성한다. 
  • if sp.issparse(X)
    • x 가 희소 행렬인 경우 sw_matrix 와 X 를 행렬 곱하여 가중치 적용
  • else:
    • 밀집 행렬의 경우 sample_weight_sqrt 를 통해 각 샘플에 가중치를 곱한다.
  • y 도 동일한 방법 수행

 

rescale 된 데이터 획득 가능