evalMLMethod
적합된 회귀 모델을 사용한 예측에는 evalMLMethod 함수를 사용합니다. 자세한 내용은 linearRegression의 링크를 참조하십시오.
stochasticLinearRegression
stochasticLinearRegression 집계 함수는 선형 모델과 MSE 손실 함수를 사용한 확률적 경사 하강법을 구현합니다. 새 데이터 예측에는 evalMLMethod를 사용합니다.
stochasticLogisticRegression
stochasticLogisticRegression 집계 함수는 이진 분류 문제를 위한 확률적 경사 하강법을 구현합니다. 새 데이터 예측에는 evalMLMethod를 사용합니다.
naiveBayesClassifier
n-그램과 라플라스 스무딩을 사용하는 Naive Bayes 모델로 입력 텍스트를 분류합니다. 사용하기 전에 ClickHouse에서 모델을 미리 구성해야 합니다.
구문
naiveBayesClassifier(model_name, input_text);인수
model_name— 사전 구성된 모델의 이름입니다. String 모델은 ClickHouse의 설정 파일에 정의되어 있어야 합니다(아래 참고).input_text— 분류할 텍스트입니다. String 입력은 제공된 그대로 처리됩니다(대소문자와 구두점 유지).
반환 값
- 예측된 클래스 ID를 부호 없는 정수로 반환합니다. UInt32 클래스 ID는 모델 생성 시 정의된 범주에 해당합니다.
예시
언어 감지 모델을 사용해 텍스트를 분류합니다:
SELECT naiveBayesClassifier('language', 'How are you?');┌─naiveBayesClassifier('language', 'How are you?')─┐
│ 0 │
└──────────────────────────────────────────────────┘결과 0은 영어를, 1은 프랑스어를 나타낼 수 있습니다. 클래스의 의미는 학습 데이터에 따라 달라집니다.
구현 세부 사항
알고리즘 이 문서를 기반으로 한 n-그램 확률을 사용하며, 관측되지 않은 n-그램을 처리하기 위해 라플라스 스무딩을 적용한 Naive Bayes 분류 알고리즘을 사용합니다.
주요 기능
- 모든 크기의 n-그램을 지원합니다
- 세 가지 토큰화 모드:
byte: 원시 바이트 단위로 동작합니다. 각 바이트가 하나의 토큰입니다.codepoint: UTF‑8에서 디코딩된 유니코드 스칼라 값을 기준으로 동작합니다. 각 코드포인트가 하나의 토큰입니다.token: 연속된 유니코드 공백(정규식 \s+)을 기준으로 분할합니다. 토큰은 공백이 아닌 부분 문자열이며, 인접한 문장부호도 토큰에 포함됩니다(예: "you?"는 하나의 토큰입니다).
모델 구성
언어 감지를 위한 Naive Bayes 모델을 생성하는 예시 소스 코드는 여기에서 확인할 수 있습니다.
또한 예시 모델과 관련 구성 파일은 여기에서 확인할 수 있습니다.
다음은 ClickHouse에서 Naive Bayes 모델에 사용하는 예시 구성입니다:
<clickhouse>
<nb_models>
<model>
<name>sentiment</name>
<path>/etc/clickhouse-server/config.d/sentiment.bin</path>
<n>2</n>
<mode>token</mode>
<alpha>1.0</alpha>
<priors>
<prior>
<class>0</class>
<value>0.6</value>
</prior>
<prior>
<class>1</class>
<value>0.4</value>
</prior>
</priors>
</model>
</nb_models>
</clickhouse>구성 매개변수
| 매개변수 | 설명 | 예시 | 기본값 |
|---|---|---|---|
| name | 고유 모델 식별자 | language_detection |
필수 |
| path | 모델 바이너리의 전체 경로 | /etc/clickhouse-server/config.d/language_detection.bin |
필수 |
| mode | 토큰화 방식: - byte: 바이트 시퀀스- codepoint: 유니코드 문자- token: 단어 토큰 |
token |
필수 |
| n | n-그램 크기(token 모드):- 1=단일 단어- 2=단어 쌍- 3=세 단어 묶음 |
2 |
필수 |
| alpha | 분류 중 모델에 나타나지 않는 n-그램을 처리하기 위해 사용하는 라플라스 스무딩 계수 | 0.5 |
1.0 |
| priors | 클래스 확률(각 클래스에 속하는 문서 비율 %) | 클래스 0 60%, 클래스 1 40% | 균등 분포 |
모델 학습 가이드
파일 포맷
사람이 읽을 수 있는 포맷에서 n=1 및 token 모드일 때 모델은 다음과 같을 수 있습니다:
<class_id> <n-gram> <count>
0 excellent 15
1 refund 28n=3 및 codepoint 모드에서는 다음과 같이 나타날 수 있습니다:
<class_id> <n-gram> <count>
0 exc 15
1 ref 28사람이 읽을 수 있는 형식은 ClickHouse에서 직접 사용되지 않으므로, 아래에 설명된 바이너리 형식으로 변환해야 합니다.
바이너리 형식 세부 정보 각 n-그램은 다음 형식으로 저장됩니다.
- 4바이트
class_id(UInt, 리틀 엔디언) - 4바이트
n-gram바이트 길이 (UInt, 리틀 엔디언) - 원본
n-gram바이트 - 4바이트
count(UInt, 리틀 엔디언)
전처리 요구 사항
문서 코퍼스에서 모델을 생성하기 전에, 지정된 mode와 n에 따라 n-그램을 추출할 수 있도록 문서를 전처리해야 합니다. 다음 단계는 전처리 과정을 설명합니다.
-
토큰화 모드에 따라 각 문서의 시작과 끝에 경계 마커를 추가합니다.
- Byte:
0x01(시작),0xFF(끝) - Codepoint:
U+10FFFE(시작),U+10FFFF(끝) - Token:
<s>(시작),</s>(끝)
참고: 문서의 앞과 뒤에 각각
(n - 1)개의 토큰을 추가합니다. - Byte:
-
token모드에서n=3인 경우의 예시:- 문서:
"ClickHouse is fast" - 처리 결과:
<s> <s> ClickHouse is fast </s> </s> - 생성된 3-그램:
<s> <s> ClickHouse<s> ClickHouse isClickHouse is fastis fast </s>fast </s> </s>
- 문서:
byte 및 codepoint 모드에서 모델 생성을 단순화하려면, 먼저 문서를 tokens으로 분리해 두는 것이 편리할 수 있습니다(byte 모드에서는 byte 목록, codepoint 모드에서는 codepoint 목록). 그런 다음 문서 앞부분에 n - 1개의 시작 토큰을 추가하고, 문서 끝부분에 n - 1개의 종료 토큰을 추가합니다. 마지막으로 n-그램을 생성하여 직렬화된 파일에 기록합니다.
evalMLMethod
도입 버전: v20.1.0
학습된 머신러닝 모델을 입력 피처에 적용해 예측값을 생성합니다.
구문
evalMLMethod(model, x1[, x2, ...])인수
model— 학습된 머신러닝 모델입니다.AggregateFunctionStatex1, x2, ...— 예측에 사용할 특성 값입니다.Float*또는(U)Int*
반환 값
학습된 모델을 기반으로 한 예측 값을 반환합니다. Float64
예시
사용 예시
CREATE TABLE trips (pickup_datetime DateTime('UTC'), trip_distance Float64, total_amount Float64) ENGINE = Memory;
-- A fare of 3, plus 2.5 for every unit of distance.
INSERT INTO trips
SELECT toDateTime('2020-01-01 00:00:00', 'UTC') + number * 60, number % 10 + 1, 2.5 * (number % 10 + 1) + 3
FROM numbers(1000);
-- One model per year of the data.
CREATE TABLE models ENGINE = Memory AS
SELECT
toYear(pickup_datetime) AS year,
stochasticLinearRegressionState(0.01, 0.0, 10, 'SGD')(total_amount, trip_distance) AS model
FROM trips
GROUP BY year;
SELECT
trip_distance,
round(evalMLMethod(model, trip_distance), 2) AS predicted,
total_amount
FROM trips
LEFT JOIN models ON year = toYear(pickup_datetime)
ORDER BY pickup_datetime
LIMIT 5┌─trip_distance─┬─predicted─┬─total_amount─┐
│ 1 │ 4.05 │ 5.5 │
│ 2 │ 6.79 │ 8 │
│ 3 │ 9.53 │ 10.5 │
│ 4 │ 12.28 │ 13 │
│ 5 │ 15.02 │ 15.5 │
└───────────────┴───────────┴──────────────┘naiveBayesClassifier
도입 버전: v25.11.0
NAIVE_BAYES 딕셔너리를 사용해 입력 텍스트를 분류합니다. dictGet(dictionary_name, class_attribute, input_text)와 동일한 예측 클래스 값을 반환합니다. 여기서 class_attribute는 딕셔너리 레이아웃에 구성된 클래스 레이블 속성의 이름입니다. dictGet와 달리 반환 유형은 클래스 속성에 선언된 유형이 아니라 항상 UInt32이며, input_text는 반드시 String이어야 합니다(키 유형 변환은 적용되지 않습니다).
구문
naiveBayesClassifier(dictionary_name, input_text)인수
반환 값
예측된 클래스 ID입니다. UInt32
예시
텍스트 분류
-- A dictionary built from the token counts of two classes: 0 for a positive review, 1 for a negative one.
CREATE TABLE review_tokens (ngram String, class_id UInt32, count UInt64) ENGINE = Memory;
INSERT INTO review_tokens VALUES ('good', 0, 5), ('great', 0, 4), ('excellent', 0, 3), ('bad', 1, 5), ('awful', 1, 4), ('terrible', 1, 3);
CREATE DICTIONARY sentiment (ngram String, class_id UInt32 DEFAULT 0, count UInt64 DEFAULT 0)
PRIMARY KEY ngram
SOURCE(CLICKHOUSE(TABLE 'review_tokens'))
LAYOUT(NAIVE_BAYES(class_attribute 'class_id' n 1 mode 'token'))
LIFETIME(0);
SELECT naiveBayesClassifier('sentiment', 'a good and great film') AS class_id;┌─class_id─┐
│ 0 │
└──────────┘naiveBayesClassifierWithAllProbs
도입 버전: v26.7.0
NAIVE_BAYES 딕셔너리를 사용하여 입력 텍스트를 분류하고, 가장 확률이 높은 클래스부터 낮은 클래스까지 각 확률과 함께 모두 반환합니다.
구문
naiveBayesClassifierWithAllProbs(dictionary_name, input_text)인수
반환 값
확률이 높은 순서부터 낮은 순서로 정렬된 (class_id, probability) 튜플 배열입니다. Array(Tuple(UInt32, Float64))
예시
모든 클래스의 확률
-- A dictionary built from the token counts of two classes: 0 for a positive review, 1 for a negative one.
CREATE TABLE review_tokens (ngram String, class_id UInt32, count UInt64) ENGINE = Memory;
INSERT INTO review_tokens VALUES ('good', 0, 5), ('great', 0, 4), ('excellent', 0, 3), ('bad', 1, 5), ('awful', 1, 4), ('terrible', 1, 3);
CREATE DICTIONARY sentiment (ngram String, class_id UInt32 DEFAULT 0, count UInt64 DEFAULT 0)
PRIMARY KEY ngram
SOURCE(CLICKHOUSE(TABLE 'review_tokens'))
LAYOUT(NAIVE_BAYES(class_attribute 'class_id' n 1 mode 'token'))
LIFETIME(0);
SELECT arrayMap(p -> (p.1, round(p.2, 4)), naiveBayesClassifierWithAllProbs('sentiment', 'a good and great film')) AS predictions;┌─predictions─────────────┐
│ [(0,0.9677),(1,0.0323)] │
└─────────────────────────┘naiveBayesClassifierWithProb
도입 버전: v26.7.0
NAIVE_BAYES 딕셔너리를 사용해 입력 텍스트를 분류하고, 예측된 클래스와 해당 확률을 반환합니다.
구문
naiveBayesClassifierWithProb(dictionary_name, input_text)인수
반환 값
(class_id, probability) 형태의 튜플입니다. Tuple(UInt32, Float64)
예시
확률과 함께 분류하기
-- A dictionary built from the token counts of two classes: 0 for a positive review, 1 for a negative one.
CREATE TABLE review_tokens (ngram String, class_id UInt32, count UInt64) ENGINE = Memory;
INSERT INTO review_tokens VALUES ('good', 0, 5), ('great', 0, 4), ('excellent', 0, 3), ('bad', 1, 5), ('awful', 1, 4), ('terrible', 1, 3);
CREATE DICTIONARY sentiment (ngram String, class_id UInt32 DEFAULT 0, count UInt64 DEFAULT 0)
PRIMARY KEY ngram
SOURCE(CLICKHOUSE(TABLE 'review_tokens'))
LAYOUT(NAIVE_BAYES(class_attribute 'class_id' n 1 mode 'token'))
LIFETIME(0);
WITH naiveBayesClassifierWithProb('sentiment', 'a good and great film') AS p
SELECT (p.1, round(p.2, 4)) AS prediction;┌─prediction─┐
│ (0,0.9677) │
└────────────┘