> ## Documentation Index
> Fetch the complete documentation index at: https://wb-21fd5541-feature-automate-reference-docs-generation.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Evaluation logger

The `EvaluationLogger` provides a flexible, incremental way to log evaluation data directly from your Python code. You don't need deep knowledge of Weave's internal data types; simply instantiate a logger and use its methods (`log_prediction`, `log_score`, `log_summary`) to record evaluation steps.

이 접근 방식은 전체 데이터셋이나 모든 평가 도구가 미리 정의되지 않을 수 있는 복잡한 워크플로우에서 특히 유용합니다.

미리 정의된 `Evaluation` object, which requires a predefined `Dataset` and list of `Scorer` objects, the `EvaluationLogger` allows you to log individual predictions and their associated scores incrementally as they become available.

<Info>
  **더 구조화된 평가를 선호하시나요?**

  미리 정의된 데이터셋과 평가 도구가 있는 더 체계적인 평가 프레임워크를 선호하신다면, [Weave's standard Evaluation framework](../core-types/evaluations.mdx)를 참조하세요.

  The `EvaluationLogger` offers flexibility while the standard framework offers structure and guidance.
</Info>

## 기본 워크플로우

1. *로거 초기화:* Create an instance of `EvaluationLogger`, optionally providing metadata about the `model` and `dataset`. Defaults will be used if omitted.
   :::important 토큰 사용량 및 비용 추적
   LLM 호출(예: OpenAI)에 대한 토큰 사용량과 비용을 캡처하려면, `EvaluationLogger` before any LLM invocations\*\*.
   LLM을 먼저 호출한 다음 나중에 예측을 로깅하면 토큰 및 비용 데이터가 캡처되지 않습니다.
   :::
2. *예측 로깅:* Call `log_prediction` for each input/output pair from your system.
3. *점수 로깅:* Use the returned `ScoreLogger` to `log_score` for the prediction. Multiple scores per prediction are supported.
4. *예측 완료:* Always call `finish()` after logging scores for a prediction to finalize it.
5. *요약 로깅:* After all predictions are processed, call `log_summary` to aggregate scores and add optional custom metrics.

<Warning>
  예측에 대해 `finish()`를 호출한 후에는 해당 예측에 대한 점수를 더 이상 로깅할 수 없습니다.
</Warning>

설명된 워크플로우를 보여주는 Python 코드는 [Basic example](#basic-example)을 참조하세요.

## 기본 예제

다음 예제는 `EvaluationLogger`를 사용하여 기존 Python 코드에서 예측과 점수를 인라인으로 로깅하는 방법을 보여줍니다.

The `user_model` model function is defined and applied to a list of inputs. For each example:

* 입력과 출력은 `log_prediction`를 사용하여 로깅됩니다.
* 간단한 정확도 점수(`correctness_score`)는 `log_score`를 통해 로깅됩니다.
* `finish()`는 해당 예측에 대한 로깅을 완료합니다.
  마지막으로, `log_summary`는 집계 메트릭을 기록하고 Weave에서 자동 점수 요약을 트리거합니다.

```python
import weave
from openai import OpenAI
from weave import EvaluationLogger 

weave.init('my-project')

# Initialize EvaluationLogger BEFORE calling the model to ensure token tracking
eval_logger = EvaluationLogger(
    model="my_model",
    dataset="my_dataset"
)

# Example input data (this can be any data structure you want)
eval_samples = [
    {'inputs': {'a': 1, 'b': 2}, 'expected': 3},
    {'inputs': {'a': 2, 'b': 3}, 'expected': 5},
    {'inputs': {'a': 3, 'b': 4}, 'expected': 7},
]

# Example model logic using OpenAI
@weave.op
def user_model(a: int, b: int) -> int:
    oai = OpenAI()
    response = oai.chat.completions.create(
        messages=[{"role": "user", "content": f"What is {a}+{b}?"}],
        model="gpt-4o-mini"
    )
    # Use the response in some way (here we just return a + b for simplicity)
    return a + b

# Iterate through examples, predict, and log
for sample in eval_samples:
    inputs = sample["inputs"]
    model_output = user_model(**inputs) # Pass inputs as kwargs

    # Log the prediction input and output
    pred_logger = eval_logger.log_prediction(
        inputs=inputs,
        output=model_output
    )

    # Calculate and log a score for this prediction
    expected = sample["expected"]
    correctness_score = model_output == expected
    pred_logger.log_score(
        scorer="correctness", # Simple string name for the scorer
        score=correctness_score
    )

    # Finish logging for this specific prediction
    pred_logger.finish()

# Log a final summary for the entire evaluation.
# Weave auto-aggregates the 'correctness' scores logged above.
summary_stats = {"subjective_overall_score": 0.8}
eval_logger.log_summary(summary_stats)

print("Evaluation logging complete. View results in the Weave UI.")
```

## 고급 사용법

### 로깅 전 출력 가져오기

먼저 모델 출력을 계산한 다음 별도로 예측과 점수를 로깅할 수 있습니다. 이를 통해 평가 로직과 로깅 로직을 더 잘 분리할 수 있습니다.

```python
# Initialize EvaluationLogger BEFORE calling the model to ensure token tracking
ev = EvaluationLogger(
    model="example_model", 
    dataset="example_dataset"
)

# Model outputs (e.g. OpenAI calls) must happen after logger init for token tracking
outputs = [your_output_generator(**inputs) for inputs in your_dataset]
preds = [ev.log_prediction(inputs, output) for inputs, output in zip(your_dataset, outputs)]
for pred in preds:
    pred.log_score(scorer="greater_than_5_scorer", score=output > 5)
    pred.log_score(scorer="greater_than_7_scorer", score=output > 7)
    pred.finish()

ev.log_summary()
```

### 풍부한 미디어 로깅

입력, 출력 및 점수에는 이미지, 비디오, 오디오 또는 구조화된 테이블과 같은 풍부한 미디어가 포함될 수 있습니다. 딕셔너리나 미디어 객체를 `log_prediction` or `log_score` methods:

```python
import io
import wave
import struct
from PIL import Image
import random
from typing import Any
import weave

def generate_random_audio_wave_read(duration=2, sample_rate=44100):
    n_samples = duration * sample_rate
    amplitude = 32767  # 16-bit max amplitude

    buffer = io.BytesIO()

    # Write wave data to the buffer
    with wave.open(buffer, 'wb') as wf:
        wf.setnchannels(1)
        wf.setsampwidth(2)  # 16-bit
        wf.setframerate(sample_rate)

        for _ in range(n_samples):
            sample = random.randint(-amplitude, amplitude)
            wf.writeframes(struct.pack('<h', sample))

    # Rewind the buffer to the beginning so we can read from it
    buffer.seek(0)

    # Return a Wave_read object
    return wave.open(buffer, 'rb')

rich_media_dataset = [
    {
        'image': Image.new(
            "RGB",
            (100, 100),
            color=(
                random.randint(0, 255),
                random.randint(0, 255),
                random.randint(0, 255),
            ),
        ),
        "audio": generate_random_audio_wave_read(),
    }
    for _ in range(5)
]

@weave.op
def your_output_generator(image: Image.Image, audio) -> dict[str, Any]:
    return {
        "result": random.randint(0, 10),
        "image": image,
        "audio": audio,
    }

ev = EvaluationLogger(model="example_model", dataset="example_dataset")

for inputs in rich_media_dataset:
    output = your_output_generator(**inputs)
    pred = ev.log_prediction(inputs, output)
    pred.log_score(scorer="greater_than_5_scorer", score=output["result"] > 5)
    pred.log_score(scorer="greater_than_7_scorer", score=output["result"] > 7)

ev.log_summary()
```

### 여러 평가 로깅 및 비교

With `EvaluationLogger`, you can log and compare multiple evaluations.

1. 아래 표시된 코드 샘플을 실행하세요.
2. Weave UI에서 `Evals` 탭으로 이동하세요.
3. 비교하려는 평가를 선택하세요.
4. Click the **Compare** 버튼을 클릭하세요. 비교 보기에서 다음을 수행할 수 있습니다:
   * 추가하거나 제거할 평가 선택
   * 표시하거나 숨길 메트릭 선택
   * 특정 예제를 페이지별로 살펴보며 다른 모델이 주어진 데이터셋에서 동일한 입력에 대해 어떻게 수행되었는지 확인
     비교에 대한 자세한 내용은 [Comparisons](../tools/comparison.mdx)

```python
import weave

models = [
    "model1",
    "model2",
     {"name": "model3", "metadata": {"coolness": 9001}}
]

for model in models:
    # EvalLogger must be initialized before model calls to capture tokens
    ev = EvaluationLogger(model=model, dataset="example_dataset")
    for inputs in your_dataset:
        output = your_output_generator(**inputs)
        pred = ev.log_prediction(inputs=inputs, output=output)
        pred.log_score(scorer="greater_than_3_scorer", score=output > 3)
        pred.log_score(scorer="greater_than_5_scorer", score=output > 5)
        pred.log_score(scorer="greater_than_7_scorer", score=output > 7)
        pred.finish()

    ev.log_summary()
```

![The Evals tab](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ko/guides/evaluation/img/evals_tab.png)

![The Comparison view](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ko/guides/evaluation/img/comparison.png)

## 사용 팁

* 각 예측 후 즉시 `finish()`를 호출하세요.
* Use `log_summary`를 사용하여 단일 예측에 연결되지 않은 메트릭(예: 전체 지연 시간)을 캡처하세요.
* 풍부한 미디어 로깅은 정성적 분석에 탁월합니다.
