LTR 모델 배포

원본 보기

LTR 모델 배포

참고

이 기능은 8.12.0 버전에서 도입되었으며 특정 구독 등급에서만 사용할 수 있습니다. 자세한 내용은 Elastic 자체 관리형 구독을 참조하세요.

일반적으로 XGBoost 모델 학습 과정에서는 Pandas와 scikit-learn 같은 표준 Python 데이터 과학 도구를 사용합니다.

elasticsearch-labs 저장소에 예제 노트북이 준비되어 있습니다. 이 대화형 Python 노트북은 모델 학습부터 배포까지의 전체 워크플로를 상세히 설명합니다.

워크플로에는 eland를 사용하는 것을 적극 권장합니다. Elasticsearch에서 LTR을 다루는 데 필요한 핵심 기능을 제공하기 때문입니다. eland로 다음을 수행할 수 있습니다.

  • 특성 추출 구성
  • 학습용 특성 추출
  • Elasticsearch에 모델 배포

특성 추출기는 템플릿 쿼리로 정의합니다. Eland는 이러한 특성 추출기를 Python에서 직접 정의할 수 있도록 eland.ml.ltr.QueryFeatureExtractor를 제공합니다.

from eland.ml.ltr import QueryFeatureExtractor

feature_extractors=[
    # We want to use the BM25 score of the match query for the title field as a feature:
    QueryFeatureExtractor(
        feature_name="title_bm25",
        query={"match": {"title": "{{query}}"}}
    ),
    # We want to use the number of matched terms in the title field as a feature:
    QueryFeatureExtractor(
        feature_name="title_matched_term_count",
        query={
            "script_score": {
                "query": {"match": {"title": "{{query}}"}},
                "script": {"source": "return _termStats.matchedTermsCount();"},
            }
        },
    ),
    # We can use a script_score query to get the value
    # of the field rating directly as a feature:
    QueryFeatureExtractor(
        feature_name="popularity",
        query={
            "script_score": {
                "query": {"exists": {"field": "popularity"}},
                "script": {"source": "return doc['popularity'].value;"},
            }
        },
    ),
    # We extract the number of terms in the query as feature.
   QueryFeatureExtractor(
        feature_name="query_term_count",
        query={
            "script_score": {
                "query": {"match": {"title": "{{query}}"}},
                "script": {"source": "return _termStats.uniqueTermsCount();"},
            }
        },
    ),
]
		
특성으로서의 용어 통계

LTR 모델이 원시 용어 통계를 특성으로 활용하는 경우는 흔합니다. 이 정보를 추출하려면 script_score 쿼리의 일부로 제공되는 용어 통계 기능을 사용할 수 있습니다.

특성 추출기를 정의했다면 이후 학습 단계에서 사용할 수 있도록 eland.ml.ltr.LTRModelConfig 객체로 감쌉니다.

from eland.ml.ltr import LTRModelConfig

ltr_config = LTRModelConfig(feature_extractors)
		

데이터셋 구축은 학습 과정에서 매우 중요한 단계입니다. 관련 특성을 추출해 판정 목록에 추가하는 작업이 포함됩니다. 이 과정에는 Eland의 eland.ml.ltr.FeatureLogger 헬퍼 클래스를 사용할 것을 권장합니다.

from eland.ml.ltr import FeatureLogger

# Create a feature logger that will be used to query Elasticsearch to retrieve the features:
feature_logger = FeatureLogger(es_client, MOVIE_INDEX, ltr_config)
		

FeatureLogger는 extract_features 메서드를 제공하며, 이를 통해 판정 목록에 있는 특정 문서들의 특성을 추출할 수 있습니다. 동시에 앞서 정의한 특성 추출기에 쿼리 파라미터를 전달할 수 있습니다.

feature_logger.extract_features(
    query_params={"query": "foo"},
    doc_ids=["doc-1", "doc-2"]
)
		

예제 노트북에서는 FeatureLogger를 사용해 판정 목록에 특성을 추가함으로써 학습 데이터셋을 구축하는 방법을 설명합니다.

  • 특성 추출을 직접 구현하는 것은 강력히 권장하지 않습니다. 학습 환경과 Elasticsearch의 추론 사이에서 특성 추출의 일관성을 유지하는 것이 매우 중요합니다. Elasticsearch와 함께 개발되고 테스트되는 eland 도구를 사용하면 양쪽이 일관되게 동작하도록 보장할 수 있습니다.
  • 특성 추출은 Elasticsearch 서버에서 쿼리를 실행하는 방식으로 수행됩니다. 판정 목록에 예시가 많거나 특성 수가 많은 경우 클러스터에 큰 부하를 줄 수 있습니다. 이 특성 로거 구현은 서버로 전송되는 검색 요청 수를 최소화하고 부하를 줄이도록 설계되었습니다. 다만 사용자에게 노출되는 프로덕션 트래픽과 격리된 Elasticsearch 클러스터에서 학습 데이터셋을 구축하는 것이 가장 좋습니다.

모델 학습이 끝나면 Elasticsearch 클러스터에 배포할 수 있습니다. Eland의 MLModel.import_ltr_model method를 사용하면 됩니다.

from eland.ml import MLModel

LEARNING_TO_RANK_MODEL_ID="ltr-model-xgboost"

MLModel.import_ltr_model(
    es_client=es_client,
    model=ranker,
    model_id=LEARNING_TO_RANK_MODEL_ID,
    ltr_model_config=ltr_config,
    es_if_exists="replace",
)
		

이 메서드는 학습된 모델과 Learning To Rank 구성(특성 추출 포함)을 Elasticsearch가 이해할 수 있는 형식으로 직렬화합니다. 그런 다음 Create Trained Models API를 사용해 모델을 Elasticsearch에 배포합니다.

현재 Elasticsearch의 LTR에서 지원하는 모델 유형은 다음과 같습니다.

앞으로 더 많은 모델 유형이 지원될 예정입니다.

모델을 Elasticsearch에 배포한 뒤에는 학습된 모델 API로 관리할 수 있습니다. 이제 검색 시점에 LTR 모델을 리스코어러로 사용할 준비가 되었습니다.