> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreweave.com/llms.txt
> Use this file to discover all available pages before exploring further.

> 머신러닝 실험의 플롯을 생성하고 추적합니다.

# 실험의 플롯 생성 및 추적

W\&B Models에서는 `wandb.plot`의 메서드와 `wandb.Run.log()`를 사용해 차트를 추적할 수 있으며, 트레이닝 중 시간에 따라 변하는 차트도 추적할 수 있습니다. 맞춤형 차트 프레임워크에 대한 자세한 내용은 [맞춤형 차트 워크스루](/ko/products/wandb/app/features/custom-charts/walkthrough)를 참조하세요.

<h3 id="basic-charts">
  기본 차트
</h3>

W\&B 차트를 만들려면 다음 단계를 따르세요.

1. `wandb.Table` 객체를 만들고 시각화할 데이터를 추가하세요.
2. W\&B의 기본 제공 [헬퍼 함수](/ko/products/wandb/ref/python/custom-charts) 중 하나를 사용하여 플롯을 생성하세요.
3. `wandb.Run.log()`로 플롯을 로깅하세요.

다음 기본 차트를 사용하면 메트릭과 결과를 간단하게 시각화할 수 있습니다.

<Tabs>
  <Tab title="선">
    임의의 축 위에 정렬된 점들을 연결한 목록인 맞춤형 선형 플롯을 로깅하세요.

    ```python theme={"system"}
    import wandb

    with wandb.init() as run:
        data = [[x, y] for (x, y) in zip(x_values, y_values)]
        table = wandb.Table(data=data, columns=["x", "y"])
        run.log(
            {
                "my_custom_plot_id": wandb.plot.line(
                    table, "x", "y", title="Custom Y versus X line plot"
                )
            }
        )
    ```

    이 기능을 사용하면 임의의 두 차원에 곡선을 로깅할 수 있습니다. 두 값 목록을 서로 플로팅하는 경우, 목록의 값 수가 정확히 일치해야 합니다. 예를 들어, 각 포인트는 x와 y를 가져야 합니다.

    <Frame>
      <img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/_media/track-line_plot.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=ef622b598153a8a6108a78edb9a2dfd9" alt="맞춤형 선형 플롯" width="1930" height="1228" data-path="products/wandb/_media/track-line_plot.png" />
    </Frame>

    자세한 내용은 [W\&B로 맞춤형 선형 플롯 만들기](https://forge.coreweave.com/wandb/wandb/plots/reports/Custom-Line-Plots--VmlldzoyNjk5NTA) 보고서를 참조하세요.

    [코드 실행](https://tiny.cc/custom-charts)
  </Tab>

  <Tab title="산점도">
    맞춤형 scatter plot(임의의 x축과 y축에 있는 점(x, y)의 목록)을 로깅하세요.

    ```python theme={"system"}
    import wandb

    with wandb.init() as run:
        data = [[x, y] for (x, y) in zip(class_x_scores, class_y_scores)]
        table = wandb.Table(data=data, columns=["class_x", "class_y"])
        run.log({"my_custom_id": wandb.plot.scatter(table, "class_x", "class_y")})
    ```

    이를 사용하면 임의의 두 차원에 대한 산점도 점을 로깅할 수 있습니다. 두 값 목록을 서로 대비하여 플로팅하는 경우, 두 목록의 값 개수가 정확히 일치해야 합니다. 예를 들어, 각 점에는 x 값과 y 값이 모두 있어야 합니다.

    <Frame>
      <img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/_media/track-demo_scatter_plot.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=6f5f64e4d2295b2759f94c1fe9a38d78" alt="맞춤형 산점도" width="2194" height="940" data-path="products/wandb/_media/track-demo_scatter_plot.png" />
    </Frame>

    자세한 내용은 [Creating Custom Scatter Plots With W\&B](https://forge.coreweave.com/wandb/wandb/plots/reports/Custom-Scatter-Plots--VmlldzoyNjk5NDQ) 리포트를 참조하세요.

    [코드 실행하기](https://tiny.cc/custom-charts)
  </Tab>

  <Tab title="막대">
    몇 줄의 코드로 맞춤형 막대 차트(레이블이 지정된 값의 목록을 막대로 표시)를 기본적으로 로깅하세요:

    ```python theme={"system"}
    import wandb

    with wandb.init() as run:
        data = [[label, val] for (label, val) in zip(labels, values)]
        table = wandb.Table(data=data, columns=["label", "value"])
        run.log(
            {
                "my_bar_chart_id": wandb.plot.bar(
                    table, "label", "value", title="Custom bar chart"
                )
            }
        )
    ```

    임의의 막대 차트를 로깅하는 데 이 기능을 사용할 수 있습니다. 목록의 레이블 수와 값 수가 정확히 일치해야 합니다. 각 데이터 포인트는 둘 다 있어야 합니다.

    <Frame>
      <img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/_media/basic_charts_bar.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=37dbe1f91ab27d1804a290c606dd9d00" alt="맞춤형 막대 차트" width="1286" height="552" data-path="products/wandb/_media/basic_charts_bar.png" />
    </Frame>

    자세한 내용은 [맞춤형 막대 차트](https://forge.coreweave.com/wandb/wandb/plots/reports/Custom-Bar-Charts--VmlldzoyNzExNzk) 보고서를 참조하세요.

    [코드 실행](https://tiny.cc/custom-charts)
  </Tab>

  <Tab title="히스토그램">
    몇 줄의 코드만으로 맞춤형 히스토그램(값 목록을 개수 또는 발생 빈도에 따라 구간별로 분류한 차트)을 기본 기능으로 로깅하세요. 예를 들어 예측 신뢰도 점수 목록(`scores`)이 있다면 다음과 같이 분포를 시각화할 수 있습니다.

    ```python theme={"system"}
    import wandb

    with wandb.init() as run:
        data = [[s] for s in scores]
        table = wandb.Table(data=data, columns=["scores"])
        run.log({"my_histogram": wandb.plot.histogram(table, "scores", title="Histogram")})
    ```

    임의의 히스토그램을 로깅하는 데 이 기능을 사용할 수 있습니다. `data`는 목록의 목록으로, 행과 열로 구성된 2D 배열을 지원하기 위한 것입니다.

    <Frame>
      <img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/_media/track-demo_custom_chart_histogram.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=c20f7d1cb890efde2e512d5cc6143eb1" alt="맞춤형 히스토그램" width="1252" height="558" data-path="products/wandb/_media/track-demo_custom_chart_histogram.png" />
    </Frame>

    자세한 내용은 [W\&B로 맞춤형 히스토그램 만들기](https://forge.coreweave.com/wandb/wandb/plots/reports/Custom-Histograms--VmlldzoyNzE0NzM) 보고서를 참조하세요.

    [코드 실행](https://tiny.cc/custom-charts)
  </Tab>

  <Tab title="다중 선">
    하나의 공유된 x-y 축에 여러 선을 플롯하거나, x-y 좌표 쌍의 여러 다른 목록을 플롯하세요:

    ```python theme={"system"}
    import wandb

    with wandb.init() as run:
        run.log(
            {
                "my_custom_id": wandb.plot.line_series(
                    xs=[0, 1, 2, 3, 4],
                    ys=[[10, 20, 30, 40, 50], [0.5, 11, 72, 3, 41]],
                    keys=["metric Y", "metric Z"],
                    title="Two Random Metrics",
                    xname="x units",
                )
            }
        )
    ```

    x 및 y points의 개수는 정확히 일치해야 합니다. x 값의 목록 하나를 여러 y 값 목록과 매칭하거나, 각 y 값 목록에 대해 별도의 x 값 목록을 제공할 수 있습니다.

    <Frame>
      <img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/_media/basic_charts_histogram.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=5bee2152f85b90f2fe5ddf5bfce9f96f" alt="다중 선형 플롯" width="537" height="339" data-path="products/wandb/_media/basic_charts_histogram.png" />
    </Frame>

    자세한 내용은 [Custom Multi-Line Plots](https://forge.coreweave.com/wandb/wandb/plots/reports/Custom-Multi-Line-Plots--VmlldzozOTMwMjU) report를 참조하세요.
  </Tab>
</Tabs>

<h3 id="model-evaluation-charts">
  모델 평가 차트
</h3>

이 사전 설정 차트에는 `wandb.plot()` 메서드가 내장되어 있어 스크립트에서 직접 차트를 빠르게 로깅하고 UI에서 원하는 정보를 정확하게 확인할 수 있습니다.

<Tabs>
  <Tab title="정밀도-재현율 곡선">
    한 줄로 [정밀도-재현율 곡선](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_recall_curve.html#sklearn.metrics.precision_recall_curve)을 생성하세요:

    ```python theme={"system"}
    import wandb
    with wandb.init() as run:
        # ground_truth는 정답 레이블 목록이고, predictions는 예측 점수 목록입니다.
        # 예시 ground_truth = [0, 1, 1, 0], predictions = [0.1, 0.4, 0.35, 0.8]
        ground_truth = [0, 1, 1, 0]
        predictions = [0.1, 0.4, 0.35, 0.8]
        run.log({"pr": wandb.plot.pr_curve(ground_truth, predictions)})
    ```

    코드에서 다음 항목에 액세스할 수 있다면 언제든지 이를 로깅할 수 있습니다:

    * 예시 집합에 대한 모델의 예측 점수(`predictions`).
    * 해당 예시의 정답 레이블(`ground_truth`).
    * (선택) 레이블 또는 클래스 이름의 목록. 예를 들어, 레이블 인덱스 0이 고양이, 1이 개, 2가 새를 의미한다면 `labels=["cat", "dog", "bird"]`입니다.
    * (선택) 그래프에 시각화할 레이블의 부분 집합(목록 형식 유지).

    <Frame>
      <img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/_media/model_eval_charts_precision_recall.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=777a55a1199ed206c8e76bee024bdefa" alt="정밀도-재현율 곡선" width="657" height="431" data-path="products/wandb/_media/model_eval_charts_precision_recall.png" />
    </Frame>

    자세한 내용은 [W\&B로 정밀도-재현율 곡선 그리기](https://forge.coreweave.com/wandb/wandb/plots/reports/Plot-Precision-Recall-Curves--VmlldzoyNjk1ODY) Reports를 참조하세요.

    [코드 실행하기](https://colab.research.google.com/drive/1mS8ogA3LcZWOXchfJoMrboW3opY1A8BY?usp=sharing)
  </Tab>

  <Tab title="ROC 곡선">
    한 줄로 [ROC 곡선](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html#sklearn.metrics.roc_curve)을 생성하세요:

    ```python theme={"system"}
    import wandb

    with wandb.init() as run:
        # ground_truth는 정답 레이블 목록이고, predictions는 예측 점수 목록입니다.
        # 예시: ground_truth = [0, 1, 1, 0], predictions = [0.1, 0.4, 0.35, 0.8]
        ground_truth = [0, 1, 1, 0]
        predictions = [0.1, 0.4, 0.35, 0.8]
        run.log({"roc": wandb.plot.roc_curve(ground_truth, predictions)})
    ```

    코드에서 다음 항목에 액세스할 수 있으면 언제든지 이를 로깅할 수 있습니다:

    * 예시 집합에 대한 모델의 예측 점수(`predictions`).
    * 해당 예시의 정답 레이블(`ground_truth`).
    * (선택) 레이블 또는 클래스 이름 목록. 예를 들어, 레이블 인덱스 0이 고양이, 1이 개, 2가 새를 의미한다면 `labels=["cat", "dog", "bird"]`입니다.
    * (선택) 플롯에 시각화할 레이블의 부분 집합(목록 형식 유지).

    <Frame>
      <img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/_media/track-demo_custom_chart_roc_curve.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=b05a58b72bb0501993a959f2efd3968f" alt="ROC 곡선" width="1338" height="788" data-path="products/wandb/_media/track-demo_custom_chart_roc_curve.png" />
    </Frame>

    자세한 내용은 [Plot ROC Curves With W\&B](https://forge.coreweave.com/wandb/wandb/plots/reports/Plot-ROC-Curves--VmlldzoyNjk3MDE) 보고서를 참조하세요.

    [코드 실행하기](https://colab.research.google.com/github/wandb/examples/blob/master/colabs/wandb-log/Plot_ROC_Curves_with_W%26B.ipynb)
  </Tab>

  <Tab title="혼동 행렬">
    한 줄로 다중 클래스 [혼동 행렬](https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html)을 생성하세요:

    ```python theme={"system"}
    import wandb

    cm = wandb.plot.confusion_matrix(
        y_true=ground_truth, preds=predictions, class_names=class_names
    )

    with wandb.init() as run:
        run.log({"conf_mat": cm})
    ```

    코드에서 다음 데이터에 액세스할 수 있는 곳이라면 어디서든 이를 로깅할 수 있습니다:

    * 예시 집합에 대한 모델의 예측 레이블(`preds`) 또는 정규화된 확률 점수(`probs`). 확률은 (예시 수, 클래스 수) 형태여야 합니다. 확률이나 예측 중 하나만 제공할 수 있으며, 둘 다 제공할 수는 없습니다.
    * 해당 예시의 정답 레이블(`y_true`).
    * `class_names`에 문자열로 지정된 레이블 또는 클래스 이름의 전체 목록. 예를 들어 인덱스 0이 `cat`, 1이 `dog`, 2가 `bird`라면 `class_names=["cat", "dog", "bird"]`로 지정합니다.

    <Frame>
      <img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/_media/confusion_matrix.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=8a7dd82b23c75594c5a4d1f90b11a2a0" alt="혼동 행렬" width="1070" height="422" data-path="products/wandb/_media/confusion_matrix.png" />
    </Frame>

    자세한 내용은 [혼동 행렬: 사용 및 예시](https://forge.coreweave.com/wandb/wandb/plots/reports/Confusion-Matrix--VmlldzozMDg1NTM) 보고서를 참조하세요.

    [코드 실행하기](https://colab.research.google.com/github/wandb/examples/blob/master/colabs/wandb-log/Log_a_Confusion_Matrix_with_W%26B.ipynb)
  </Tab>
</Tabs>

<h3 id="interactive-custom-charts">
  대화형 맞춤형 차트
</h3>

전체 맞춤 설정을 하려면 기본 제공 [맞춤형 차트 사전 설정](/ko/products/wandb/app/features/custom-charts/walkthrough)을 수정하거나 새 사전 설정을 만든 다음 차트를 저장하세요. 차트 ID를 사용하면 스크립트에서 해당 맞춤형 사전 설정으로 데이터를 직접 로깅할 수 있습니다.

```python theme={"system"}
import wandb
# 차트에 표시할 열로 table을 생성하세요.
table = wandb.Table(data=data, columns=["step", "height"])

# table의 열을 차트의 필드에 매핑하세요.
fields = {"x": "step", "value": "height"}

# table을 사용하여 새 맞춤형 차트 프리셋에 데이터를 채우세요.
# 직접 저장한 차트 프리셋을 사용하려면 vega_spec_name을 변경하세요.
# 제목을 수정하려면 string_fields를 변경하세요.
my_custom_chart = wandb.plot_table(
    vega_spec_name="carey/new_chart",
    data_table=table,
    fields=fields,
    string_fields={"title": "Height Histogram"},
)

with wandb.init() as run:
    # 맞춤형 차트를 로깅하세요.
    run.log({"my_custom_chart": my_custom_chart})
```

[코드 실행하기](https://tiny.cc/custom-charts)

<h3 id="matplotlib-and-plotly-plots">
  Matplotlib 및 Plotly 플롯
</h3>

`wandb.plot()`으로 W\&B [맞춤형 차트](/ko/products/wandb/app/features/custom-charts/walkthrough)를 사용하는 대신, [matplotlib](https://matplotlib.org/) 및 [Plotly](https://plotly.com/)로 생성한 차트를 로깅할 수도 있습니다.

```python theme={"system"}
import wandb
import matplotlib.pyplot as plt

with wandb.init() as run:
    # 단순한 matplotlib 플롯을 생성합니다.
    plt.figure()
    plt.plot([1, 2, 3, 4])
    plt.ylabel("some interesting numbers")

    # 플롯을 W&B에 로깅합니다.
    run.log({"chart": plt})
```

`matplotlib` 플롯 또는 figure 객체를 `wandb.Run.log()`에 전달하세요. 기본적으로 플롯을 [Plotly](https://plot.ly/) 플롯으로 변환합니다. 플롯을 이미지로 로깅하려면 `wandb.Image`에 플롯을 전달할 수 있습니다. Plotly 차트도 직접 허용합니다.

<Note>
  "You attempted to log an empty plot"와 같은 오류가 발생하면 `fig = plt.figure()`로 플롯과 별도로 figure를 저장한 다음 `wandb.Run.log()` 호출에서 `fig`를 로깅하세요.
</Note>

<h3 id="log-custom-html-to-wb-tables">
  W\&B Tables에 맞춤형 HTML 로깅하기
</h3>

W\&B에서는 Plotly와 Bokeh의 대화형 차트를 HTML로 로깅하여 Tables에 추가할 수 있습니다.

<h4 id="log-plotly-figures-to-tables-as-html">
  Plotly figure를 HTML로 Tables에 로깅하기
</h4>

대화형 Plotly 차트를 HTML로 변환하여 W\&B Tables에 로깅할 수 있습니다.

```python theme={"system"}
import wandb
import plotly.express as px

# 새 run을 초기화합니다.
with wandb.init(project="log-plotly-fig-tables", name="plotly_html") as run:

    # table을 생성합니다.
    table = wandb.Table(columns=["plotly_figure"])

    # Plotly figure의 경로를 생성합니다.
    path_to_plotly_html = "./plotly_figure.html"

    # Plotly figure 예시입니다.
    fig = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])

    # Plotly figure를 HTML로 저장합니다.
    # auto_play를 False로 설정하면 애니메이션이 있는 Plotly 차트가
    # table에서 자동으로 재생되지 않습니다.
    fig.write_html(path_to_plotly_html, auto_play=False)

    # Plotly figure를 HTML 파일로 Table에 추가합니다.
    table.add_data(wandb.Html(path_to_plotly_html))

    # table을 로깅합니다.
    run.log({"test_table": table})
```

<h4 id="log-bokeh-figures-to-tables-as-html">
  Bokeh figure를 HTML로 Tables에 로깅하기
</h4>

대화형 Bokeh 차트를 HTML로 변환하면 W\&B Tables에 로깅할 수 있습니다.

```python theme={"system"}
from scipy.signal import spectrogram
import holoviews as hv
import panel as pn
from scipy.io import wavfile
import numpy as np
from bokeh.resources import INLINE

hv.extension("bokeh", logo=False)
import wandb


def save_audio_with_bokeh_plot_to_html(audio_path, html_file_name):
    sr, wav_data = wavfile.read(audio_path)
    duration = len(wav_data) / sr
    f, t, sxx = spectrogram(wav_data, sr)
    spec_gram = hv.Image((t, f, np.log10(sxx)), ["Time (s)", "Frequency (hz)"]).opts(
        width=500, height=150, labelled=[]
    )
    audio = pn.pane.Audio(wav_data, sample_rate=sr, name="Audio", throttle=500)
    slider = pn.widgets.FloatSlider(end=duration, visible=False)
    line = hv.VLine(0).opts(color="white")
    slider.jslink(audio, value="time", bidirectional=True)
    slider.jslink(line, value="glyph.location")
    combined = pn.Row(audio, spec_gram * line, slider).save(html_file_name)


html_file_name = "audio_with_plot.html"
audio_path = "hello.wav"
save_audio_with_bokeh_plot_to_html(audio_path, html_file_name)

wandb_html = wandb.Html(html_file_name)

with wandb.init(project="audio_test") as run:
    my_table = wandb.Table(columns=["audio_with_plot"], data=[[wandb_html]])
    run.log({"audio_table": my_table})
```
