Skip to content

アプリケーション内で をクリックすると、お使いのDataRobotバージョンに関する全プラットフォームドキュメントにアクセスできます。

カスタム指標の定義

MetricBaseクラスは、カスタム指標を定義するインターフェイスを提供します。 カスタム指標の作成には、ModelMetricBaseDataMetricBaseLLMMetricBaseおよびSklearnMetricの4つの追加のデフォルトクラスが役立ちます。

指標ベースの作成

MetricBaseで、指標に必要なデータの型を定義します。カスタム指標はその定義を継承します。

class MetricBase(object):
    def __init__(
        self,
        name: str,
        description: str = None,
        need_predictions: bool = False,
        need_actuals: bool = False,
        need_scoring_data: bool = False,
        need_training_data: bool = False,
    ):
        self.name = name
        self.description = description
        self._need_predictions = need_predictions
        self._need_actuals = need_actuals
        self._need_scoring_data = need_scoring_data
        self._need_training_data = need_training_data 

さらに、MetricBaseでは、スコアリングおよび削減の方法を導入する必要があります。

  • スコアリング(score):初期化されたデータ型を使用して指標を計算します。

  • 削減(reduce_func):同じTimeBucketにある複数の値を1つの値に減らします。

    def score(
        self,
        scoring_data: pd.DataFrame,
        predictions: np.ndarray,
        actuals: np.ndarray,
        fit_ctx=None,
        metadata=None,
    ) -> float:
        raise NotImplemented

    def reduce_func(self) -> callable:
        return np.mean 

予測値と実測値で計算される指標の作成

ModelMetricBaseは、指標の計算に実測値と予測値を必要とする指標の基本クラスです。

class ModelMetricBase(MetricBase):
    def __init__(
        self, name: str, description: str = None, need_training_data: bool = False
    ):
        super().__init__(
            name=name,
            description=description,
            need_scoring_data=False,
            need_predictions=True,
            need_actuals=True,
            need_training_data=need_training_data,
        )

    def score(
        self,
        prediction: np.ndarray,
        actuals: np.ndarray,
        fit_context=None,
        metadata=None,
        scoring_data=None,
    ) -> float:
        raise NotImplemented 

スコアリングデータで計算された指標の作成

DataMetricBaseは、指標の計算にスコアリングデータが必要な指標の基本クラスです。

class DataMetricBase(MetricBase):
    def __init__(
        self, name: str, description: str = None, need_training_data: bool = False
    ):
        super().__init__(
            name=name,
            description=description,
            need_scoring_data=True,
            need_predictions=False,
            need_actuals=False,
            need_training_data=need_training_data,
        )

    def score(
        self,
        scoring_data: pd.DataFrame,
        fit_ctx=None,
        metadata=None,
        predictions=None,
        actuals=None,
    ) -> float:
        raise NotImplemented 

LLM指標の作成

LLMMetricBaseは、指標の計算にスコアリングデータおよび予測値を必要とするLLM指標の基本クラスです。 プロンプト (ユーザー入力)および 完了 (LLMの回答)とも呼ばれます。

class LLMMetricBase(MetricBase):
    def __init__(
        self, name: str, description: str = None, need_training_data: bool = False
    ):
        super().__init__(
            name=name,
            description=description,
            need_scoring_data=True,
            need_predictions=True,
            need_actuals=False,
            need_training_data=need_training_data,
        )

    def score(
        self,
        scoring_data: pd.DataFrame,
        predictions: np.ndarray,
        fit_ctx=None,
        metadata=None,
        actuals=None,
    ) -> float:
        raise NotImplemented 

Sklearn指標の作成

カスタム指標の導入を加速するために、 Sklearnの既製で実績のある指標を使用できます。 カスタム指標を作成するために、SklearnMetricクラスを基本クラスとして使用し、指標名を指定します。 例:

from dmm.metric.sklearn_metric import SklearnMetric


class MedianAbsoluteError(SklearnMetric):
    """
    Metric that calculates the median absolute error of the difference between predictions and actuals
    """

    def __init__(self):
        super().__init__(
            metric="median_absolute_error",
        ) 

PromptSimilarityMetricBase

The PromptSimilarityMetricBase class compares the LLM prompt and context vectors. This class is generally used with Text Generation models where the prompt and context vectors are populated as described below:

The base class pulls the vectors from the scoring_data, and iterates over each entry:

  • The prompt vector is pulled from the prompt_column (which defaults to _LLM_PROMPT_VECTOR) of the scoring_data.

  • The context vectors are pulled from the context_column (which defaults to _LLM_CONTEXT) of the scoring_data. The context column contains a list of context dictionaries, and each context needs to have a vector element.

備考

Both the prompt_column and context_column are expected to be JSON-encoded data.

A derived class must implement calculate_distance(). For this class, score() is already implemented.

The calculate_distance function returns a single floating point value based on a single prompt_vector and a list of context_vectors.

For an example using the PromptSimilarityMetricBase, review the code below calculating the minimum Euclidean distance:

from dmm.metric import PromptSimilarityMetricBase

class EuclideanMinMetric(PromptSimilarityMetricBase):
    """Calculate the minimum Euclidean distance between a prompt vector and a list of context vectors"""
    def calculate_distance(self, prompt_vector: np.ndarray, context_vectors: List[np.ndarray]) -> float:
        distances = [
            np.linalg.norm(prompt_vector - context_vector)
            for context_vector in context_vectors
        ]
        return min(distances)

# Instantiation could look like this
scorer = EuclideanMinMetric(name=custom_metric.name, description="Euclidean minimum distance between prompt and context vectors")

カスタム指標値の報告

上記の指標は、カスタム指標定義のソースを提供します。 CustomMetricインターフェイスを使用して、DataRobot内の既存のカスタム指標のメタデータを取得し、そのカスタム指標に対してデータを報告します。 パラメーターを明示的に指定することにより指標を初期化します(metric_iddeployment_idmodel_idDataRobotClient())。

from dmm import CustomMetric


cm = CustomMetric.from_id(metric_id=METRIC_ID, deployment_id=DEPLOYMENT_ID, model_id=MODEL_ID, client=CLIENT) 

これらのパラメーターを環境変数として定義することもできます。

パラメーター 環境変数
metric_id os.environ["CUSTOM_METRIC_ID"]
deployment_id os.environ["DEPLOYMENT_ID"]
model_id os.environ["MODEL_ID"]
DataRobotClient() os.environ["BASE_URL"] and os.environ["DATAROBOT_ENDPOINT"]
from dmm import CustomMetric


cm = CustomMetric.from_id() 

オプションで、バッチモード(is_batch=True)を指定します。

from dmm import CustomMetric


cm = CustomMetric.from_id(is_batch=True) 

reportメソッドでは、カスタム指標値をDataRobotで定義されたカスタム指標に送信します。 このメソッドを使用するには、MetricEvaluatorから出力された形式でDataFrameを報告します。

print(aggregated_metric_per_time_bucket.to_string())

                    timestamp  samples  median_absolute_error
1  01/06/2005 14:00:00.000000        2                  0.001

response = cm.report(df=aggregated_metric_per_time_bucket)
print(response.status_code)
202 

dry_runパラメーターは、カスタム指標値転送が、仮実行(値がデータベースに保存されない)か、本番データ転送かを決定します。

このパラメーターはデフォルトではFalseです(値は保存されます)。

response = cm.report(df=aggregated_metric_per_time_bucket, dry_run=True)
print(response.status_code)
202 

更新しました January 3, 2025