> ## 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 Tables를 생성, 채우고 로깅하여 실험 run에서 구조화된 데이터를 시각화하고 쿼리하세요.

# table 로깅

`wandb.Table`을 사용하여 데이터를 로깅하여 W\&B로 시각화하고 쿼리하세요. 이 가이드에서 다음을 배우세요:

1. [table 생성](/ko/products/wandb/track/log/log-tables#create-tables)
2. [데이터 추가](/ko/products/wandb/track/log/log-tables#add-data)
3. [데이터 조회](/ko/products/wandb/track/log/log-tables#retrieve-data)
4. [table 저장](/ko/products/wandb/track/log/log-tables#save-tables)

<h2 id="create-tables">
  table 생성
</h2>

table을 정의하려면 각 데이터 행에 표시할 열을 지정하세요. 각 행은 트레이닝 데이터셋의 단일 항목, 트레이닝 중 특정 단계 또는 에포크, 테스트 항목에 대한 모델의 예측, 모델이 생성한 객체 등이 될 수 있습니다. 각 열에는 숫자, 텍스트, 불리언, 이미지, 비디오, 오디오 등 고정된 유형이 있습니다. 유형을 미리 지정할 필요는 없습니다. 각 열에 이름을 지정하고, 해당 열 인덱스에는 그 유형의 데이터만 전달하세요. 더 자세한 예시는 [W\&B Tables 가이드](https://forge.coreweave.com/wandb/stacey/mnist-viz/reports/Guide-to-W-B-Tables--Vmlldzo2NTAzOTk#1.-how-to-log-a-wandb.table)를 참조하세요.

`wandb.Table` 생성자는 다음 두 가지 방법 중 하나로 사용합니다.

1. **행 목록:**

   이름이 지정된 열과 데이터 행을 로깅합니다. 예를 들어 다음 코드 스니펫은 2개의 행과 3개의 열로 구성된 table을 생성합니다.

   ```python theme={"system"}
   wandb.Table(columns=["a", "b", "c"], data=[["1a", "1b", "1c"], ["2a", "2b", "2c"]])
   ```

2. **Pandas 데이터프레임:** `wandb.Table(dataframe=my_df)`를 사용하여 데이터프레임을 로깅합니다. 열 이름은 데이터프레임에서 추출됩니다.

<h4 id="from-an-existing-array-or-dataframe">
  기존 배열 또는 데이터프레임에서
</h4>

```python theme={"system"}
# 모델이 네 개의 이미지에 대한 예측을 반환했다고 가정합니다
# 다음 필드를 사용할 수 있습니다:
# - 이미지 ID
# - wandb.Image()로 래핑된 이미지 픽셀
# - 모델의 예측 레이블
# - 실제 레이블
my_data = [
    [0, wandb.Image("img_0.jpg"), 0, 0],
    [1, wandb.Image("img_1.jpg"), 8, 0],
    [2, wandb.Image("img_2.jpg"), 7, 1],
    [3, wandb.Image("img_3.jpg"), 1, 1],
]

# 해당 열로 wandb.Table()을 생성합니다
columns = ["id", "image", "prediction", "truth"]
test_table = wandb.Table(data=my_data, columns=columns)
```

<h2 id="add-data">
  데이터 추가
</h2>

table은 변경 가능합니다. 스크립트가 실행되는 동안 table에 최대 200,000행까지 더 많은 데이터를 추가할 수 있습니다. table에 데이터를 추가하는 방법에는 두 가지가 있습니다:

1. **행 추가**: `table.add_data("3a", "3b", "3c")`. 새 행은 목록으로 표현되지 않습니다. 행이 목록 형식인 경우 별표 표기 `*` 를 사용하여 목록을 위치 인수로 확장하세요: `table.add_data(*my_row_list)`. 행은 table의 열 수와 동일한 수의 항목을 포함해야 합니다.
2. **열 추가**: `table.add_column(name="col_name", data=col_data)`. `col_data`의 길이는 table의 현재 행 수와 같아야 합니다. 여기서 `col_data`는 목록 데이터 또는 NumPy NDArray일 수 있습니다.

<h3 id="adding-data-incrementally">
  데이터를 점진적으로 추가하기
</h3>

이 코드 샘플은 W\&B table을 점진적으로 생성하고 데이터를 채우는 방법을 보여줍니다. 가능한 모든 레이블의 신뢰도 점수를 포함해 미리 정의된 열로 table을 정의한 다음, 추론 중에 데이터를 한 행씩 추가합니다. [run을 재개할 때 table에 데이터를 점진적으로 추가](#adding-data-to-resumed-runs)할 수도 있습니다.

```python theme={"system"}
# 각 레이블의 신뢰도 점수를 포함하여 table의 열을 정의합니다
columns = ["id", "image", "guess", "truth"]
for digit in range(10):  # 각 숫자(0-9)의 신뢰도 점수 열을 추가합니다
    columns.append(f"score_{digit}")

# 정의한 열로 table을 초기화합니다
test_table = wandb.Table(columns=columns)

# 테스트 데이터셋을 순회하면서 table에 데이터를 한 행씩 추가합니다
# 각 행에는 이미지 ID, 이미지, 예측 레이블, 실제 레이블, 신뢰도 점수가 포함됩니다
for img_id, img in enumerate(mnist_test_data):
    true_label = mnist_test_data_labels[img_id]  # 실제 레이블
    guess_label = my_model.predict(img)  # 예측 레이블
    test_table.add_data(
        img_id, wandb.Image(img), guess_label, true_label
    )  # table에 행 데이터를 추가합니다
```

<h4 id="adding-data-to-resumed-runs">
  재개된 run에 데이터 추가
</h4>

W\&B table을 재개된 run에서 점진적으로 업데이트할 수 있습니다. 아티팩트에서 기존 table을 로드하고 마지막 데이터 행을 검색한 후 업데이트된 메트릭을 추가하세요. 그런 다음 호환성을 위해 table을 다시 초기화하고 업데이트된 버전을 W\&B에 로깅하세요.

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

# run을 초기화합니다 
with wandb.init(project="my_project") as run:

    # 아티팩트에서 기존 table을 로드합니다
    best_checkpt_table = run.use_artifact(table_tag).get(table_name)

    # 재개를 위해 table의 마지막 데이터 행을 조회합니다
    best_iter, best_metric_max, best_metric_min = best_checkpt_table.data[-1]

    # 필요에 따라 최상의 메트릭을 업데이트합니다

    # 업데이트된 데이터를 table에 추가합니다
    best_checkpt_table.add_data(best_iter, best_metric_max, best_metric_min)

    # 호환성을 위해 업데이트된 데이터로 table을 다시 초기화합니다
    best_checkpt_table = wandb.Table(
        columns=["col1", "col2", "col3"], data=best_checkpt_table.data
    )

    # run을 초기화합니다
    with wandb.init() as run:

        # 업데이트된 table을 W&B에 로깅합니다
        run.log({table_name: best_checkpt_table})
```

<h2 id="retrieve-data">
  데이터 조회
</h2>

Table에 데이터가 있으면 열 또는 행으로 액세스하세요:

1. **행 Iterator**: Table의 행 iterator(예: `for ndx, row in table.iterrows(): ...`)를 사용하여 데이터의 행을 효율적으로 반복하세요.
2. **열 조회**: `table.get_column("col_name")`을 사용하여 데이터 열을 조회하세요. 편의상 `convert_to="numpy"`를 전달하여 열을 primitives의 NumPy NDArray로 변환할 수 있습니다. 이는 열에 `wandb.Image`와 같은 media 유형이 포함된 경우 유용하며, 기본 데이터에 직접 액세스할 수 있습니다.

<h2 id="save-tables">
  table 저장하기
</h2>

스크립트에서 모델 예측 table 같은 데이터 table을 생성했다면 W\&B에 저장하여 결과를 실시간으로 시각화하세요.

<h3 id="log-a-table-to-a-run">
  run에 table 로깅하기
</h3>

다음과 같이 `wandb.Run.log()`를 사용하여 table을 run에 저장하세요:

```python theme={"system"}
with wandb.init() as run:
    my_table = wandb.Table(columns=["a", "b"], data=[["1a", "1b"], ["2a", "2b"]])
    run.log({"table_key": my_table})
```

table을 같은 키에 로깅할 때마다 table의 새 버전이 생성되어 백엔드에 저장됩니다. 따라서 같은 키에 로깅하기만 하면 여러 트레이닝 단계에 걸쳐 같은 table을 로깅하여 시간에 따른 모델 예측의 개선 과정을 확인하거나, 서로 다른 run의 table을 비교할 수 있습니다. 최대 200,000개의 행을 로깅할 수 있습니다.

<Note>
  200,000개가 넘는 행을 로깅하려면 다음과 같이 제한을 재정의할 수 있습니다:

  `wandb.Table.MAX_ARTIFACT_ROWS = X`

  하지만 이렇게 하면 UI에서 쿼리 속도가 느려지는 등의 성능 문제가 발생할 수 있습니다.
</Note>

<h3 id="access-tables-programmatically">
  프로그래밍 방식으로 table에 액세스하기
</h3>

백엔드에서 Tables는 아티팩트로 저장됩니다. 특정 버전에 액세스하려면 아티팩트 API를 사용하세요.

```python theme={"system"}
with wandb.init() as run:
    my_table = run.use_artifact("run-<run-id>-<table-name>:<tag>").get("<table-name>")
```

아티팩트에 대한 자세한 내용은 개발자 가이드의 [Artifacts 챕터](/ko/products/wandb/artifacts)를 참조하세요.

<h3 id="visualize-tables">
  table 시각화
</h3>

이 방식으로 로깅한 table은 모두 Run page와 Project page의 Workspace에 표시됩니다. 자세한 내용은 [Tables 시각화 및 분석](/ko/products/wandb/tables/visualize-tables)을 참조하세요.

<h2 id="artifact-tables">
  아티팩트 table
</h2>

`artifact.add()`를 사용하면 table을 workspace 대신 run의 Artifacts 섹션에 로깅할 수 있습니다. 한 번 로깅해 두고 이후 run에서 참조할 데이터셋이 있을 때 유용합니다.

```python theme={"system"}
with wandb.init(project="my_project") as run:
    # 의미 있는 단계마다 wandb 아티팩트를 생성합니다
    test_predictions = wandb.Artifact("mnist_test_preds", type="predictions")

    # [위와 같이 예측 데이터를 구성합니다]
    test_table = wandb.Table(data=data, columns=columns)
    test_predictions.add(test_table, "my_test_key")
    run.log_artifact(test_predictions)
```

[이미지 데이터로 artifact.add()를 사용하는 자세한 예시](https://wandb.me/dsviz-nature-colab)는 이 Colab을 참고하세요. Artifacts와 Tables를 사용해 [테이블 형식 데이터의 버전을 관리하고 중복을 제거하는 방법](https://wandb.me/TBV-Dedup)에 대한 예시는 이 Report를 참고하세요.

<h3 id="join-artifact-tables">
  아티팩트 table 조인
</h3>

`wandb.JoinedTable(table_1, table_2, join_key)`를 사용하여 로컬에서 구성한 table이나 다른 아티팩트에서 검색한 table을 조인할 수 있습니다.

| 인수 | 설명 |
| - | - |
| table\_1 | (str, `wandb.Table`, ArtifactEntry) 아티팩트 내 `wandb.Table`의 경로, table 객체 또는 ArtifactEntry |
| table\_2 | (str, `wandb.Table`, ArtifactEntry) 아티팩트 내 `wandb.Table`의 경로, table 객체 또는 ArtifactEntry |
| join\_key | (str, \[str, str]) 조인을 수행할 키 또는 키들 |

아티팩트 컨텍스트에서 이전에 로깅한 두 개의 Table을 조인하려면, 아티팩트에서 가져와서 결과를 새 Table로 조인하세요.

예를 들어, 다음 코드 예시는 `'original_songs'`라는 원본 노래 Table과 `'synth_songs'`라는 동일한 노래의 합성 버전 Table을 조회하는 방법을 보여줍니다. 코드는 두 table을 `"song_id"`에서 조인하고, 결과 table을 새 W\&B Table로 업로드합니다:

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

with wandb.init(project="my_project") as run:

    # original songs table 가져오기
    orig_songs = run.use_artifact("original_songs:latest")
    orig_table = orig_songs.get("original_samples")

    # synthesized songs table 가져오기
    synth_songs = run.use_artifact("synth_songs:latest")
    synth_table = synth_songs.get("synth_samples")

    # "song_id"를 기준으로 table 조인
    join_table = wandb.JoinedTable(orig_table, synth_table, "song_id")
    join_at = wandb.Artifact("synth_summary", "analysis")

    # table을 아티팩트에 추가하고 W&B에 로깅
    join_at.add(join_table, "synth_explore")
    run.log_artifact(join_at)
```

[이 튜토리얼 조회](https://forge.coreweave.com/wandb/stacey/cshanty/reports/Whale2Song-W-B-Tables-for-Audio--Vmlldzo4NDI3NzM)하여 서로 다른 아티팩트 객체에 저장된 이전에 저장된 두 개의 table을 결합하는 방법에 대한 예시를 확인하세요.


## Related topics

- [table 로깅하기](/ko/products/wandb/tables/log_tables.md)
