# -*- coding: utf-8 -*- """ 공통 유틸리티 함수 및 평가 지표 계산 """ import numpy as np import random import torch from sklearn.metrics import accuracy_score, f1_score, mean_squared_error, mean_absolute_error # 피어슨 상관계수를 위해 scipy 임포트 try: from scipy.stats import pearsonr except ImportError: print("Warning: scipy not installed. Pearson correlation metrics will be skipped.") pearsonr = None # --- 시드 고정 --- def seed_everything(seed: int): """모든 난수 생성을 고정하여 재현성 확보""" random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # --- 분류 모델 (Classification) 평가 지표 --- def compute_cls_metrics(p): """ 분류 모델 평가 지표 계산 (Accuracy, F1-Macro) p: (predictions, labels) 튜플 """ predictions, labels = p predictions = np.argmax(predictions, axis=1) accuracy = accuracy_score(labels, predictions) f1_macro = f1_score(labels, predictions, average="macro", zero_division=0) return { "accuracy": accuracy, "f1_macro": f1_macro, } # --- 회귀 모델 (Regression) 평가 지표 --- def compute_reg_metrics(p): """ 회귀 모델 평가 지표 계산 (RMSE, Pearson R) p: (predictions, labels) 튜플. predictions/labels는 (N, 2) 형태 (Valence, Arousal) """ preds, labels = p # 1. MSE 계산 (squared=False 인수를 제거하여 최신 scikit-learn 호환성 문제 해결) mse_v = mean_squared_error(labels[:, 0], preds[:, 0]) mse_a = mean_squared_error(labels[:, 1], preds[:, 1]) # 2. RMSE 계산 (루트 씌우기) rmse_v = np.sqrt(mse_v) rmse_a = np.sqrt(mse_a) # 3. 전체 평균 RMSE rmse_mean = (rmse_v + rmse_a) / 2 metrics = { "rmse_mean": rmse_mean, "rmse_valence": rmse_v, "rmse_arousal": rmse_a, "mae_valence": mean_absolute_error(labels[:, 0], preds[:, 0]), "mae_arousal": mean_absolute_error(labels[:, 1], preds[:, 1]), } # 4. Pearson 상관 계수 계산 (활성화 및 Scipy 설치 확인) if pearsonr: try: v_corr, _ = pearsonr(labels[:, 0], preds[:, 0]) a_corr, _ = pearsonr(labels[:, 1], preds[:, 1]) pearson_mean = (v_corr + a_corr) / 2 metrics["pearson_mean"] = pearson_mean metrics["pearson_valence"] = v_corr metrics["pearson_arousal"] = a_corr except ValueError as e: # 라벨이나 예측값이 상수일 경우 (e.g. [0, 0, 0]) pearsonr 계산 시 오류 발생 print(f"Warning: Could not compute Pearson correlation. {e}") metrics["pearson_mean"] = 0.0 return metrics