学习huggingface evaluate 库, 用于获取各种计算指标的库. 例如 accuracy, f1, 以及其他常用指标等.
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 import evaluatemetric = evaluate.load("accuracy" ) result: {"accuracy" : float } = metric.compute(references: list = ..., predictions: list = ...) predictions: list = ... references: list = ... for pred, reference in zip (predictions, references): metric.add(pred, reference) result: {"accuracy" : float } = metric.compute() predictions: list [list ] = ... references: list [list ] = ... for preds, refers in zip (predictions, references): metric.add_batch(preds, refers) result: {"accuracy" : float } = metric.compute() for inputs, labels in evaluation_dataset: predictions = model(inputs) metric.add_batch(references=labels, predictions=predictions) result: {"accuracy" : float } = metric.compute()
使用 load 方法返回了一个对象, 其中暴露了 compute() 方法用于计算指标. 有两种方式传入数据
当作函数使用: 直接将标签与预测分别使用 references 和 predictions 传入方法
当作对象方法使用: 使用 add() , add_batch() 方法传入数据, 然后调用前一个方法来计算.
猜测实现
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 import numpy as npdef load (metric_name ): return MetricFactory.build(metric_name) class MetricFactory (): def __init__ (self ): pass def build (self, metric_name ): ... return Metric() class Metric (): def __init__ (self ): self .references = [] self .predictions = [] def compute (self, references = null, predictions = null ): if references is None : references = self .references if predictions is None : predictions = predictions ... return res def add (self, references: list , predictions: list ): self .references = references self .predictions = predictions def add_batch (self, references: list [list ], predictions: list [list ] ): self .references = np.array(references).flatten().item() self .predictions = np.array(predictions).flatten().item()
huggingface 中的 Tokenizer 对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 from transformers import AutoTokenizerfrom typing import Union tokenizer = AutoTokenizer.from_pretrained("bert-base" ) sentences: str | list [str ] = ... ids: list [int ] = tokenizer.encode(sentences) encoded_inputs = tokenizer(sentences) encoded_inputs: { "input_ids" : list [int ] | list [list [int ]], "token_type_ids" : list [int ] | list [list [int ]], "attention_mask" : list [int ] | list [list [int ]] } tokens: str = tokenzier.decode(token_ids: list [int ])