Recommendation System

Learning to Rank :: Pointwise, Pairwise, Listwise

Dan-k 2024. 9. 5. 10:00
반응형

Learning to Rank (LTR) 개요

  • 목적: LTR(Learning to Rank) 모델은 대량의 데이터를 처리하면서 제한된 공간에 가장 관련성이 높은 항목을 최상단에 배치하는 것에 중점을 둔다. 이는 검색 엔진, 온라인 쇼핑몰의 상품 추천 등에서 사용
  • 특징: LTR 모델은 정확한 예측 값보다 항목들의 상대적 순서를 최적화하는 데 집중
  • 적용 분야: 검색 엔진, 상품 추천 등

1. Pointwise LTR

  • 목적: 개별 항목의 특정 메트릭(예: 클릭 확률, 매출액 등)을 예측하여 순위를 매기는 것에 최적화.
  • 접근 방법:
    • 각 항목을 독립적으로 처리.
    • 항목별로 점수나 확률을 예측하고, 이 점수를 기준으로 정렬.
  • 대표 모델:
    • 로지스틱 회귀(Logistic Regression)
    • 서포트 벡터 머신(SVM)
  • 평가 방법: 일반적인 분류 또는 회귀 평가 지표(정확도, 정밀도, RMSE 등)를 사용. 특히 특정 위치 k에서의 성능을 평가 (예: top k 안에 관련 항목이 얼마나 포함되었는가).
  • 구현 코드 예시 (Logistic Regression):
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# 특징과 라벨 정의
X_train = [[0.1, 0.2], [0.4, 0.6], [0.7, 0.8]]
y_train = [0, 1, 1]

# 로지스틱 회귀 모델
model = LogisticRegression()
model.fit(X_train, y_train)

# 예측
predictions = model.predict(X_train)

# 평가
accuracy = accuracy_score(y_train, predictions)
print(f"Accuracy at position k: {accuracy}")

2. Pairwise LTR

  • 목적: 항목 쌍의 상대적 순서를 최적화.
  • 접근 방법:
    • 항목 쌍을 비교하여 더 중요한 항목이 상위에 위치하도록 학습.
    • 올바른 순서에 있을 때 손실 없음, 잘못된 순서일 때 손실 추가.
  • 대표 모델:
    • RankSVM: 서포트 벡터 머신(SVM) 모델의 개념을 활용하여 올바른 순서와 반대인 항목 쌍에 대해 페널티를 부여.
  • 평가 방법: Pairwise accuracy at position (정확한 순서의 항목 쌍 수 / 전체 항목 쌍 수).
  • 구현 코드 예시 (RankNet):
import tensorflow as tf
from tensorflow.keras import layers, Model
import numpy as np

# 샘플 데이터 생성 (특징 벡터와 레이블)
np.random.seed(42)
X_train = np.random.rand(100, 10)  # 100개의 샘플, 각 샘플은 10차원의 특징 벡터
y_train = np.random.randint(0, 2, size=(100,))  # 100개의 샘플에 대한 관련도 레이블 (0 또는 1)

# Pairwise 데이터 생성
def create_pairwise_data(X, y):
    X1, X2, y_diff = [], [], []
    for i in range(len(y)):
        for j in range(i + 1, len(y)):
            if y[i] != y[j]:
                X1.append(X[i])
                X2.append(X[j])
                y_diff.append(y[i] - y[j])
    return np.array(X1), np.array(X2), np.array(y_diff)

X1_train, X2_train, y_diff_train = create_pairwise_data(X_train, y_train)

# RankNet 모델 정의
def create_ranknet_model(input_shape):
    input_ = layers.Input(shape=input_shape)
    dense = layers.Dense(64, activation='relu')(input_)
    dense = layers.Dense(32, activation='relu')(dense)
    output = layers.Dense(1, activation='linear')(dense)
    return Model(inputs=input_, outputs=output)

# RankNet 모델 생성
ranknet = create_ranknet_model(X_train.shape[1])

# 손실 함수 정의
def ranknet_loss(y_true, y_pred):
    return tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_true, logits=y_pred))

# 모델 컴파일
ranknet.compile(optimizer='adam', loss=ranknet_loss)

# 학습 데이터 준비
input_1 = tf.convert_to_tensor(X1_train, dtype=tf.float32)
input_2 = tf.convert_to_tensor(X2_train, dtype=tf.float32)
y_train_diff = tf.convert_to_tensor(y_diff_train, dtype=tf.float32)

# 모델 학습
ranknet.fit([input_1, input_2], y_train_diff, epochs=10, batch_size=32)

3. Listwise LTR

  • 목적: 항목 전체의 순서를 최적화.
  • 접근 방법:
    • 개별 쌍이 아닌 전체 항목 리스트를 평가.
    • 주어진 항목 집합의 최적 순서를 찾는 것에 중점을 둠.
  • 대표 모델:
    • XGBoost: NDCG(Normalized Discounted Cumulative Gain)를 최적화.
  • 평가 방법: NDCG 등 리스트 전체의 성능을 평가하는 지표를 사용.
  • 구현 코드 예시 (XGBoost with NDCG):
import xgboost as xgb
from sklearn.metrics import ndcg_score

# 특징과 라벨 정의
X_train = [[0.1, 0.2], [0.4, 0.6], [0.3, 0.7]]
y_train = [3, 2, 1]  # 관련도 점수

# NDCG 최적화를 위한 XGBoost 모델
model = xgb.XGBRanker(objective='rank:ndcg')
model.fit(X_train, y_train)

# 예측
predictions = model.predict(X_train)

# 평가
ndcg = ndcg_score([y_train], [predictions])
print(f"NDCG score: {ndcg}")

요약

접근 방법목적대표 모델평가 지표

  목적 모델 평가지표
Pointwise 특정 메트릭 예측(예: 클릭 확률, 매출액) Logistic Regression, SVM Accuracy, Precision, RMSE
Pairwise 항목 쌍의 상대적 순서 최적화 RankSVM Pairwise Accuracy
Listwise 전체 항목 리스트의 순서 최적화 XGBoost (NDCG) NDCG, Listwise Accuracy
728x90
반응형
LIST