Skip to content

Add ngramClassify and ngramClassifyUTF8 functions#48984

Closed
0442A403 wants to merge 15 commits intoClickHouse:masterfrom
0442A403:ngram_category_distance_function
Closed

Add ngramClassify and ngramClassifyUTF8 functions#48984
0442A403 wants to merge 15 commits intoClickHouse:masterfrom
0442A403:ngram_category_distance_function

Conversation

@0442A403
Copy link
Copy Markdown
Contributor

@0442A403 0442A403 commented Apr 20, 2023

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

Add ngramClassify and ngramClassifyUTF8 functions

Documentation entry for user-facing changes

  • Documentation is written
  • Tests are written

Task is described at #42194 as "Text classification with ngram models".

This PR adds new function ngramClassify and ngramClassifyUTF8 which implements naive Bayes classifier. These functions are a easy way to classify text very quickly (sacrificing quality of course).

For example you need to find offensive comments about football and hockey then you can query:

SELECT comment_text
FROM comments
WHERE ngramClassify('offensive', comment_text) = 'positive'
AND ngramClassify('sport', comment_text) in ('football', 'hockey');

So it is based on models. In example above there are 2 models: offensive and sport. These models are based on texts that must represent all its class.
Models are configurated in config. So for query above there could be the following config:

<ngram_classifiers>
    <ngram_classifier>
        <ngram_classifier_name>offensive</ngram_classifier_name>
        <ngram_classes>
            <ngram_class>
                <ngram_class_name>positive</ngram_class_name>
                <ngram_class_path>/etc/offensive.txt</ngram_class_path>
            </ngram_class>
            <ngram_class>
                <ngram_class_name>negative</ngram_class_name>
                <ngram_class_path>/etc/non-offensive.txt</ngram_class_path>
            </ngram_class>
        </ngram_classes>
    </ngram_classifier>
    <ngram_classifier>
        <ngram_classifier_name>sport</ngram_classifier_name>
        <ngram_classes>
            <ngram_class>
                <ngram_class_name>football</ngram_class_name>
                <ngram_class_path>/etc/football.txt</ngram_class_path>
            </ngram_class>
            <ngram_class>
                <ngram_class_name>basketball</ngram_class_name>
                <ngram_class_path>/etc/backetball.txt</ngram_class_path>
            </ngram_class>
            <ngram_class>
                <ngram_class_name>hockey</ngram_class_name>
                <ngram_class_path>/etc/hockey.txt</ngram_class_path>
            </ngram_class>
            <ngram_class>
                <ngram_class_name>chess</ngram_class_name>
                <ngram_class_path>/etc/chess.txt</ngram_class_path>
            </ngram_class>
        </ngram_classes>
    </ngram_classifier>
</ngram_classifiers>

Template for configuration is located on programs/server/config.d/ngram_classifiers.xml.

In the sequal of this PR functionality can expand up to next features:

  • Loading models from the CSV file without processing it after reading
  • Dumping processed models for the purpose of previous point
  • Downloading models with FTP
  • Publications some frequently asked models on ClickHouse resources so everyone could just type ngramClassify('clickhouse.offensive', text)
  • Other Bayes classifiers (could be found here)

@CLAassistant
Copy link
Copy Markdown

CLAassistant commented Apr 20, 2023

CLA assistant check
All committers have signed the CLA.

@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-feature Pull request with new product feature label Apr 20, 2023
@qoega qoega added the can be tested Allows running workflows for external contributors label Apr 20, 2023
@rschu1ze rschu1ze self-assigned this Apr 23, 2023
@alexey-milovidov
Copy link
Copy Markdown
Member

It does not build.

@alexey-milovidov
Copy link
Copy Markdown
Member

alexey-milovidov commented Apr 24, 2023

Either I didn't understand the code, or it was not the algorithm we wanted to implement.
I thought we wanted to implement a Bayes multi-classifier, something like https://towardsdatascience.com/naive-bayes-algorithm-for-classification-bc5e98bff4d7

@alexey-milovidov alexey-milovidov marked this pull request as draft April 24, 2023 03:00
@alexey-milovidov
Copy link
Copy Markdown
Member

Missing the analysis of the algorithm (for charset or language classification).

@0442A403 0442A403 force-pushed the ngram_category_distance_function branch from c95824a to 1105d61 Compare May 22, 2023 03:03
@robot-ch-test-poll3
Copy link
Copy Markdown
Contributor

robot-ch-test-poll3 commented May 22, 2023

This is an automated comment for commit 384e073 with description of existing statuses. It's updated for the latest CI running
The full report is available here
The overall status of the commit is 🔴 failure

Check nameDescriptionStatus
AST fuzzerRuns randomly generated queries to catch program errors. The build type is optionally given in parenthesis. If it fails, ask a maintainer for help🟢 success
CI runningA meta-check that indicates the running CI. Normally, it's in success or pending state. The failed status indicates some problems with the PR🟢 success
ClickHouse build checkBuilds ClickHouse in various configurations for use in further steps. You have to fix the builds that fail. Build logs often has enough information to fix the error, but you might have to reproduce the failure locally. The cmake options can be found in the build log, grepping for cmake. Use these options and follow the general build process🟢 success
Compatibility checkChecks that clickhouse binary runs on distributions with old libc versions. If it fails, ask a maintainer for help🟢 success
Docker image for serversThe check to build and optionally push the mentioned image to docker hub🟢 success
Docs CheckBuilds and tests the documentation🟡 pending
Fast testNormally this is the first check that is ran for a PR. It builds ClickHouse and runs most of stateless functional tests, omitting some. If it fails, further checks are not started until it is fixed. Look at the report to see which tests fail, then reproduce the failure locally as described here🟢 success
Flaky testsChecks if new added or modified tests are flaky by running them repeatedly, in parallel, with more randomization. Functional tests are run 100 times with address sanitizer, and additional randomization of thread scheduling. Integrational tests are run up to 10 times. If at least once a new test has failed, or was too long, this check will be red. We don't allow flaky tests, read the doc🔴 failure
Install packagesChecks that the built packages are installable in a clear environment🟢 success
Integration testsThe integration tests report. In parenthesis the package type is given, and in square brackets are the optional part/total tests🟢 success
Mergeable CheckChecks if all other necessary checks are successful🔴 failure
Performance ComparisonMeasure changes in query performance. The performance test report is described in detail here. In square brackets are the optional part/total tests🔴 failure
Push to DockerhubThe check for building and pushing the CI related docker images to docker hub🟢 success
SQLancerFuzzing tests that detect logical bugs with SQLancer tool🟢 success
SqllogicRun clickhouse on the sqllogic test set against sqlite and checks that all statements are passed🟢 success
Stateful testsRuns stateful functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc🟢 success
Stateless testsRuns stateless functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc🔴 failure
Stress testRuns stateless functional tests concurrently from several clients to detect concurrency-related errors🔴 failure
Style CheckRuns a set of checks to keep the code style clean. If some of tests failed, see the related log from the report🟢 success
Unit testsRuns the unit tests for different release types🟢 success
Upgrade checkRuns stress tests on server version from last release and then tries to upgrade it to the version from the PR. It checks if the new server can successfully startup without any errors, crashes or sanitizer asserts🟢 success

@0442A403 0442A403 changed the title Add ngramCategoryDistance and ngramCategoryDistanceUTF8 functions Add ngramClassify and ngramClassifyUTF8 functions May 22, 2023
@0442A403 0442A403 marked this pull request as ready for review May 22, 2023 12:05
@0442A403
Copy link
Copy Markdown
Contributor Author

0442A403 commented May 22, 2023

I've done a model quality analysis. Here's results:

┌─ans──────┬───────────y_i=spam─┬─y_i=ham─┐
│ ans=spam │ 0.7058823529411765 │       0 │
└──────────┴────────────────────┴─────────┘
│ ans=ham  │0.29411764705882354 │       1 │
└──────────┴────────────────────┴─────────┘

Historically naive Bayes classificator began its development in 90s with email spam filtering. So I decided to measure quality on spam filtering.
I downloaded dataset from kaggle with over 5500 emails. I wrote simple python script to divide it to test and train data.

import numpy as np
from sklearn.model_selection import train_test_split
import pandas as pd

data = pd.read_csv('spam.csv').to_numpy()
data[:,0] = data[:,0] == 'ham'

X_train, X_test, y_train, y_test = train_test_split(data[:,1:], data[:,0], test_size=0.25, random_state=128)
y_train, y_test = y_train.astype(bool), y_test.astype(bool)

with open('spam_model_emails.txt', 'w') as file:
    for email in X_train[~y_train]:
        file.write(email[0])

with open('ham_model_emails.txt', 'w') as file:
    for email in X_train[y_train]:
        file.write(email[0])

with open('spam_pred_emails.csv', 'w') as file:
    file.write('email,\n')
    for email in X_test[~y_test]:
        file.write('"' + email[0].replace('"', '') + '",\n')

with open('ham_pred_emails.csv', 'w') as file:
    file.write('email,\n')
    for email in X_test[y_test]:
        file.write('"' + email[0].replace('"', '') + '",\n')

Then the following commands imports data:

clickhouse client -q "INSERT INTO ensure_ham FORMAT CSV" < ~/ham_pred_emails.csv  
clickhouse client -q "INSERT INTO ensure_spam FORMAT CSV" < ~/spam_pred_emails.csv

And the result:

> (
WITH
(SELECT count(*) FROM ensure_spam WHERE ngramClassify('spam', email) = 'spam') AS tp,
(SELECT count(*) FROM ensure_ham WHERE ngramClassify('spam', email) = 'spam') AS fp,
(SELECT count(*) FROM ensure_spam) as spam_count,
(SELECT count(*) FROM ensure_ham) as ham_count
SELECT 'ans=spam' AS "ans", tp / spam_count AS "y_i=spam", fp / ham_count AS "y_i=ham"
)
UNION ALL
(
WITH
(SELECT count(*) FROM ensure_spam WHERE ngramClassify('spam', email) = 'ham') AS fn,
(SELECT count(*) FROM ensure_ham WHERE ngramClassify('spam', email) = 'ham') AS tn,
(SELECT count(*) FROM ensure_spam) as spam_count,
(SELECT count(*) FROM ensure_ham) as ham_count
SELECT 'ans=ham' AS "ans", fn / spam_count AS "y_i=spam", tn / ham_count AS "y_i=ham"
);

┌─ans──────┬───────────y_i=spam─┬─y_i=ham─┐
│ ans=spam │ 0.70588235294117650 │
└──────────┴────────────────────┴─────────┘
┌─ans─────┬────────────y_i=spam─┬─y_i=ham─┐
│ ans=ham │ 0.294117647058823541 │
└─────────┴─────────────────────┴─────────┘

I think the result and especially for ham emails is very good. If invest more time in finding good model result could be much better!

@0442A403 0442A403 requested a review from alexey-milovidov May 22, 2023 19:55
@@ -0,0 +1 @@
offensive angry war violance evil adversity bad break bummer calamity cataclysm catastrophe disaster downer drag evil hard knocks hard times hardship jam misery misfortune mishap storm cloud tragedy tribulation trouble unpleasantnes No newline at end of file
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not as discussed. The model file should contain (class_id, ngram, count) triples.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants