Lighteval 文档

添加新指标

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

添加新指标

首先,检查您是否可以使用 语料库指标样本指标 中的参数化函数之一。

如果不是,您可以使用 custom_task 系统来注册您的新指标

要查看与自定义任务一起添加的自定义指标示例,请查看 IFEval 自定义任务

要将您的自定义指标贡献给 lighteval 仓库,您首先需要通过运行 pip install -e .[dev] 安装所需的开发依赖项,然后运行 pre-commit install 以安装 pre-commit 钩子。

  • 创建一个新的 Python 文件,其中应包含您的指标的完整逻辑。
  • 该文件还需要以这些导入开始
from aenum import extend_enum
from lighteval.metrics import Metrics

您需要定义一个样本级别指标

def custom_metric(predictions: list[str], formatted_doc: Doc, **kwargs) -> bool:
    response = predictions[0]
    return response == formatted_doc.choices[formatted_doc.gold_index]

这里样本级别指标仅返回一个指标,如果您想为每个样本返回多个指标,则需要返回一个字典,其中指标作为键,值作为值。

def custom_metric(predictions: list[str], formatted_doc: Doc, **kwargs) -> dict:
    response = predictions[0]
    return {"accuracy": response == formatted_doc.choices[formatted_doc.gold_index], "other_metric": 0.5}

然后,如果需要,您可以定义一个聚合函数,常见的聚合函数是 np.mean

def agg_function(items):
    flat_items = [item for sublist in items for item in sublist]
    score = sum(flat_items) / len(flat_items)
    return score

最后,您可以定义您的指标。如果它是样本级别指标,您可以使用以下代码和 SampleLevelMetric

my_custom_metric = SampleLevelMetric(
    metric_name={custom_metric_name},
    higher_is_better={either True or False},
    category={MetricCategory},
    use_case={MetricUseCase},
    sample_level_fn=custom_metric,
    corpus_level_fn=agg_function,
)

如果您的指标为每个样本定义了多个指标,您可以使用以下代码和 SampleLevelMetricGrouping

custom_metric = SampleLevelMetricGrouping(
    metric_name={submetric_names},
    higher_is_better={n: {True or False} for n in submetric_names},
    category={MetricCategory},
    use_case={MetricUseCase},
    sample_level_fn=custom_metric,
    corpus_level_fn={
        "accuracy": np.mean,
        "other_metric": agg_function,
    },
)

最后,添加以下内容,以便在作为模块加载时将您的指标添加到我们的指标列表中。

# Adds the metric to the metric list!
extend_enum(Metrics, "metric_name", metric_function)
if __name__ == "__main__":
    print("Imported metric")

然后,您可以通过在使用 --custom-tasks path_to_your_file 启动 lighteval 时给出您的自定义指标。

< > 在 GitHub 上更新