python
import numpy as np
import torch
from datasets import load_dataset
from torch.utils.data import DataLoader
"""
GLUE の課題を Hugging Face datasets で読み込み、公式の指標で検証用の値を計算する
課題の名前:'cola' 'sst2' 'mrpc' 'qqp' 'stsb' 'mnli' 'qnli' 'rte' 'wnli'(診断用データは 'ax')
テスト用の正解は公開されていない(label に正しい値は入っていない)。テスト用の値は gluebenchmark.com に予測を送って得る
"""
TASK_KEYS = { # 課題ごとの入力の列名(1 文の課題は 2 つ目が None)
'cola': ('sentence', None), 'sst2': ('sentence', None),
'mrpc': ('sentence1', 'sentence2'), 'stsb': ('sentence1', 'sentence2'),
'qqp': ('question1', 'question2'), 'mnli': ('premise', 'hypothesis'),
'qnli': ('question', 'sentence'), 'rte': ('sentence1', 'sentence2'), 'wnli': ('sentence1', 'sentence2'),
}
ds = load_dataset('nyu-mll/glue', 'rte')
print(ds) # train 2490 / validation 277 / test 3000
print(ds['train'][0]) # {'sentence1': ..., 'sentence2': ..., 'label': 0 か 1, 'idx': ...}
# MNLI は検証用が 'validation_matched' と 'validation_mismatched' の 2 つに分かれている
def matthews_corr(pred, gold):
"""CoLA の指標。2 クラスの混同行列の 4 つの数から計算する(-1〜1、でたらめなら 0)"""
tp = np.sum((pred == 1) & (gold == 1)); tn = np.sum((pred == 0) & (gold == 0))
fp = np.sum((pred == 1) & (gold == 0)); fn = np.sum((pred == 0) & (gold == 1))
denom = np.sqrt(float((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)))
return 0.0 if denom == 0 else (tp * tn - fp * fn) / denom
def f1(pred, gold):
tp = np.sum((pred == 1) & (gold == 1))
precision = tp / max(np.sum(pred == 1), 1); recall = tp / max(np.sum(gold == 1), 1)
return 0.0 if precision + recall == 0 else 2 * precision * recall / (precision + recall)
def task_score(task, pred, gold):
"""課題の得点。指標が 2 つある課題は重みなしで平均する(GLUE スコアの計算と同じ)"""
if task == 'cola':
return matthews_corr(pred, gold)
if task in ('mrpc', 'qqp'):
return (np.mean(pred == gold) + f1(pred, gold)) / 2
if task == 'stsb': # 回帰:ピアソン相関とスピアマン相関の平均
from scipy.stats import pearsonr, spearmanr
return (pearsonr(pred, gold)[0] + spearmanr(pred, gold)[0]) / 2
return np.mean(pred == gold) # そのほかは正解率
# 検証用での評価(model は課題用の分類器、tokenizer は事前学習モデルのもの)
# model.eval() # Dropout を止める
# key1, key2 = TASK_KEYS['rte']
# preds, golds = [], []
# with torch.no_grad():
# for batch in DataLoader(ds['validation'], batch_size=32):
# enc = tokenizer(batch[key1], batch[key2], padding=True, truncation=True, return_tensors='pt')
# preds.append(model(**enc).logits.argmax(-1).numpy())
# golds.append(batch['label'].numpy())
# print('RTE 検証用の正解率', task_score('rte', np.concatenate(preds), np.concatenate(golds)))
# GLUE スコア = 9 課題の task_score(MNLI は一致・不一致の平均)の単純な平均。WNLI を含めたかどうかを必ず書く