Evaluate 文档

结合自定义管道使用评估器

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

结合自定义管道使用评估器

评估器旨在与 transformer 管道开箱即用。然而,在许多情况下,你可能有一个不属于 transformer 生态系统的模型或管道。你仍然可以使用 evaluator 轻松地为它们计算指标。在本指南中,我们将展示如何为 Scikit-Learn pipeline 和 Spacy pipeline 执行此操作。让我们从 Scikit-Learn 的情况开始。

Scikit-Learn

首先,我们需要训练一个模型。我们将在 IMDb 数据集上训练一个简单的文本分类器,所以让我们先下载数据集。

from datasets import load_dataset

ds = load_dataset("imdb")

然后,我们可以构建一个简单的 TF-IDF 预处理器和一个包装在 Pipeline 中的朴素贝叶斯分类器。

from sklearn.pipeline import Pipeline
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer

text_clf = Pipeline([
        ('vect', CountVectorizer()),
        ('tfidf', TfidfTransformer()),
        ('clf', MultinomialNB()),
])

text_clf.fit(ds["train"]["text"], ds["train"]["label"])

遵循 transformersTextClassificationPipeline 中的约定,我们的管道应该是可调用的,并返回一个字典列表。此外,我们使用 task 属性来检查管道是否与 evaluator 兼容。为此,我们可以编写一个小的包装类。

class ScikitEvalPipeline:
    def __init__(self, pipeline):
        self.pipeline = pipeline
        self.task = "text-classification"

    def __call__(self, input_texts, **kwargs):
        return [{"label": p} for p in self.pipeline.predict(input_texts)]

pipe = ScikitEvalPipeline(text_clf)

我们现在可以将这个 pipeline 传递给 evaluator

from evaluate import evaluator

task_evaluator = evaluator("text-classification")
task_evaluator.compute(pipe, ds["test"], "accuracy")

>>> {'accuracy': 0.82956}

实现这个简单的包装器,就足以将任何框架的任何模型与 evaluator 一起使用。在 __call__ 方法中,你可以实现所有必要的逻辑,以高效地通过你的模型进行前向传播。

Spacy

我们将使用 spacytextblob 项目的 polarity 特性来获得一个简单的情感分析器。首先,你需要安装该项目并下载资源。

pip install spacytextblob
python -m textblob.download_corpora
python -m spacy download en_core_web_sm

然后,我们可以简单地加载 nlp 管道并添加 spacytextblob 管道。

import spacy

nlp = spacy.load('en_core_web_sm')
nlp.add_pipe('spacytextblob')

这个代码片段展示了我们如何使用通过 spacytextblob 添加的 polarity 特性来获取文本的情感。

texts = ["This movie is horrible", "This movie is awesome"]
results = nlp.pipe(texts)

for txt, res in zip(texts, results):
    print(f"{text} | Polarity: {res._.blob.polarity}")

现在,我们可以像前面的 Scikit-Learn 示例一样,将其包装在一个简单的包装类中。它只需要返回一个包含预测标签的字典列表。如果极性大于0,我们将预测为积极情绪,否则为消极情绪。

class SpacyEvalPipeline:
    def __init__(self, nlp):
        self.nlp = nlp
        self.task = "text-classification"

    def __call__(self, input_texts, **kwargs):
        results =[]
        for p in self.nlp.pipe(input_texts):
            if p._.blob.polarity>=0:
                results.append({"label": 1})
            else:
                results.append({"label": 0})
        return results

pipe = SpacyEvalPipeline(nlp)

该类与 evaluator 兼容,我们可以使用与前面示例相同的实例以及 IMDb 测试集。

eval.compute(pipe, ds["test"], "accuracy")
>>> {'accuracy': 0.6914}

这将比 Scikit-Learn 示例花费更长的时间,但在大约10-15分钟后,你将得到评估结果!

< > 在 GitHub 上更新