Spaces:
Sleeping
Sleeping
File size: 2,904 Bytes
7df4497 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | # -*- 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 |