# カスタム指標の定義

> カスタム指標の定義 - MetricBaseクラスは、4つの追加のデフォルトクラスと共に、カスタム指標を定義するインターフェイスを提供します。

This Markdown file sits beside the HTML page at the same path (with a `.md` suffix). It summarizes the topic and lists links for tools and LLM context.

Companion generated at `2026-07-15T05:55:44.596781+00:00` (UTC).

## Primary page

- [カスタム指標の定義](https://docs.datarobot.com/ja/docs/api/code-first-tools/dr-model-metrics/dmm-custom-metrics.html.md): Full documentation for this topic (Markdown sidecar).

## Sections on this page

- [指標ベースの作成](https://docs.datarobot.com/ja/docs/api/code-first-tools/dr-model-metrics/dmm-custom-metrics.html.md#_2): In-page section heading.
- [予測値と実測値で計算される指標の作成](https://docs.datarobot.com/ja/docs/api/code-first-tools/dr-model-metrics/dmm-custom-metrics.html.md#_3): In-page section heading.
- [スコアリングデータで計算された指標の作成](https://docs.datarobot.com/ja/docs/api/code-first-tools/dr-model-metrics/dmm-custom-metrics.html.md#_4): In-page section heading.
- [LLM指標の作成](https://docs.datarobot.com/ja/docs/api/code-first-tools/dr-model-metrics/dmm-custom-metrics.html.md#llm): In-page section heading.
- [Sklearn指標の作成](https://docs.datarobot.com/ja/docs/api/code-first-tools/dr-model-metrics/dmm-custom-metrics.html.md#sklearn): In-page section heading.
- [PromptSimilarityMetricBase](https://docs.datarobot.com/ja/docs/api/code-first-tools/dr-model-metrics/dmm-custom-metrics.html.md#promptsimilaritymetricbase): In-page section heading.
- [カスタム指標値の報告](https://docs.datarobot.com/ja/docs/api/code-first-tools/dr-model-metrics/dmm-custom-metrics.html.md#_5): In-page section heading.

## Documentation content

`MetricBase` クラスは、カスタム指標を定義するインターフェイスを提供します。 カスタム指標の作成には、 `ModelMetricBase` 、 `DataMetricBase` 、 `LLMMetricBase` および `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](https://scikit-learn.org/stable/modules/classes.html#module-sklearn.metrics) の既製で実績のある指標を使用できます。 カスタム指標を作成するために、 `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

`PromptSimilarityMetricBase` クラスは、LLMプロンプトとコンテキストベクトルを比較します。 このクラスは一般的に、プロンプトベクトルとコンテキストベクトルが以下のように入力されるテキスト生成モデルで使用されます。

基底クラスは `scoring_data` からベクトルを取り出し、各エントリを繰り返し処理します。

- プロンプトベクトルは、scoring_dataのprompt_column（デフォルトは_LLM_PROMPT_VECTOR）から抽出されます。
- コンテキストベクトルは、scoring_dataのcontext_column（デフォルトは_LLM_CONTEXT）から抽出されます。 コンテキスト列にはコンテキストディクショナリのリストが含まれ、各コンテキストにはvector要素が必要です。

> [!NOTE] 備考
> `prompt_column` も `context_column` もJSONエンコードされたデータであることが期待されます。

派生クラスは `calculate_distance()` を実装する必要があります。 このクラスでは、 `score()` は既に実装されています。

`calculate_distance` 関数は、単一 `prompt_vector` および `context_vectors` のリストに基づいて、単一の浮動小数点値を返します。

`PromptSimilarityMetricBase` を使った例として、ユークリッド距離の最小値を計算する以下のコードをご覧ください：

```
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_id` 、 `deployment_id` 、 `model_id` 、 `DataRobotClient()` ）。

```
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 
```
