Skip to content
ClickHouse Docs
ClickHouse DocsClickHouse Docs

機械学習関数

evalMLMethod

学習済みの回帰モデルを使用した予測には、evalMLMethod 関数を使用します。詳しくは linearRegression のリンクを参照してください。

stochasticLinearRegression

stochasticLinearRegression 集約関数は、線形モデルと MSE 損失関数を用いた確率的勾配降下法を実装します。新しいデータに対する予測には evalMLMethod を使用します。

stochasticLogisticRegression

stochasticLogisticRegression 集約関数は、二値分類問題に対する確率的勾配降下法を実装します。新しいデータに対する予測には evalMLMethod を使用します。

naiveBayesClassifier

N-gram とラプラス平滑化を用いた 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-gram の確率を用い、未出現の N-gram に対応するため、ラプラス平滑化を適用した Naive Bayes 分類アルゴリズムを使用します。

主な機能

  • 任意のサイズの N-gram をサポート
  • 3 つのトークン化モード:
    • byte: 生のバイト列を対象に処理します。各バイトが 1 つのトークンになります。
    • codepoint: UTF‑8 からデコードされた Unicode スカラー値を対象に処理します。各コードポイントが 1 つのトークンになります。
    • token: Unicode の空白文字の連続 (正規表現 \s+) で分割します。トークンは空白以外の連続した部分文字列で、句読点が隣接している場合はその句読点もトークンに含まれます (例: "you?" は 1 つのトークンです) 。

モデル設定

言語検出用の Naive Bayes モデルを作成するためのサンプルソースコードは、こちらで確認できます。

さらに、サンプルモデルと関連する config ファイルはこちらで公開されています。

以下は、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: Unicode 文字
- token: 単語トークン
token 必須
n N-gram のサイズ (token モード) :
- 1=単語 1 語
- 2=単語 2 語の組
- 3=単語 3 語の組
2 必須
alpha 分類時に、モデルに現れない N-gram に対応するために使用するラプラス平滑化係数 0.5 1.0
priors クラス確率 (各クラスに属するドキュメントの割合) クラス 0 が 60%、クラス 1 が 40% 均等分布

モデル学習ガイド

ファイルフォーマット 可読形式では、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 では直接使用されず、以下で説明するバイナリ形式に変換する必要があります。

バイナリ形式の詳細 各 N-gram は、次の形式で格納されます。

  1. 4 バイトの class_id (UInt、リトルエンディアン)
  2. 4 バイトの n-gram のバイト長 (UInt、リトルエンディアン)
  3. 生の n-gram バイト列
  4. 4 バイトの count (UInt、リトルエンディアン)

前処理の要件 ドキュメントコーパスからモデルを作成する前に、指定された moden に従って N-gram を抽出できるよう、ドキュメントを前処理する必要があります。以下に、その前処理の手順を示します。

  1. トークン化モードに応じて、各ドキュメントの先頭と末尾に境界マーカーを追加します。

    • Byte: 0x01 (先頭) 、0xFF (末尾)
    • Codepoint: U+10FFFE (先頭) 、U+10FFFF (末尾)
    • Token: <s> (先頭) 、</s> (末尾)

    注: (n - 1) 個のトークンが、ドキュメントの先頭と末尾の両方に追加されます。

  2. token モードでの n=3 の例:

    • Document: "ClickHouse is fast"
    • Processed as: <s> <s> ClickHouse is fast </s> </s>
    • 生成されるトライグラム:
      • <s> <s> ClickHouse
      • <s> ClickHouse is
      • ClickHouse is fast
      • is fast </s>
      • fast </s> </s>

byte モードおよび codepoint モードでのモデル作成を簡単にするには、まず文書をトークン列に分割しておくと便利です (byte モードでは byte のリスト、codepoint モードでは codepoint のリスト) 。次に、文書の先頭に n - 1 個の開始トークンを、末尾に n - 1 個の終了トークンを追加します。最後に、N-gram を生成してシリアライズ済みファイルに書き込みます。


evalMLMethod

導入バージョン: v20.1.0

学習済みの機械学習モデルを入力された特徴量に適用し、予測を生成します。

構文

evalMLMethod(model, x1[, x2, ...])

引数

戻り値

学習済みモデルに基づいて予測された値を返します。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 Dictionary を使用して入力テキストを分類します。dictGet(dictionary_name, class_attribute, input_text) と同じ予測クラス値を返します。ここで、class_attribute は Dictionary のレイアウトで設定されたクラスラベル属性の名前です。dictGet とは異なり、戻り値の型はクラス属性の宣言型ではなく常に UInt32 であり、input_textString である必要があります (キー型変換は適用されません) 。

構文

naiveBayesClassifier(dictionary_name, input_text)

引数

  • dictionary_name — NAIVE_BAYES レイアウトの Dictionary 名。String
  • input_text — 分類対象のテキスト。String

戻り値

予測されたクラス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 Dictionaryを使用して入力テキストを分類し、すべてのクラスとその確率を、確率の高い順に返します。

構文

naiveBayesClassifierWithAllProbs(dictionary_name, input_text)

引数

  • dictionary_name — NAIVE_BAYES レイアウトを使用するDictionary名。String
  • input_text — 分類対象のテキスト。String

戻り値

確率の高い順に並んだ (class_id, probability) の Tuple からなる Array。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 Dictionary を使用して入力テキストを分類し、予測されたクラスとその確率を返します。

構文

naiveBayesClassifierWithProb(dictionary_name, input_text)

引数

  • dictionary_name — NAIVE_BAYES レイアウトを持つ Dictionary の名前。String
  • input_text — 分類対象のテキスト。String

戻り値

(class_id, probability) から成る Tuple。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) │
└────────────┘
Navigation