서론
이미 검색창에 AutoML이라고 검색하면, 잘 만들어진 AutoML들이 많습니다
많은 프로그래밍들을 보고 의도와 구현 방식을 배우는 것이 목표입니다.
AutoSklearnClassifier Source
원본은 아래 공식 홈페이지에서 확인할 수 있습니다.
[AutoML] 구현을 향해, AutoSklearnClassifier-fit - 4편
AutoSklearnClassifier의 fit() 메서드부터 분석
AutoSklearn.fit()
class AutoSklearnClassifier(AutoSklearnEstimator, ClassifierMixin):
def fit(self, X, y,
X_test=None,
y_test=None,
feat_type=None,
dataset_name=None):
# step1
y = convert_if_sparse(y)
# step2
target_type = type_of_target(y)
# step3
supported_types = ['binary', 'multiclass', 'multilabel-indicator']
if target_type not in supported_types:
raise ValueError("Classification with data of type {} is "
"not supported. Supported types are {}. "
"You can find more information about scikit-learn "
"data types in: "
"https://scikit-learn.org/stable/modules/multiclass.html"
"".format(
target_type,
supported_types
)
)
self.target_type = target_type
# step4
super().fit(
X=X,
y=y,
X_test=X_test,
y_test=y_test,
feat_type=feat_type,
dataset_name=dataset_name,
)
self.classes_ = self.automl_.InputValidator.target_validator.classes_
return self
step1. convert_if_sparse
해당 메서드는 y(label)이 희소행렬(sparse matrix)이면, 밀집 행렬로 바꿔주는 메서드입니다.
from autosklearn.data.validation import convert_if_sparse
def convert_if_sparse(
y: typing.Union[SUPPORTED_TARGET_TYPES, spmatrix]
) -> SUPPORTED_TARGET_TYPES:
"""If the labels `y` are sparse, it will convert it to its dense representation
Parameters
"""
if issparse(y):
y = typing.cast(spmatrix, y)
y = y.toarray()
y = typing.cast(np.ndarray, y)
# For one dimensional data, toarray will return (1, nrows)
if y.shape[0] == 1:
y = y.flatten()
return y
typing.cast(spmatrix, y)
- 언뜻보면 y를 sparse matrix로 변환하는 함수 같지만 아님
- 파이썬 문서에는 다음과 같이 적혀있음
typing.cast(typ,val)
값을 형으로 변환합니다.
값을 변경하지 않고 반환합니다. 형 검사기에서는 반환 값이 지정된 형임을 나타내지만, 실행 시간에는 의도적으로 아무것도 확인하지 않습니다.
- 쉽게 말하면 런타임에서는 typing.cast는 실제로 아무것도 하지 않음
y.toarray()
- 사실상 typing.cast() 부분을 제거하면 toarray() 함수를 사용해 밀집 행렬로 변환하는 것을 확인할 수 있음
- 그 외에 다른 방법(matrix.A, matrix.todense())들도 존재
step 2. type_of_target
- 대상이 나타내는 데이터 유형을 결정함
from sklearn.utils.multiclass import type_of_target
# 예시
>>> type_of_target([0.1, 0.6])
'continuous'
>>> type_of_target([1, -1, -1, 1])
'binary'
>>> type_of_target(['a', 'b', 'a'])
'binary'
step3. check target_type
- y 데이터가 지원하지 않는 타입인 경우 에러를 발생 시킴
Step 4. fit
- AutosklearnEstimator의 fit 메서드를 사용하고 있음
- 자세한 건 다음 포스팅에서 다룰예정
결론
AutoSklearnClassifier클래스의 fit메서드는 y 데이터를 밀집 행렬로 변환하고, 지원하는 데이터인지 확인합니다.
그 후, AutosklearnEstimator를 서브 클래싱 하여 학습하게 됩니다.
'코드읽기 > auto-sklearn' 카테고리의 다른 글
[AutoML] 구현을 향해, AutoSklearnClassifeir.fit(2) - 5편 (0) | 2022.05.14 |
---|---|
[AutoML] 구현을 향해, AutoSklearn-parameters - 3편 (0) | 2022.05.05 |
[AutoML] 구현을 향해, sklearn-BaseEstimator? 2편 (0) | 2022.04.30 |
[AutoML]구현을 향해, AutoML? 그거 별거 없는거 아닌가? 1편 (0) | 2022.04.16 |