mlflow.metrics
mlflow.metrics 模块可帮助你对模型进行定量和定性评估。
- class mlflow.metrics.EvaluationMetric(eval_fn, name, greater_is_better, long_name=None, version=None, metric_details=None, metric_metadata=None, genai_metric_args=None)[source]
一个评估指标。
- Parameters
eval_fn –
一个计算指标的函数,具有以下签名:
def eval_fn( predictions: pandas.Series, targets: pandas.Series, metrics: Dict[str, MetricValue], **kwargs, ) -> Union[float, MetricValue]: """ 参数: predictions: 一个 pandas Series,包含模型生成的预测值。 targets:(可选)一个 pandas Series,包含对应于该输入的预测的标签。 metrics:(可选)一个字典,包含由默认评估器计算的指标。键是指标的名称,值是指标的数值。要访问系统计算的指标的 MetricValue,确保为此参数指定类型提示为 Dict[str, MetricValue]。参阅 DefaultEvaluator 行为部分以了解根据模型类型(即分类器或回归器)将返回哪些指标。 kwargs: 包含用于计算指标的一系列参数。这些参数可以是来自输入数据、模型输出、其他指标的信息,或在 `evaluator_config` 参数中为 `mlflow.evaluate` API 指定的参数。 返回:包含每行得分、每行理由和汇总结果的 MetricValue。 """ ...
name – 指标的名称。
greater_is_better – 指标的值越大是否更好。
long_name – (Optional) The long name of the metric. For example,
"root_mean_squared_error"for"mse".version – (可选)指标的版本。例如
v1.metric_details – (可选) 对该度量的描述以及其计算方式。
metric_metadata – (可选) 一个包含该指标元数据的字典。
genai_metric_args – (可选)一个字典,包含用户在调用 make_genai_metric 或 make_genai_metric_from_prompt 时指定的参数。这些参数会被持久化,以便我们以后能够反序列化出相同的 metric 对象。
这些 EvaluationMetric 被 mlflow.evaluate() API 使用,要么根据 model_type 自动计算,要么通过 extra_metrics 参数 指定。
下面的代码演示了如何使用 mlflow.evaluate() 与 EvaluationMetric 一起。
import mlflow
from mlflow.metrics.genai import EvaluationExample, answer_similarity
eval_df = pd.DataFrame(
{
"inputs": [
"What is MLflow?",
],
"ground_truth": [
"MLflow is an open-source platform for managing the end-to-end machine learning lifecycle. It was developed by Databricks, a company that specializes in big data and machine learning solutions. MLflow is designed to address the challenges that data scientists and machine learning engineers face when developing, training, and deploying machine learning models.",
],
}
)
example = EvaluationExample(
input="What is MLflow?",
output="MLflow is an open-source platform for managing machine "
"learning workflows, including experiment tracking, model packaging, "
"versioning, and deployment, simplifying the ML lifecycle.",
score=4,
justification="The definition effectively explains what MLflow is "
"its purpose, and its developer. It could be more concise for a 5-score.",
grading_context={
"ground_truth": "MLflow is an open-source platform for managing "
"the end-to-end machine learning (ML) lifecycle. It was developed by Databricks, "
"a company that specializes in big data and machine learning solutions. MLflow is "
"designed to address the challenges that data scientists and machine learning "
"engineers face when developing, training, and deploying machine learning models."
},
)
answer_similarity_metric = answer_similarity(examples=[example])
results = mlflow.evaluate(
logged_model.model_uri,
eval_df,
targets="ground_truth",
model_type="question-answering",
extra_metrics=[answer_similarity_metric],
)
有关如何计算 EvaluationMetric 的信息,例如用于评分的提示,可通过 metric_details 属性获得。
import mlflow
from mlflow.metrics.genai import relevance
my_relevance_metric = relevance()
print(my_relevance_metric.metric_details)
评估结果存储为 MetricValue。汇总结果作为指标记录到 MLflow 运行中,而逐例结果以评估表格的形式作为工件记录到 MLflow 运行中。
- class mlflow.metrics.MetricValue(scores: Optional[Union[list[str], list[float]]] = None, justifications: Optional[list[str]] = None, aggregate_results: Optional[dict[str, float]] = None)[source]
指标的值。
- Parameters
scores – 每行的度量值
justifications – 对相应分数的说明(如适用)
aggregate_results – 一个字典,将聚合的名称映射到其值
我们提供以下内置工厂函数来创建 EvaluationMetric 用于评估模型。这些指标会根据 model_type 自动计算。有关 model_type 参数的更多信息,请参见 mlflow.evaluate() API。
回归器指标
- mlflow.metrics.mae() mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建用于评估 mae 的指标。
该指标计算用于回归的平均绝对误差的聚合得分。
- mlflow.metrics.mape() mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建一个用于评估 mape 的指标。
该指标计算回归问题中平均绝对百分比误差的聚合得分。
- mlflow.metrics.max_error() mlflow.models.evaluation.base.EvaluationMetric[source]
This function will create a metric for evaluating max_error.
该度量计算回归中最大残差的聚合得分。
- mlflow.metrics.mse() mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建一个用于评估 mse 的指标。
该指标计算回归任务中均方误差的聚合得分。
- mlflow.metrics.rmse() mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建一个用于评估 mse 的平方根的指标。
该指标计算回归问题的根平均绝对误差的聚合得分。
- mlflow.metrics.r2_score() mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建一个用于评估r2_score的指标。
该指标计算决定系数的汇总得分。R2 的取值范围从负无穷大到 1,用于衡量回归中预测变量解释的方差百分比。
分类器指标
- mlflow.metrics.precision_score() mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将为分类创建一个用于评估 precision 的指标。
该指标计算分类任务的精确率的聚合得分,介于0和1之间。
- mlflow.metrics.recall_score() mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建一个用于评估分类中recall的指标。
该指标为分类任务的召回率计算一个介于0和1之间的聚合得分。
- mlflow.metrics.f1_score() mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建一个用于评估二元分类中 f1_score 的指标。
此度量计算分类任务的 F1 score (F-measure) 的聚合得分,范围在 0 到 1 之间。F1 score 定义为 2 * (precision * recall) / (precision + recall)。
文本指标
- mlflow.metrics.ari_grade_level() mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建一个用于计算 automated readability index 的指标,使用 textstat。
该指标输出一个数字,用于近似表示理解该文本所需的年级水平,通常大约在0到15之间(但不限于此范围)。
- Aggregations calculated for this metric:
平均值
- mlflow.metrics.flesch_kincaid_grade_level() mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建一个用于计算 flesch kincaid grade level 的指标,使用 textstat。
该指标输出一个数字,近似表示理解该文本所需的年级水平,通常大约在0到15之间(但不限于此范围)。
- Aggregations calculated for this metric:
平均值
问答评估指标
包含上述所有 文本指标 以及以下内容:
- mlflow.metrics.exact_match() mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建一个用于使用 sklearn 计算 accuracy 的指标。
该指标仅计算一个取值范围为 0 到 1 的聚合得分。
- mlflow.metrics.rouge1() mlflow.models.evaluation.base.EvaluationMetric[source]
这个函数将创建一个用于评估 rouge1 的指标。
分数范围为0到1,分数越高表示相似度越高。 rouge1 使用基于一元(unigram)的评分来计算相似度。
- Aggregations calculated for this metric:
平均值
- mlflow.metrics.rouge2() mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建用于评估 rouge2 的指标。
得分范围从0到1,得分越高表示相似度越高。rouge2 使用基于二元(bigram)的评分来计算相似度。
- Aggregations calculated for this metric:
平均值
- mlflow.metrics.rougeL() mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建一个用于评估 rougeL 的指标。
得分范围从0到1,分数越高表示相似度越高。 rougeL 使用基于一元(unigram)的评分来计算相似度。
- Aggregations calculated for this metric:
均值
- mlflow.metrics.rougeLsum() mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建一个用于评估 rougeLsum 的指标。
得分范围为 0 到 1,分数越高表示相似度越高。 rougeLsum 使用基于最长公共子序列的评分来计算相似度。
- Aggregations calculated for this metric:
平均值
- mlflow.metrics.toxicity() mlflow.models.evaluation.base.EvaluationMetric[source]
该函数将为评估toxicity创建一个指标,使用的模型为roberta-hate-speech-dynabench-r4,该模型将“仇恨”定义为“针对特定群体特征(例如族裔出身、宗教、性别或性取向)的辱骂性言论”。
得分范围从0到1,越接近1表示越有毒。将文本视为“toxic”的默认阈值为0.5。
- Aggregations calculated for this metric:
有毒输入文本的比例
- mlflow.metrics.token_count(encoding: str = 'cl100k_base') mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建一个用于计算 token_count 的指标。令牌数量使用 tiktoken 的 cl100k_base 分词器进行计算。
注意:对于隔离网络环境,您可以设置 TIKTOKEN_CACHE_DIR 环境变量来为 tiktoken 指定本地缓存目录,以避免下载分词器文件。
- mlflow.metrics.latency() mlflow.models.evaluation.base.EvaluationMetric[source]
该函数将创建一个用于计算延迟的度量。延迟由为给定输入生成预测所需的时间决定。请注意,计算延迟需要对每一行按顺序进行预测,这可能会减慢评估过程。
- mlflow.metrics.bleu() mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建用于评估bleu的指标。
BLEU分数范围从0到1,分数越高表示与参考文本越相似。BLEU考虑n-gram精确度和长度惩罚。虽然增加更多参考文本可以提升分数,但完美的分数很罕见,而且对有效评估并非必要。
- Aggregations calculated for this metric:
平均值
方差
第90百分位
检索器指标
以下指标是针对 'retriever' 模型类型的内置指标,这意味着它们会使用默认的 retriever_k 值 3 自动计算。
要评估文档检索模型,建议使用包含以下列的数据集:
输入查询
已检索到相关文档 ID
真实文档 ID
或者,你也可以通过 model 参数提供一个函数来表示你的检索模型。该函数应接受一个包含输入查询和 ground-truth 相关的 doc IDs 的 Pandas DataFrame,并返回一个带有检索到的相关 doc IDs 列的 DataFrame。
“文档 ID”是唯一标识文档的字符串或整数。检索到的和真实的文档 ID 列的每一行应由文档 ID 的列表或 numpy 数组组成。
参数:
targets:一个字符串,指定真实相关文档 ID 的列名predictions: 一个字符串,指定在静态数据集或由model函数返回的 Dataframe 中检索到的相关文档 ID 的列名retriever_k: 一个正整数,指定针对每个输入查询要考虑的检索到的文档 ID 的数量。retriever_k默认值为 3。您可以通过使用mlflow.evaluate()API 来更改:# 使用模型并使用 `evaluator_config` mlflow.evaluate( model=retriever_function, data=data, targets="ground_truth", model_type="retriever", evaluators="default", evaluator_config={"retriever_k": 5} )
# 使用静态数据集并使用 `extra_metrics` mlflow.evaluate( data=data, predictions="predictions_param", targets="targets_param", model_type="retriever", extra_metrics = [ mlflow.metrics.precision_at_k(5), mlflow.metrics.precision_at_k(6), mlflow.metrics.recall_at_k(5), mlflow.metrics.ndcg_at_k(5) ] )
注意:在第二种方法中,建议也省略
model_type,否则precision@3和recall@3将会被计算,除此之外还会计算precision@5、precision@6、recall@5和ndcg_at_k@5。
- mlflow.metrics.precision_at_k(k) mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将为检索模型创建一个用于计算
precision_at_k的指标。该度量为每一行计算一个介于0和1之间的分数,表示在给定的
k值下检索模型的精确率。如果未检索到任何相关文档,则得分为0,表示未检索到相关文档。让x = min(k, # of retrieved doc IDs)。那么,在其他情况下,k 时的精确率按如下方式计算:precision_at_k=(在排名前x的检索结果中相关的文档 ID 数)/x。
- mlflow.metrics.recall_at_k(k) mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将为检索器模型创建一个用于计算
recall_at_k的指标。该指标为每一行计算一个介于 0 到 1 之间的分数,表示检索器模型在给定
k值处的召回能力。如果未提供真实文档 ID 且未检索到任何文档,则得分为 1。然而,如果未提供真实文档 ID 且检索到了文档,则得分为 0。在所有其他情况下,k 处的召回按如下方式计算:recall_at_k= (# 在排名前k的文档中检索到的唯一相关文档 ID 的数量) / (# 真实标注的文档 ID 的数量)
- mlflow.metrics.ndcg_at_k(k) mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将为检索器模型创建用于评估 NDCG@k 的指标。
NDCG 分数能够处理非二元的相关性概念。然而,为了简单起见,我们在此使用二元相关性。真实标注(ground truth)中文档的相关性分数为 1,而非真实标注文档的相关性分数为 0。
NDCG 得分使用 sklearn.metrics.ndcg_score 计算,在 sklearn 实现的基础上处理以下边缘情况:
如果未提供真实文档 ID 且未检索到任何文档,则得分为 1。
如果没有提供真实文档 ID 且检索到了文档,则得分为 0。
如果提供了真实标注的文档 ID 且未检索到任何文档,则得分为 0。
如果检索到重复的文档 ID 且这些重复的文档 ID 出现在真实标注中,它们将被视为不同的文档。例如,如果真实标注的文档 ID 为 [1, 2] 且检索到的文档 ID 为 [1, 1, 1, 3],则得分等同于真实标注的文档 ID 为 [10, 11, 12, 2] 且检索到的文档 ID 为 [10, 11, 12, 3]。
用户创建他们自己的 EvaluationMetric,使用 make_metric 工厂函数
- mlflow.metrics.make_metric(*, eval_fn, greater_is_better, name=None, long_name=None, version=None, metric_details=None, metric_metadata=None, genai_metric_args=None)[source]
用于创建一个
EvaluationMetric对象的工厂函数。- Parameters
eval_fn –
一个计算指标的函数,具有以下签名:
def eval_fn( predictions: pandas.Series, targets: pandas.Series, metrics: Dict[str, MetricValue], **kwargs, ) -> Union[float, MetricValue]: """ Args: predictions: A pandas Series containing the predictions made by the model. targets: (Optional) A pandas Series containing the corresponding labels for the predictions made on that input. metrics: (Optional) A dictionary containing the metrics calculated by the default evaluator. The keys are the names of the metrics and the values are the metric values. To access the MetricValue for the metrics calculated by the system, make sure to specify the type hint for this parameter as Dict[str, MetricValue]. Refer to the DefaultEvaluator behavior section for what metrics will be returned based on the type of model (i.e. classifier or regressor). kwargs: Includes a list of args that are used to compute the metric. These args could information coming from input data, model outputs or parameters specified in the `evaluator_config` argument of the `mlflow.evaluate` API. kwargs: Includes a list of args that are used to compute the metric. These args could be information coming from input data, model outputs, other metrics, or parameters specified in the `evaluator_config` argument of the `mlflow.evaluate` API. Returns: MetricValue with per-row scores, per-row justifications, and aggregate results. """ ...
greater_is_better – 指标的值越大是否更好。
name – 指标的名称。如果
eval_fn是一个 lambda 函数 或者eval_fn.__name__属性不可用,则必须指定此参数。long_name – (Optional) The long name of the metric. For example,
"mean_squared_error"for"mse".version – (可选)指标的版本。例如
v1.metric_details – (可选) 对该度量的描述以及其计算方式。
metric_metadata – (可选) 一个包含该指标元数据的字典。
genai_metric_args – (可选)一个字典,包含用户在调用 make_genai_metric 或 make_genai_metric_from_prompt 时指定的参数。这些参数会被持久化,以便我们以后能够反序列化出相同的 metric 对象。
另请参见
mlflow.models.EvaluationMetric
生成式 AI 指标
我们还提供用于评估文本模型的生成式 AI(“genai”)EvaluationMetric。这些度量使用 LLM 来评估模型输出文本的质量。请注意,您在评估中使用第三方 LLM 服务(例如 OpenAI)可能受该 LLM 服务使用条款的约束并受其管理。以下工厂函数可帮助您根据用例自定义该智能度量。
- mlflow.metrics.genai.answer_correctness(model: Optional[str] = None, metric_version: Optional[str] = None, examples: Optional[list[mlflow.metrics.genai.base.EvaluationExample]] = None, metric_metadata: Optional[dict[str, typing.Any]] = None, parameters: Optional[dict[str, typing.Any]] = None, extra_headers: Optional[dict[str, str]] = None, proxy_url: Optional[str] = None, max_workers: int = 10) mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建一个 genai 指标,用于使用提供的模型评估 LLM 的答案正确性。答案正确性将通过所提供输出相对于
ground_truth的准确性来评估,ground_truth应在targets列中指定。较高的分数表示模型输出包含与ground_truth相似且正确的信息;而较低的分数则表示输出可能与ground_truth不一致或输出中的信息不正确。注意:这构建在 answer_similarity 之上。targetseval_arg 必须作为输入数据集或输出预测的一部分提供。可以通过在evaluator_config参数中使用col_mapping将其映射到不同名称的列,或在 mlflow.evaluate() 中使用targets参数实现。如果为该指标指定的版本不存在,将会引发 MlflowException。
- Parameters
model – (可选)将用于计算指标的评判模型的 URI,例如
openai:/gpt-4。有关受支持的模型类型及其 URI 格式,请参阅 LLM-as-a-Judge Metrics 文档。metric_version – 要使用的答案正确性指标的版本。默认为最新版本。
示例 – 提供一组示例以帮助评判模型评估答案的正确性。强烈建议添加示例,作为评估新结果的参考。
metric_metadata – (可选) 附加到 EvaluationMetric 对象的元数据字典。对于需要额外信息以决定如何评估此指标的模型评估器很有用。
parameters – (可选) 要传递给 judge 模型的 parameters 字典,例如 {“temperature”: 0.5}。指定后,这些 parameters 将覆盖在指标实现中定义的默认参数。
extra_headers – (可选) 用于传递给评审模型的额外请求头字典。
proxy_url –(可选)用于评估模型的代理 URL。当评估模型通过代理端点提供,而不是直接通过 LLM 提供者服务时,这非常有用。如果未指定,将使用 LLM 提供者的默认 URL(例如 https://api.openai.com/v1/chat/completions,适用于 OpenAI 聊天模型)。
max_workers –(可选)用于评判评分的最大工作者数量。默认值为10个工作者。
- Returns
一个指标对象
- mlflow.metrics.genai.answer_relevance(model: Optional[str] = None, metric_version: str | None = 'v1', examples: Optional[list[mlflow.metrics.genai.base.EvaluationExample]] = None, metric_metadata: Optional[dict[str, typing.Any]] = None, parameters: Optional[dict[str, typing.Any]] = None, extra_headers: Optional[dict[str, str]] = None, proxy_url: Optional[str] = None, max_workers: int = 10) mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建一个 genai 指标,用于使用所提供的模型评估 LLM 回答的相关性。回答相关性将根据输出相对于输入的适当性和适用性进行评估。高分表示模型的输出与输入主题大致相同,而低分则表示输出可能与主题无关。
如果为该指标指定的版本不存在,将会抛出 MlflowException。
- Parameters
model –
(可选)将用于计算指标的评判模型的模型 URI,例如
openai:/gpt-4。有关受支持的模型类型及其 URI 格式,请参阅 LLM-as-a-Judge Metrics 文档。metric_version – 要使用的答案相关性指标的版本。 默认为最新版本。
examples – 提供示例列表以帮助评判模型评估答案的相关性。强烈建议添加示例作为参考,用于评估新的结果。
metric_metadata –(可选)要附加到 EvaluationMetric object 的元数据字典。对于需要额外信息以确定如何评估该指标的模型评估器很有用。
parameters – (可选) 传递给评判模型的参数字典,例如 {“temperature”: 0.5}。当指定时,这些参数将覆盖度量实现中定义的默认参数。
extra_headers –(可选)传递给 judge 模型的额外请求头字典。
proxy_url – (可选) 用于评判模型的代理 URL。当评判模型通过代理端点提供,而不是直接通过 LLM 提供商的服务时,这很有用。如果未指定,将使用 LLM 提供商的默认 URL(例如 https://api.openai.com/v1/chat/completions 用于 OpenAI 聊天模型)。
max_workers – (可选) 用于进行评判评分的最大工作者数。默认为 10 个工作者。
- Returns
一个指标对象
- mlflow.metrics.genai.answer_similarity(model: Optional[str] = None, metric_version: Optional[str] = None, examples: Optional[list[mlflow.metrics.genai.base.EvaluationExample]] = None, metric_metadata: Optional[dict[str, typing.Any]] = None, parameters: Optional[dict[str, typing.Any]] = None, extra_headers: Optional[dict[str, str]] = None, proxy_url: Optional[str] = None, max_workers: int = 10) mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建一个 genai 指标,用于使用所提供的模型评估 LLM 的答案相似度。答案相似度将通过输出与
ground_truth的语义相似度来评估,后者应在targets列中指定。高分表示模型的输出包含与ground_truth相似的信息,而低分则表示输出可能与ground_truth存在不一致。targetseval_arg 必须作为输入数据集或输出预测的一部分提供。可以使用col_mapping在evaluator_config参数中将其映射到不同名称的列,或在 mlflow.evaluate() 中使用targets参数。如果为该指标指定的版本不存在,将会引发 MlflowException。
- Parameters
model –
(可选)用于计算度量的评判模型的 Model uri, 例如
openai:/gpt-4。请参阅 LLM-as-a-Judge Metrics 文档,了解支持的模型类型及其 URI 格式。metric_version – (可选) 要使用的答案相似性度量的版本。默认使用最新版本。
examples – (可选)提供一个示例列表,以帮助评判模型评估答案的相似性。强烈建议添加示例作为评估新结果的参考。
metric_metadata – (可选) 附加到 EvaluationMetric 对象的元数据字典。对于需要额外信息来决定如何评估该指标的模型评估器很有用。
parameters – (可选) 传递给判定模型的参数字典,例如 {“temperature”: 0.5}。当指定时,这些参数将覆盖度量实现中定义的默认参数。
extra_headers – (可选) 传递给 judge 模型的额外请求头的字典。
proxy_url – (可选)用于评估模型的代理 URL。当评估模型通过代理端点提供,而不是直接通过 LLM 提供商的服务时,这很有用。如果未指定,将使用 LLM 提供商的默认 URL(例如,https://api.openai.com/v1/chat/completions 对于 OpenAI 聊天模型)。
max_workers – (可选)用于评分的最大工作线程数。默认值为 10 个工作线程。
- Returns
一个指标对象
- mlflow.metrics.genai.faithfulness(model: Optional[str] = None, metric_version: str | None = 'v1', examples: Optional[list[mlflow.metrics.genai.base.EvaluationExample]] = None, metric_metadata: Optional[dict[str, typing.Any]] = None, parameters: Optional[dict[str, typing.Any]] = None, extra_headers: Optional[dict[str, str]] = None, proxy_url: Optional[str] = None, max_workers: int = 10) mlflow.models.evaluation.base.EvaluationMetric[source]
这个函数将创建一个 genai 指标,用于使用提供的模型评估 LLM 的忠实性。忠实性将基于输出与
context在事实上的一致程度来评估。高分意味着输出包含与上下文一致的信息,而低分意味着输出可能与上下文不一致(输入会被忽略)。必须在输入数据集或输出预测中提供
contexteval_arg。可以在evaluator_config参数中的col_mapping将其映射到不同名称的列。如果为该指标指定的版本不存在,将会抛出 MlflowException。
- Parameters
model –
(可选) 用于计算指标的 judge 模型的 URI,例如
openai:/gpt-4。有关受支持的模型类型及其 URI 格式,请参阅 LLM-as-a-Judge Metrics 文档。metric_version – 要使用的忠实度指标的版本。默认为最新版本。
examples – 提供一系列示例,帮助评判模型评估忠实度。强烈建议添加示例,作为评估新结果的参考。
metric_metadata – (可选) 附加到 EvaluationMetric 对象的元数据字典。对于需要额外信息以决定如何评估此指标的模型评估器很有用。
parameters – (可选) 要传递给评判模型的 parameters 字典,例如 {“temperature”: 0.5}。指定后,这些 parameters 将覆盖在指标实现中定义的默认 parameters。
extra_headers – (可选) 传递给 judge 模型的额外请求头字典。
proxy_url – (可选) 用于 judge 模型的代理 URL。当 judge 模型通过代理端点提供,而不是直接通过 LLM 提供商服务时,这很有用。如果未指定,则将使用 LLM 提供商的默认 URL(例如 https://api.openai.com/v1/chat/completions,用于 OpenAI 聊天模型)。
max_workers –(可选)用于评判评分的最大工作者数量。默认值为10个工作者。
- Returns
一个指标对象
- mlflow.metrics.genai.make_genai_metric_from_prompt(name: str, judge_prompt: Optional[str] = None, model: str | None = 'openai:/gpt-4', parameters: Optional[dict[str, typing.Any]] = None, aggregations: Optional[list[str]] = None, greater_is_better: bool = True, max_workers: int = 10, metric_metadata: Optional[dict[str, typing.Any]] = None, extra_headers: Optional[dict[str, str]] = None, proxy_url: Optional[str] = None) mlflow.models.evaluation.base.EvaluationMetric[source]
在 MLflow 中创建一个 genai 指标,用于使用 LLM 作为评判者来评估 LLM。该指标仅使用提供的评判提示,而不使用任何预先编写的系统提示。对于在任何
EvaluationModel版本中未被完整评分提示覆盖的用例,这很有用。- Parameters
name – 指标的名称。
judge_prompt – 用于评估模型的完整提示。 该提示会用最简要的格式化指令进行封装,以确保可以解析分数。 提示可能使用 f-string 格式来包含变量。 相应的变量必须作为关键字参数传递到生成的度量的 eval 函数中。
model –
(可选) 将用于计算指标的评判模型的模型 URI,例如
openai:/gpt-4。有关支持的模型类型及其 URI 格式,请参阅 LLM-as-a-Judge Metrics 文档。parameters – (可选)用于计算度量的 LLM 的参数。默认情况下,我们将 temperature 设置为 0.0,max_tokens 设置为 200,top_p 设置为 1.0。我们建议将用于作为评判的 LLM 的 temperature 设置为 0.0,以确保结果一致。
aggregations – (可选)用于聚合分数的选项列表。目前支持的选项有:min, max, mean, median, variance, p90.
greater_is_better – (可选) 指标值越大是否更好。
max_workers –(可选)用于评判评分的最大工作者数量。默认值为10个工作者。
metric_metadata – (可选) 附加到 EvaluationMetric 对象的元数据字典。对于需要额外信息以决定如何评估此指标的模型评估器很有用。
extra_headers – (可选) 传递给 judge 模型的附加请求头。
proxy_url –(可选)用于评估模型的代理 URL。当评估模型通过代理端点提供,而不是直接通过 LLM 提供者服务时,这非常有用。如果未指定,将使用 LLM 提供者的默认 URL(例如 https://api.openai.com/v1/chat/completions,适用于 OpenAI 聊天模型)。
- Returns
一个指标对象。
import pandas as pd import mlflow from mlflow.metrics.genai import make_genai_metric_from_prompt metric = make_genai_metric_from_prompt( name="ease_of_understanding", judge_prompt=( "You must evaluate the output of a bot based on how easy it is to " "understand its outputs." "Evaluate the bot's output from the perspective of a layperson." "The bot was provided with this input: {input} and this output: {output}." ), model="openai:/gpt-4", parameters={"temperature": 0.0}, aggregations=["mean", "variance", "p90"], greater_is_better=True, ) data = pd.DataFrame( { "input": ["Where is the capital of France."], "ground_truth": ["Paris"], "output": ["The capital of France is Paris."], } ) mlflow.evaluate( data=data, targets="ground_truth", predictions="output", evaluators="default", extra_metrics=[metric], )
- mlflow.metrics.genai.relevance(model: Optional[str] = None, metric_version: Optional[str] = None, examples: Optional[list[mlflow.metrics.genai.base.EvaluationExample]] = None, metric_metadata: Optional[dict[str, typing.Any]] = None, parameters: Optional[dict[str, typing.Any]] = None, extra_headers: Optional[dict[str, str]] = None, proxy_url: Optional[str] = None, max_workers: int = 10) mlflow.models.evaluation.base.EvaluationMetric[source]
此函数将创建一个用于评估给定模型下 LLM 相关性的 genai 指标。相关性将通过输出相对于输入和
context的适当性、重要性和可应用性来评估。高分意味着模型已理解上下文并从上下文中正确提取了相关信息,而低分则意味着输出完全忽视了问题和上下文,可能在产生幻觉。必须将
contexteval_arg 作为输入数据集或输出预测的一部分提供。可以在evaluator_config参数中使用col_mapping将其映射到不同名称的列。如果为该指标指定的版本不存在,将会抛出 MlflowException。
- Parameters
model –
(可选)将用于计算指标的评判模型的模型 URI,例如
openai:/gpt-4。有关受支持的模型类型及其 URI 格式,请参阅 LLM-as-a-Judge Metrics 文档。metric_version – (可选)要使用的相关性指标的版本。默认使用最新版本。
examples – (可选)提供一个示例列表,以帮助评判模型评估相关性。强烈建议添加示例作为参考,用于评估新的结果。
metric_metadata – (可选) 附加到 EvaluationMetric 对象的元数据字典。对于需要额外信息来决定如何评估该指标的模型评估器很有用。
parameters – (可选) 要传递给 judge 模型的 parameters 字典,例如 {“temperature”: 0.5}。指定后,这些 parameters 将覆盖在指标实现中定义的默认参数。
extra_headers – (可选)一个字典,包含要传递给 judge model 的额外 headers。
proxy_url –(可选)用于评估模型的代理 URL。当评估模型通过代理端点提供,而不是直接通过 LLM 提供者服务时,这非常有用。如果未指定,将使用 LLM 提供者的默认 URL(例如 https://api.openai.com/v1/chat/completions,适用于 OpenAI 聊天模型)。
max_workers –(可选)用于评判评分的最大工作者数量。默认值为10个工作者。
- Returns
一个指标对象
- mlflow.metrics.genai.retrieve_custom_metrics(run_id: str, name: Optional[str] = None, version: Optional[str] = None) list[mlflow.models.evaluation.base.EvaluationMetric][source]
检索与特定评估运行关联的、由用户通过 make_genai_metric() 或 make_genai_metric_from_prompt() 创建的自定义指标。
- Parameters
run_id – 该运行的唯一标识符。
name – (可选) 要检索的自定义指标的名称。如果 None,检索所有指标。
version – (可选) 要检索的自定义指标的版本。如果为 None,则检索所有指标。
- Returns
匹配检索条件的 EvaluationMetric 对象列表。
import pandas as pd import mlflow from mlflow.metrics.genai.genai_metric import ( make_genai_metric_from_prompt, retrieve_custom_metrics, ) eval_df = pd.DataFrame( { "inputs": ["foo"], "ground_truth": ["bar"], } ) with mlflow.start_run() as run: system_prompt = "Answer the following question in two sentences" basic_qa_model = mlflow.openai.log_model( model="gpt-4o-mini", task="chat.completions", name="model", messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": "{question}"}, ], ) custom_metric = make_genai_metric_from_prompt( name="custom_llm_judge", judge_prompt="This is a custom judge prompt.", greater_is_better=False, parameters={"temperature": 0.0}, ) results = mlflow.evaluate( basic_qa_model.model_uri, eval_df, targets="ground_truth", model_type="question-answering", evaluators="default", extra_metrics=[custom_metric], ) metrics = retrieve_custom_metrics( run_id=run.info.run_id, name="custom_llm_judge", )
您还可以创建您自己的生成式 AI EvaluationMetric,使用 make_genai_metric 工厂函数。
- mlflow.metrics.genai.make_genai_metric(name: str, definition: str, grading_prompt: str, examples: Optional[list[mlflow.metrics.genai.base.EvaluationExample]] = None, version: str | None = 'v1', model: str | None = 'openai:/gpt-4', grading_context_columns: Optional[Union[str, list[str]]] = None, include_input: bool = True, parameters: Optional[dict[str, typing.Any]] = None, aggregations: Optional[list[str]] = None, greater_is_better: bool = True, max_workers: int = 10, metric_metadata: Optional[dict[str, typing.Any]] = None, extra_headers: Optional[dict[str, str]] = None, proxy_url: Optional[str] = None) mlflow.models.evaluation.base.EvaluationMetric[source]
创建一个 genai 指标,用于在 MLflow 中使用 LLM 作为评判者来评估 LLM。完整的评分提示存储在
EvaluationMetric对象的 metric_details 字段中。- Parameters
name – 指标的名称。
definition – 指标的定义。
grading_prompt – 指标的评分标准。
examples – (可选)指标的示例。
version –(可选)指标的版本。目前支持的版本为:v1。
model –
(可选)将用于计算指标的评判模型的模型 URI,例如
openai:/gpt-4。有关受支持的模型类型及其 URI 格式,请参阅 LLM-as-a-Judge Metrics 文档。grading_context_columns – (可选)评分上下文列的名称,或一组评分上下文列名称,计算指标时所需。
grading_context_columns被 LLM 用作评判时的附加信息以计算指标。grading_context_columns这些列根据传递给mlflow.evaluate()的evaluator_config中的col_mapping从输入数据集或输出预测中提取。它们也可以是其他已评估指标的名称。include_input – (可选) 在计算指标时是否包含输入。
parameters – (可选)用于计算指标的LLM的参数。默认情况下,我们将 temperature 设置为 0.0,max_tokens 设置为 200,top_p 设置为 1.0。我们建议将作为评判者使用的 LLM 的 temperature 设置为 0.0 以确保结果一致。
aggregations –(可选)用于对分数进行聚合的选项列表。目前支持的选项有:min, max, mean, median, variance, p90。
greater_is_better – (可选) 当该指标越大时是否更好。
max_workers – (可选)用于评分的最大工作线程数。默认值为 10 个工作线程。
metric_metadata –(可选)要附加到 EvaluationMetric object 的元数据字典。对于需要额外信息以确定如何评估该指标的模型评估器很有用。
extra_headers – (可选) 传递给评估模型的附加头信息。
proxy_url – (可选) 用于 judge 模型的代理 URL。当 judge 模型通过代理端点提供,而不是直接通过 LLM 提供商服务时,这很有用。如果未指定,则将使用 LLM 提供商的默认 URL(例如 https://api.openai.com/v1/chat/completions,用于 OpenAI 聊天模型)。
- Returns
一个指标对象。
from mlflow.metrics.genai import EvaluationExample, make_genai_metric example = EvaluationExample( input="What is MLflow?", output=( "MLflow is an open-source platform for managing machine " "learning workflows, including experiment tracking, model packaging, " "versioning, and deployment, simplifying the ML lifecycle." ), score=4, justification=( "The definition effectively explains what MLflow is " "its purpose, and its developer. It could be more concise for a 5-score.", ), grading_context={ "targets": ( "MLflow is an open-source platform for managing " "the end-to-end machine learning (ML) lifecycle. It was developed by " "Databricks, a company that specializes in big data and machine learning " "solutions. MLflow is designed to address the challenges that data " "scientists and machine learning engineers face when developing, training, " "and deploying machine learning models." ) }, ) metric = make_genai_metric( name="answer_correctness", definition=( "Answer correctness is evaluated on the accuracy of the provided output based on " "the provided targets, which is the ground truth. Scores can be assigned based on " "the degree of semantic similarity and factual correctness of the provided output " "to the provided targets, where a higher score indicates higher degree of accuracy." ), grading_prompt=( "Answer correctness: Below are the details for different scores:" "- Score 1: The output is completely incorrect. It is completely different from " "or contradicts the provided targets." "- Score 2: The output demonstrates some degree of semantic similarity and " "includes partially correct information. However, the output still has significant " "discrepancies with the provided targets or inaccuracies." "- Score 3: The output addresses a couple of aspects of the input accurately, " "aligning with the provided targets. However, there are still omissions or minor " "inaccuracies." "- Score 4: The output is mostly correct. It provides mostly accurate information, " "but there may be one or more minor omissions or inaccuracies." "- Score 5: The output is correct. It demonstrates a high degree of accuracy and " "semantic similarity to the targets." ), examples=[example], version="v1", model="openai:/gpt-4", grading_context_columns=["targets"], parameters={"temperature": 0.0}, aggregations=["mean", "variance", "p90"], greater_is_better=True, )
在使用生成式 AI 的 EvaluationMetric 时,传入一个 EvaluationExample 非常重要。
- class mlflow.metrics.genai.EvaluationExample(output: str, score: float, justification: str, input: Optional[str] = None, grading_context: Optional[Union[dict[str, str], str]] = None)[source]
在 LLM 评估期间,在少样本学习过程中存储样本示例
- Parameters
input – 提供给模型的输入
output – 模型生成的输出
score – 评估者给出的分数
justification – 评估者给出的理由
grading_context – 提供给评估器用于评估的 grading_context。可以是一个包含 grading context 列名和 grading context 字符串的字典,或者一个单一的 grading context 字符串。
from mlflow.metrics.genai import EvaluationExample example = EvaluationExample( input="What is MLflow?", output="MLflow is an open-source platform for managing machine " "learning workflows, including experiment tracking, model packaging, " "versioning, and deployment, simplifying the ML lifecycle.", score=4, justification="The definition effectively explains what MLflow is " "its purpose, and its developer. It could be more concise for a 5-score.", grading_context={ "ground_truth": "MLflow is an open-source platform for managing " "the end-to-end machine learning (ML) lifecycle. It was developed by Databricks, " "a company that specializes in big data and machine learning solutions. MLflow is " "designed to address the challenges that data scientists and machine learning " "engineers face when developing, training, and deploying machine learning models." }, ) print(str(example))
Input: What is MLflow? Provided output: "MLflow is an open-source platform for managing machine " "learning workflows, including experiment tracking, model packaging, " "versioning, and deployment, simplifying the ML lifecycle." Provided ground_truth: "MLflow is an open-source platform for managing " "the end-to-end machine learning (ML) lifecycle. It was developed by Databricks, " "a company that specializes in big data and machine learning solutions. MLflow is " "designed to address the challenges that data scientists and machine learning " "engineers face when developing, training, and deploying machine learning models." Score: 4 Justification: "The definition effectively explains what MLflow is " "its purpose, and its developer. It could be more concise for a 5-score."
用户必须为他们用于评估的 LLM 服务设置适当的环境变量。例如,如果您使用 OpenAI 的 API,必须设置 OPENAI_API_KEY 环境变量。如果使用 Azure OpenAI,还必须设置 OPENAI_API_TYPE、OPENAI_API_VERSION、OPENAI_API_BASE 和 OPENAI_DEPLOYMENT_NAME 环境变量。参见 Azure OpenAI documentation。如果使用网关路由,用户无需设置这些环境变量。