Hub documentation

SQL 작업 수행

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

SQL 작업 수행

DuckDB를 사용하여 SQL 작업을 수행하면 데이터셋을 효율적으로 쿼리할 수 있는 무한한 가능성을 열어줍니다. DuckDB 함수의 강력한 기능을 보여주는 몇 가지 예시를 살펴보겠습니다.

데모를 위해 흥미로운 데이터셋을 살펴보겠습니다. MMLU 데이터셋은 다양한 지식 영역을 아우르는 객관식 질문으로 구성된 멀티태스크 테스트입니다.

데이터셋을 미리 보기 위해 3행의 샘플을 선택해 보겠습니다:

FROM 'hf://datasets/cais/mmlu/all/test-*.parquet' USING SAMPLE 3;

┌──────────────────────┬──────────────────────┬──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬────────┐
│       question       │       subject        │                                                                         choices                                                                          │ answer │
│       varchar        │       varchar        │                                                                        varchar[]                                                                         │ int64  │
├──────────────────────┼──────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼────────┤
│ The model of light…  │ conceptual_physics   │ [wave model, particle model, Both of these, Neither of these]                                                                                            │      1 │
│ A person who is lo…  │ professional_psych…  │ [his/her life scripts., his/her own feelings, attitudes, and beliefs., the emotional reactions and behaviors of the people he/she is interacting with.…  │      1 │
│ The thermic effect…  │ nutrition            │ [is substantially higher for carbohydrate than for protein, is accompanied by a slight decrease in body core temperature., is partly related to sympat…  │      2 │
└──────────────────────┴──────────────────────┴──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴────────┘

이 명령은 데이터셋에서 3개의 무작위 샘플을 가져와 확인하도록 합니다.

데이터셋의 스키마를 살펴보는 것으로 시작해 보겠습니다. 다음 표는 데이터셋의 구조를 보여줍니다:

DESCRIBE FROM 'hf://datasets/cais/mmlu/all/test-*.parquet' USING SAMPLE 3;
┌─────────────┬─────────────┬─────────┬─────────┬─────────┬─────────┐
│ column_name │ column_type │  null   │   key   │ default │  extra  │
│   varchar   │   varchar   │ varchar │ varchar │ varchar │ varchar │
├─────────────┼─────────────┼─────────┼─────────┼─────────┼─────────┤
│ question    │ VARCHAR     │ YES     │         │         │         │
│ subject     │ VARCHAR     │ YES     │         │         │         │
│ choices     │ VARCHAR[]   │ YES     │         │         │         │
│ answer      │ BIGINT      │ YES     │         │         │         │
└─────────────┴─────────────┴─────────┴─────────┴─────────┴─────────┘

다음으로, 데이터셋에 중복된 레코드가 있는지 분석해 보겠습니다:

SELECT   *,
         COUNT(*) AS counts
FROM     'hf://datasets/cais/mmlu/all/test-*.parquet'
GROUP BY ALL
HAVING   counts > 2; 

┌──────────┬─────────┬───────────┬────────┬────────┐
│ question │ subject │  choices  │ answer │ counts │
│ varchar  │ varchar │ varchar[] │ int64  │ int64  │
├──────────┴─────────┴───────────┴────────┴────────┤
│                      0 rows                      │
└──────────────────────────────────────────────────┘

다행히도 우리의 데이터셋에는 중복된 레코드가 포함되어 있지 않습니다.

막대 그래프로 과목별 질문의 비율을 살펴보겠습니다:

SELECT 
    subject, 
    COUNT(*) AS counts, 
    BAR(COUNT(*), 0, (SELECT COUNT(*) FROM 'hf://datasets/cais/mmlu/all/test-*.parquet')) AS percentage 
FROM 
    'hf://datasets/cais/mmlu/all/test-*.parquet' 
GROUP BY 
    subject 
ORDER BY 
    counts DESC;

┌──────────────────────────────┬────────┬────────────────────────────────────────────────────────────────────────────────┐
│           subject            │ counts │                                   percentage                                   │
│           varchar            │ int64  │                                    varchar                                     │
├──────────────────────────────┼────────┼────────────────────────────────────────────────────────────────────────────────┤
│ professional_law             │   1534 │ ████████▋                                                                      │
│ moral_scenarios              │    895 │ █████                                                                          │
│ miscellaneous                │    783 │ ████▍                                                                          │
│ professional_psychology      │    612 │ ███▍                                                                           │
│ high_school_psychology       │    545 │ ███                                                                            │
│ high_school_macroeconomics   │    390 │ ██▏                                                                            │
│ elementary_mathematics       │    378 │ ██▏                                                                            │
│ moral_disputes               │    346 │ █▉                                                                             │
├──────────────────────────────┴────────┴────────────────────────────────────────────────────────────────────────────────┤
│ 57 rows (8 shown)                                                                                           3 columns  │
└────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

이제 영양과 관련된 질문을 포함하는 데이터셋의 하위 집합을 준비하고, 질문에서 정답으로의 매핑을 생성해 보겠습니다. choices 열이 있으며, answer 열을 인덱스로 사용하여 정답을 가져올 수 있다는 점에 유의하세요.

SELECT *
FROM   'hf://datasets/cais/mmlu/all/test-*.parquet'
WHERE  subject = 'nutrition' LIMIT 3;

┌──────────────────────┬───────────┬─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬────────┐
│       question       │  subject  │                                                                               choices                                                                               │ answer │
│       varchar        │  varchar  │                                                                              varchar[]                                                                              │ int64  │
├──────────────────────┼───────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼────────┤
│ Which foods tend t…  │ nutrition │ [Meat, Confectionary, Fruits and vegetables, Potatoes]                                                                                                              │      2 │
│ In which one of th…  │ nutrition │ [If the incidence rate of the disease falls., If survival time with the disease increases., If recovery of the disease is faster., If the population in which the…  │      1 │
│ Which of the follo…  │ nutrition │ [The flavonoid class comprises flavonoids and isoflavonoids., The digestibility and bioavailability of isoflavones in soya food products are not changed by proce…  │      0 │
└──────────────────────┴───────────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴────────┘
SELECT question,
       choices[answer] AS correct_answer
FROM   'hf://datasets/cais/mmlu/all/test-*.parquet'
WHERE  subject = 'nutrition' LIMIT 3;

┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬─────────────────────────────────────────────┐
│                                                              question                                                               │               correct_answer                │
│                                                               varchar                                                               │                   varchar                   │
├─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────┤
│ Which foods tend to be consumed in lower quantities in Wales and Scotland (as of 2020)?\n                                           │ Confectionary                               │
│ In which one of the following circumstances will the prevalence of a disease in the population increase, all else being constant?\n │ If the incidence rate of the disease falls. │
│ Which of the following statements is correct?\n                                                                                     │                                             │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴─────────────────────────────────────────────┘

데이터의 청결성을 보장하기 위해, 질문 끝의 개행 문자를 제거하고 빈 답변을 필터링해 보겠습니다:

SELECT regexp_replace(question, '\n', '') AS question,
       choices[answer] AS correct_answer
FROM   'hf://datasets/cais/mmlu/all/test-*.parquet'
WHERE  subject = 'nutrition' AND LENGTH(correct_answer) > 0 LIMIT 3;

┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬─────────────────────────────────────────────┐
│                                                             question                                                              │               correct_answer                │
│                                                              varchar                                                              │                   varchar                   │
├───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────┤
│ Which foods tend to be consumed in lower quantities in Wales and Scotland (as of 2020)?                                           │ Confectionary                               │
│ In which one of the following circumstances will the prevalence of a disease in the population increase, all else being constant? │ If the incidence rate of the disease falls. │
│ Which vitamin is a major lipid-soluble antioxidant in cell membranes?                                                             │ Vitamin D                                   │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴─────────────────────────────────────────────┘

마지막으로, 이 섹션에서 사용된 DuckDB 함수 중 일부를 강조하겠습니다:

  • DESCRIBE는 테이블 스키마를 반환합니다.
  • USING SAMPLE를 사용하면 데이터셋의 하위 집합을 무작위로 선택하는 데 샘플이 사용됩니다.
  • BAR은 (x - min)에 비례하는 폭을 가진 밴드를 그리며, x = max일 때 폭이 width 문자와 같도록 합니다. width의 기본값은 80입니다.
  • string[begin:end]은 슬라이스 규칙을 사용하여 문자열을 추출합니다. begin 또는 end 인수가 누락된 경우 각각 리스트의 시작 또는 끝으로 해석됩니다. 음수 값도 허용됩니다.
  • regexp_replace는 문자열에 정규식 패턴이 포함된 경우, 일치하는 부분을 replacement로 대체합니다.
  • LENGTH는 문자열의 문자 수를 가져옵니다.

DuckDB의 SQL 함수 개요에는 유용한 함수가 많이 제공됩니다. 가장 좋은 점은 Hugging Face 데이터셋에서 이 함수들을 바로 사용할 수 있다는 것입니다.

Update on GitHub