머신러닝 함수
머신러닝 함수 (Machine Learning Functions)
학습된 회귀·분류 모델로 예측하고, 텍스트를 분류하는 함수들이에요. ClickHouse에 학습/설정된 모델에 evalMLMethod 등을 적용해 새 데이터를 예측해요.
출처: 문서
본문
evalMLMethod
적합된 회귀 모델을 사용한 예측은 evalMLMethod 함수를 사용해요. linearRegression의 링크를 참고해요.
stochasticLinearRegression
stochasticLinearRegression 집계 함수는 선형 모델과 MSE 손실 함수를 사용해 확률적 경사 하강법을 구현해요. 새 데이터 예측에는 evalMLMethod를 사용해요.
stochasticLogisticRegression
stochasticLogisticRegression 집계 함수는 이진 분류 문제를 위한 확률적 경사 하강법을 구현해요. 새 데이터 예측에는 evalMLMethod를 사용해요.
naiveBayesClassifier
n-gram과 라플라스 스무딩을 사용하는 Naive Bayes 모델로 입력 텍스트를 분류해요. 사용 전에 ClickHouse에서 모델을 설정해야 해요.
구문 (Syntax)
naiveBayesClassifier(model_name, input_text);
인자 (Arguments)
model_name— 미리 설정된 모델의 이름. String 모델은 ClickHouse 설정 파일에 정의되어야 해요(아래 참고).input_text— 분류할 텍스트. String 입력은 제공된 그대로 처리돼요(대소문자·구두점 보존).
반환 값 (Returned Value)
- 예측된 클래스 ID를 부호 없는 정수로. UInt32 클래스 ID는 모델 구성 시 정의된 카테고리에 대응해요.
예시 (Example)
언어 감지 모델로 텍스트를 분류해요:
SELECT naiveBayesClassifier('language', 'How are you?');
┌─naiveBayesClassifier('language', 'How are you?')─┐
│ 0 │
└──────────────────────────────────────────────────┘
결과 0은 영어를, 1은 프랑스어를 나타낼 수 있어요 — 클래스 의미는 학습 데이터에 달려 있어요.
구현 세부 사항 (Implementation Details)
알고리즘 (Algorithm) 라플라스 스무딩을 사용한 Naive Bayes 분류 알고리즘을 사용해요. 보이지 않는 n-gram을 처리하기 위해 n-gram 확률을 바탕으로 해요. 자세한 내용은 이 자료를 참고해요.
주요 특징 (Key Features)
- 모든 크기의 n-gram 지원
- 세 가지 토큰화 모드:
byte: 원시 바이트 단위로 동작해요. 각 바이트가 하나의 토큰이에요.codepoint: UTF-8에서 디코딩된 유니코드 스칼라 값 단위로 동작해요. 각 코드포인트가 하나의 토큰이에요.token: 유니코드 공백 연속(정규식\s+)으로 나눠요. 토큰은 공백이 아닌 부분 문자열이에요. 구두점은 인접하면 토큰의 일부가 돼요(예: "you?"는 토큰 하나).
모델 구성 (Model Configuration)
언어 감지를 위한 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>
구성 매개변수 (Configuration Parameters)
| 매개변수 | 설명 | 예시 | 기본값 |
|---|---|---|---|
| name | 고유 모델 식별자 | language_detection | 필수 |
| path | 모델 바이너리의 전체 경로 | /etc/clickhouse-server/config.d/language_detection.bin | 필수 |
| mode | 토큰화 방법: - byte: 바이트 시퀀스 - codepoint: 유니코드 문자 - token: 단어 토큰 | token | 필수 |
| n | N-gram 크기(token 모드): - 1=단일 단어 - 2=단어 쌍 - 3=단어 삼중쌍 | 2 | 필수 |
| alpha | 모델에 나타나지 않는 n-gram을 처리하기 위해 분류 중 사용되는 라플라스 스무딩 계수 | 0.5 | 1.0 |
| priors | 클래스 확률(한 클래스에 속하는 문서의 % ) | 클래스 0 60%, 클래스 1 40% | 균등 분포 |
모델 학습 가이드 (Model Training Guide)
파일 형식 (File Format)
사람이 읽을 수 있는 형식에서, n=1과 token 모드의 모델은 이렇게 생길 수 있어요:
<class_id> <n-gram> <count>
0 excellent 15
1 refund 28
n=3과 codepoint 모드에서는 이렇게 생길 수 있어요:
<class_id> <n-gram> <count>
0 exc 15
1 ref 28
사람이 읽을 수 있는 형식은 ClickHouse가 직접 사용하지 않아요. 아래 설명된 이진 형식으로 변환해야 해요.
이진 형식 세부 사항 (Binary Format Details) 각 n-gram은 다음과 같이 저장돼요:
- 4바이트
class_id(UInt, 리틀엔디언) - 4바이트 n-gram 바이트 길이 (UInt, 리틀엔디언)
- 원시 n-gram 바이트
- 4바이트
count(UInt, 리틀엔디언)
전처리 요구 사항 (Preprocessing Requirements)
문서 말뭉치에서 모델을 만들기 전에, 지정된 mode와 n에 따라 n-gram을 추출하도록 문서를 전처리해야 해요. 전처리는 다음 단계로 진행돼요:
- 토큰화 모드에 따라 각 문서의 시작과 끝에 경계 마커를 추가해요:
참고: 문서의 시작과 끝 양쪽에
(n - 1)개의 토큰이 추가돼요.- byte:
0x01(시작),0xFF(끝) - codepoint:
U+10FFFE(시작),U+10FFFF(끝) - token:
<s>(시작),</s>(끝)
- byte:
- token 모드에서 n=3의 예시:
- 문서:
"ClickHouse is fast" - 처리 후:
<s> <s> ClickHouse is fast </s> </s> - 생성된 trigram:
<s> <s> ClickHouse<s> ClickHouse isClickHouse is fastis fast </s>fast </s> </s>
- 문서:
byte 및 codepoint 모드의 모델 생성을 단순화하려면, 먼저 문서를 토큰으로 토큰화하는 것이 편리할 수 있어요(byte 모드는 byte 목록, codepoint 모드는 codepoint 목록). 그런 다음 문서의 시작에 n - 1개의 시작 토큰, 끝에 n - 1개의 끝 토큰을 추가해요. 마지막으로 n-gram을 생성해 직렬화된 파일에 써요.
assignCentroid
Introduced in: v26.8.0
벡터에 가장 가까운(L2) 센트로이드의 id를 반환해요. 센트로이드는 float 배열의 상수 배열로 주어지며(그 배열에서 0부터 시작하는 위치가 id), 또는 cid와 vec 속성을 담는 Dictionary의 이름으로 주어져요(이때 id는 cid).
참고: 이 함수는 비결정적이에요. 같은 인자에 대해 다른 결과를 반환할 수 있어요.
구문 (Syntax)
assignCentroid(vec, centroids | dict_name)
인자 (Arguments)
vec— 할당할 벡터. 센트로이드와 차원이 일치해야 해요.Float32가 아닌 폭은 스코어링 커널이 사용하는Float32로 변환돼요.Array(Float32)또는Array(Float64)또는Array(BFloat16)centroids— 대조할 센트로이드로, 반드시 상수여야 해요. 크기가 같고 비어 있지 않은 float 배열의 배열로 주어지며, 그 배열에서 0부터 시작하는 위치가 id가 돼요. 또는UInt32에 맞는 부호 없는 정수 타입의cid속성과Array(Float32)타입의vec속성을 가진Dictionary의 이름으로 주어지며, 이때 id는cid예요. 딕셔너리는 한 번 읽고 다시 로드될 때까지 캐시돼요.Array(Array(Float32))또는Array(Array(Float64))또는Array(Array(BFloat16))또는String
반환 값 (Returned value)
가장 가까운 센트로이드 id. UInt32
예시 (Examples)
인라인 센트로이드 (Inline centroids)
SELECT assignCentroid([1.0, 2.0]::Array(Float32), [[0.0, 0.0], [1.0, 2.0]]::Array(Array(Float32)))
1
evalMLMethod
Introduced in: v20.1.0
학습된 머신러닝 모델을 입력 피처에 적용해 예측을 생성해요.
구문 (Syntax)
evalMLMethod(model, x1[, x2, ...])
인자 (Arguments)
model— 학습된 머신러닝 모델.AggregateFunctionStatex1, x2, ...— 예측을 위한 피처 값.Float*또는(U)Int*
반환 값 (Returned value)
학습된 모델에 기반한 예측 값을 반환해요. Float64
예시 (Examples)
사용 예 (Example usage)
CREATE TABLE trips (pickup_datetime DateTime('UTC'), trip_distance Float64, total_amount Float64) ENGINE = Memory;
-- 기본 요금 3 + 거리 단위당 2.5.
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);
-- 데이터의 연도별 모델 하나씩.
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
Introduced in: v25.11.0
NAIVE_BAYES 딕셔너리를 사용해 입력 텍스트를 분류해요. 딕셔너리의 layout에 구성된 클래스 레이블 속성 이름을 class_attribute로 하는 dictGet(dictionary_name, class_attribute, input_text)와 같은 예측 클래스 값을 반환해요. dictGet과 달리 결과 타입은 클래스 속성의 선언된 타입이 아니라 항상 UInt32이고, input_text는 반드시 String이어야 해요(키 타입 변환은 적용되지 않아요).
참고: 이 함수는 비결정적이에요. 같은 인자에 대해 다른 결과를 반환할 수 있어요.
구문 (Syntax)
naiveBayesClassifier(dictionary_name, input_text)
인자 (Arguments)
dictionary_name— NAIVE_BAYES 레이아웃의 딕셔너리 이름.Stringinput_text— 분류할 텍스트.String
반환 값 (Returned value)
예측된 클래스 ID. UInt32
예시 (Examples)
텍스트 분류 (Classify text)
-- 두 클래스의 토큰 개수로 만든 딕셔너리: 0은 긍정 리뷰, 1은 부정 리뷰.
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
Introduced in: v26.7.0
NAIVE_BAYES 딕셔너리를 사용해 입력 텍스트를 분류하고, 모든 클래스를 확률과 함께 가장 높은 확률부터 낮은 순으로 반환해요.
참고: 이 함수는 비결정적이에요. 같은 인자에 대해 다른 결과를 반환할 수 있어요.
구문 (Syntax)
naiveBayesClassifierWithAllProbs(dictionary_name, input_text)
인자 (Arguments)
dictionary_name— NAIVE_BAYES 레이아웃의 딕셔너리 이름.Stringinput_text— 분류할 텍스트.String
반환 값 (Returned value)
가장 높은 확률부터 낮은 순으로 정렬된 (class_id, probability) 튜플 배열. Array(Tuple(UInt32, Float64))
예시 (Examples)
전체 클래스 확률 (All class probabilities)
-- 두 클래스의 토큰 개수로 만든 딕셔너리: 0은 긍정 리뷰, 1은 부정 리뷰.
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
Introduced in: v26.7.0
NAIVE_BAYES 딕셔너리를 사용해 입력 텍스트를 분류하고, 예측된 클래스를 확률과 함께 반환해요.
참고: 이 함수는 비결정적이에요. 같은 인자에 대해 다른 결과를 반환할 수 있어요.
구문 (Syntax)
naiveBayesClassifierWithProb(dictionary_name, input_text)
인자 (Arguments)
dictionary_name— NAIVE_BAYES 레이아웃의 딕셔너리 이름.Stringinput_text— 분류할 텍스트.String
반환 값 (Returned value)
(class_id, probability) 튜플. Tuple(UInt32, Float64)
예시 (Examples)
확률과 함께 분류 (Classify with probability)
-- 두 클래스의 토큰 개수로 만든 딕셔너리: 0은 긍정 리뷰, 1은 부정 리뷰.
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) │
└────────────┘
더 알아보기 (Learn more)
- stochasticLinearRegression
- stochasticLogisticRegression
- ClickHouse 함수 목록 전체는 함수 개요를 참고해요.