提交 533750ef 编写于 作者: B BayoNet 提交者: Ivan Blinkov

DOCAPI-6985: RU translations for some articles. (#5572)

上级 eb1fe2ed
......@@ -393,14 +393,16 @@ SELECT kurtSamp(value) FROM series_with_value_column
```
## timeSeriesGroupSum(uid, timestamp, value) {#agg_function-timeseriesgroupsum}
timeSeriesGroupSum can aggregate different time series that sample timestamp not alignment.
`timeSeriesGroupSum` can aggregate different time series that sample timestamp not alignment.
It will use linear interpolation between two sample timestamp and then sum time-series together.
`uid` is the time series unique id, UInt64.
`timestamp` is Int64 type in order to support millisecond or microsecond.
`value` is the metric.
- `uid` is the time series unique id, `UInt64`.
- `timestamp` is Int64 type in order to support millisecond or microsecond.
- `value` is the metric.
Before use this function, timestamp should be in ascend order
The function returns array of tuples with `(timestamp, aggregated_value)` pairs.
Before using this function make sure `timestamp` is in ascending order.
Example:
```
......@@ -708,15 +710,12 @@ SELECT arrayReduce('simpleLinearRegression', [0, 1, 2, 3], [3, 4, 5, 6])
└───────────────────────────────────────────────────────────────────┘
```
## linearRegression
## stochasticLinearRegression {#agg_functions-stochasticlinearregression}
This function implements stochastic linear regression. It supports custom parameters for learning rate, L2 regularization coefficient,
mini-batch size and has few methods for updating weights (simple SGD, Momentum, Nesterov).
This function works as a usual aggregate function in terms of distributed processing of data, which is followed by merges. With regard to `linearRegression` this means that different aggregate function states are merged with weights - the more data was processed by a state, the bigger weight it has during a merge with other state.
This function implements stochastic linear regression. It supports custom parameters for learning rate, L2 regularization coefficient, mini-batch size and has few methods for updating weights ([simple SGD](https://en.wikipedia.org/wiki/Stochastic_gradient_descent), [Momentum](https://en.wikipedia.org/wiki/Stochastic_gradient_descent#Momentum), [Nesterov](https://mipt.ru/upload/medialibrary/d7e/41-91.pdf)).
#### Parameters
### Parameters {#agg_functions-stochasticlinearregression-parameters}
There are 4 customizable parameters. They are passed to the function sequentially, but there is no need to pass all four - default values will be used, however good model required some parameter tuning.
......@@ -730,14 +729,16 @@ stochasticLinearRegression(1.0, 1.0, 10, 'SGD')
4. `method for updating weights`, there are 3 of them: `SGD`, `Momentum`, `Nesterov`. `Momentum` and `Nesterov` require little bit more computations and memory, however they happen to be useful in terms of speed of convergance and stability of stochastic gradient methods. Default is `'SGD'`.
**Usage of linearRegression**
### Usage {#agg_functions-stochasticlinearregression-usage}
`stochasticLinearRegression` is used in two steps: fitting the model and predicting on new data. In order to fit the model and save its state for later usage we use `-State` combinator, which basically saves the state (model weights, etc).
To predict we use function `evalMLMethod`, which takes a state as an argument as well as features to predict on.
To predict we use function [evalMLMethod](../functions/machine_learning_functions.md#machine_learning_methods-evalmlmethod), which takes a state as an argument as well as features to predict on.
1. *Fitting*
<a name="stochasticlinearregression-usage-fitting"></a>
1. Fitting
Such query may be used.
```sql
CREATE TABLE IF NOT EXISTS train_data
(
......@@ -751,21 +752,24 @@ To predict we use function `evalMLMethod`, which takes a state as an argument as
AS state FROM train_data;
```
Here we also need to insert data into `train_data` table. The number of parameters is not fixed, it depends only on number of arguments, passed into `linearRegressionState`. They all must be numeric values.
Note that the column with target value(which we would like to learn to predict) is inserted as the first argument.
2. *Predicting*
2. Predicting
After saving a state into the table, we may use it multiple times for prediction, or even merge with other states and create new even better models.
```sql
WITH (SELECT state FROM your_model) AS model SELECT
evalMLMethod(model, param1, param2) FROM test_data
```
The query will return a column of predicted values. Note that first argument of `evalMLMethod` is `AggregateFunctionState` object, next are columns of features.
`test_data` is a table like `train_data` but may not contain target value.
**Some notes**
### Notes {#agg_functions-stochasticlinearregression-notes}
1. To merge two models user may create such query:
```sql
......@@ -779,44 +783,60 @@ To predict we use function `evalMLMethod`, which takes a state as an argument as
```
Such query will fit the model and return its weights - first are weights, which correspond to the parameters of the model, the last one is bias. So in the example above the query will return a column with 3 values.
**See Also**
- [stochasticLogisticRegression](#agg_functions-stochasticlogisticregression)
- [Difference between linear and logistic regressions](https://stackoverflow.com/questions/12146914/what-is-the-difference-between-linear-regression-and-logistic-regression)
## logisticRegression
## stochasticLogisticRegression {#agg_functions-stochasticlogisticregression}
This function implements stochastic logistic regression. It can be used for binary classification problem, supports the same custom parameters as stochasticLinearRegression and works the same way.
#### Parameters
### Parameters {#agg_functions-stochasticlogisticregression-parameters}
Parameters are exactly the same as in stochasticLinearRegression:
`learning rate`, `l2 regularization coefficient`, `mini-batch size`, `method for updating weights`.
For more information see [parameters](#parameters).
For more information see [parameters](#agg_functions-stochasticlinearregression-parameters).
```text
stochasticLogisticRegression(1.0, 1.0, 10, 'SGD')
```
1. *Fitting*
1. Fitting
See the `Fitting` section in the [stochasticLinearRegression](#stochasticlinearregression-usage-fitting) description.
See *stochasticLinearRegression.Fitting*
Predicted labels have to be in [-1, 1].
Predicted labels have to be in {-1, 1}.
2. Predicting
2. *Predicting*
Using saved state we can predict probability of object having label `1`.
Using saved state we can predict probability of object having label *1*.
```sql
WITH (SELECT state FROM your_model) AS model SELECT
evalMLMethod(model, param1, param2) FROM test_data
```
The query will return a column of probabilities. Note that first argument of `evalMLMethod` is `AggregateFunctionState` object, next are columns of features.
We can also set a bound of probability, which assigns elements to different labels.
```sql
SELECT ans < 1.1 AND ans > 0.5 FROM
(WITH (SELECT state FROM your_model) AS model SELECT
evalMLMethod(model, param1, param2) AS ans FROM test_data)
```
Then the result will be labels.
`test_data` is a table like `train_data` but may not contain target value.
**See Also**
- [stochasticLinearRegression](#agg_functions-stochasticlinearregression)
- [Difference between linear and logistic regressions.](https://stackoverflow.com/questions/12146914/what-is-the-difference-between-linear-regression-and-logistic-regression)
[Original article](https://clickhouse.yandex/docs/en/query_language/agg_functions/reference/) <!--hide-->
......@@ -458,7 +458,7 @@ SELECT arraySlice([1, 2, NULL, 4, 5], 2, 3) AS res
Array elements set to `NULL` are handled as normal values.
## arraySort(\[func,\] arr, ...) {#array_functions-reverse-sort}
## arraySort(\[func,\] arr, ...) {#array_functions-sort}
Sorts the elements of the `arr` array in ascending order. If the `func` function is specified, sorting order is determined by the result of the `func` function applied to the elements of the array. If `func` accepts multiple arguments, the `arraySort` function is passed several arrays that the arguments of `func` will correspond to. Detailed examples are shown at the end of `arraySort` description.
......@@ -513,7 +513,7 @@ SELECT arraySort((x) -> -x, [1, 2, 3]) as res;
└─────────┘
```
For each element of the source array, the lambda function returns the sorting key, that is, [1 –> -1, 2 –> -2, 3 –> -3]. Since the `arraySort` function sorts the keys in ascending order, the result is [3, 2, 1]. Thus, the `(x) –> -x` lambda function sets the [descending order](#array_functions-reverse-sort) in a sorting.
For each element of the source array, the lambda function returns the sorting key, that is, [1 –> -1, 2 –> -2, 3 –> -3]. Since the `arraySort` function sorts the keys in ascending order, the result is [3, 2, 1]. Thus, the `(x) –> -x` lambda function sets the [descending order](#array_functions-reverse-sort) in a sorting.
The lambda function can accept multiple arguments. In this case, you need to pass the `arraySort` function several arrays of identical length that the arguments of lambda function will correspond to. The resulting array will consist of elements from the first input array; elements from the next input array(s) specify the sorting keys. For example:
......@@ -579,7 +579,7 @@ SELECT arrayReverseSort(['hello', 'world', '!']);
```
Consider the following sorting order for the `NULL`, `NaN` and `Inf` values:
``` sql
SELECT arrayReverseSort([1, nan, 2, NULL, 3, nan, -4, NULL, inf, -inf]) as res;
```
......@@ -609,7 +609,7 @@ The array is sorted in the following way:
1. At first, the source array ([1, 2, 3]) is sorted according to the result of the lambda function applied to the elements of the array. The result is an array [3, 2, 1].
2. Array that is obtained on the previous step, is reversed. So, the final result is [1, 2, 3].
The lambda function can accept multiple arguments. In this case, you need to pass the `arrayReverseSort` function several arrays of identical length that the arguments of lambda function will correspond to. The resulting array will consist of elements from the first input array; elements from the next input array(s) specify the sorting keys. For example:
``` sql
......@@ -625,8 +625,8 @@ In this example, the array is sorted in the following way:
1. At first, the source array (['hello', 'world']) is sorted according to the result of the lambda function applied to the elements of the arrays. The elements that are passed in the second array ([2, 1]), define the sorting keys for corresponding elements from the source array. The result is an array ['world', 'hello'].
2. Array that was sorted on the previous step, is reversed. So, the final result is ['hello', 'world'].
Other examples are shown below.
Other examples are shown below.
``` sql
SELECT arrayReverseSort((x, y) -> y, [4, 3, 5], ['a', 'b', 'c']) AS res;
......
......@@ -76,6 +76,8 @@ select JSONHas('{"a": "hello", "b": [-100, 200.0, 300]}', 'b', 4) = 0
* Positive integer = access the n-th member/key from the beginning.
* Negative integer = access the n-th member/key from the end.
Minimum index of the element is 1. Thus the element 0 doesn't exist.
You may use integers to access both JSON arrays and JSON objects.
So, for example:
......
# Machine learning methods
## evalMLMethod (prediction) {#machine_learning_methods-evalmlmethod}
Prediction using fitted regression models uses `evalMLMethod` function. See link in `linearRegression`.
### Stochastic Linear Regression
The [stochasticLinearRegression](../agg_functions/reference.md#agg_functions-stochasticlinearregression) aggregate function implements stochastic gradient descent method using linear model and MSE loss function. Uses `evalMLMethod` to predict on new data.
### Stochastic Logistic Regression
The [stochasticLogisticRegression](../agg_functions/reference.md#agg_functions-stochasticlogisticregression) aggregate function implements stochastic gradient descent method for binary classification problem. Uses `evalMLMethod` to predict on new data.
# Machine learning methods
## evalMLMethod (prediction)
Prediction using fitted regression models uses `evalMLMethod` function. See link in `linearRegression`.
## Stochastic Linear Regression
`stochasticLinearRegression` aggregate function implements stochastic gradient descent method using linear model and MSE loss function. Uses `evalMLMethod` to predict on new data.
See examples and notes [here](../agg_functions/reference.md#linearregression).
## Stochastic Logistic Regression
`stochasticLogisticRegression` aggregate function implements stochastic gradient descent method for binary classification problem. Uses `evalMLMethod` to predict on new data.
See examples and notes [here](../agg_functions/reference.md#logisticregression).
\ No newline at end of file
../../../en/operations/settings/constraints_on_settings.md
\ No newline at end of file
../../../en/query_language/functions/machine_learning_functions.md
\ No newline at end of file
../../../en/data_types/domains/ipv4.md
\ No newline at end of file
## IPv4
`IPv4` — это домен, базирующийся на типе данных `UInt32` предназначенный для хранения адресов IPv4. Он обеспечивает компактное хранение данных с удобным для человека форматом ввода-вывода, и явно отображаемым типом данных в структуре таблицы.
### Применение
```sql
CREATE TABLE hits (url String, from IPv4) ENGINE = MergeTree() ORDER BY url;
DESCRIBE TABLE hits;
```
```
┌─name─┬─type───┬─default_type─┬─default_expression─┬─comment─┬─codec_expression─┐
│ url │ String │ │ │ │ │
│ from │ IPv4 │ │ │ │ │
└──────┴────────┴──────────────┴────────────────────┴─────────┴──────────────────┘
```
Или вы можете использовать домен IPv4 в качестве ключа:
```sql
CREATE TABLE hits (url String, from IPv4) ENGINE = MergeTree() ORDER BY from;
```
`IPv4` поддерживает вставку в виде строк с текстовым представлением IPv4 адреса:
```sql
INSERT INTO hits (url, from) VALUES ('https://wikipedia.org', '116.253.40.133')('https://clickhouse.yandex', '183.247.232.58')('https://clickhouse.yandex/docs/en/', '116.106.34.242');
SELECT * FROM hits;
```
```
┌─url────────────────────────────────┬───────────from─┐
│ https://clickhouse.yandex/docs/en/ │ 116.106.34.242 │
│ https://wikipedia.org │ 116.253.40.133 │
│ https://clickhouse.yandex │ 183.247.232.58 │
└────────────────────────────────────┴────────────────┘
```
Значения хранятся в компактной бинарной форме:
```sql
SELECT toTypeName(from), hex(from) FROM hits LIMIT 1;
```
```
┌─toTypeName(from)─┬─hex(from)─┐
│ IPv4 │ B7F7E83A │
└──────────────────┴───────────┘
```
Значения с доменным типом данных не преобразуются неявно в другие типы данных, кроме `UInt32`.
Если необходимо преобразовать значение типа `IPv4` в строку, то это необходимо делать явно с помощью функции `IPv4NumToString()`:
```sql
SELECT toTypeName(s), IPv4NumToString(from) AS s FROM hits LIMIT 1;
```
```
┌─toTypeName(IPv4NumToString(from))─┬─s──────────────┐
│ String │ 183.247.232.58 │
└───────────────────────────────────┴────────────────┘
```
Или приводить к типу данных `UInt32`:
```sql
SELECT toTypeName(i), CAST(from AS UInt32) AS i FROM hits LIMIT 1;
```
```
┌─toTypeName(CAST(from, 'UInt32'))─┬──────────i─┐
│ UInt32 │ 3086477370 │
└──────────────────────────────────┴────────────┘
```
[Оригинальная статья](https://clickhouse.yandex/docs/ru/data_types/domains/ipv4) <!--hide-->
../../../en/data_types/domains/ipv6.md
\ No newline at end of file
## IPv6
`IPv6` — это домен, базирующийся на типе данных `FixedString(16)`, предназначенный для хранения адресов IPv6. Он обеспечивает компактное хранение данных с удобным для человека форматом ввода-вывода, и явно отображаемым типом данных в структуре таблицы.
### Применение
```sql
CREATE TABLE hits (url String, from IPv6) ENGINE = MergeTree() ORDER BY url;
DESCRIBE TABLE hits;
```
```
┌─name─┬─type───┬─default_type─┬─default_expression─┬─comment─┬─codec_expression─┐
│ url │ String │ │ │ │ │
│ from │ IPv6 │ │ │ │ │
└──────┴────────┴──────────────┴────────────────────┴─────────┴──────────────────┘
```
Или вы можете использовать домен `IPv6` в качестве ключа:
```sql
CREATE TABLE hits (url String, from IPv6) ENGINE = MergeTree() ORDER BY from;
```
`IPv6` поддерживает вставку в виде строк с текстовым представлением IPv6 адреса:
```sql
INSERT INTO hits (url, from) VALUES ('https://wikipedia.org', '2a02:aa08:e000:3100::2')('https://clickhouse.yandex', '2001:44c8:129:2632:33:0:252:2')('https://clickhouse.yandex/docs/en/', '2a02:e980:1e::1');
SELECT * FROM hits;
```
```
┌─url────────────────────────────────┬─from──────────────────────────┐
│ https://clickhouse.yandex │ 2001:44c8:129:2632:33:0:252:2 │
│ https://clickhouse.yandex/docs/en/ │ 2a02:e980:1e::1 │
│ https://wikipedia.org │ 2a02:aa08:e000:3100::2 │
└────────────────────────────────────┴───────────────────────────────┘
```
Значения хранятся в компактной бинарной форме:
```sql
SELECT toTypeName(from), hex(from) FROM hits LIMIT 1;
```
```
┌─toTypeName(from)─┬─hex(from)────────────────────────┐
│ IPv6 │ 200144C8012926320033000002520002 │
└──────────────────┴──────────────────────────────────┘
```
Значения с доменным типом данных не преобразуются неявно в другие типы данных, кроме `FixedString(16)`.
Если необходимо преобразовать значение типа `IPv6` в строку, то это необходимо делать явно с помощью функции `IPv6NumToString()`:
```sql
SELECT toTypeName(s), IPv6NumToString(from) AS s FROM hits LIMIT 1;
```
```
┌─toTypeName(IPv6NumToString(from))─┬─s─────────────────────────────┐
│ String │ 2001:44c8:129:2632:33:0:252:2 │
└───────────────────────────────────┴───────────────────────────────┘
```
Или приводить к типу данных `FixedString(16)`:
```sql
SELECT toTypeName(i), CAST(from AS FixedString(16)) AS i FROM hits LIMIT 1;
```
```
┌─toTypeName(CAST(from, 'FixedString(16)'))─┬─i───────┐
│ FixedString(16) │ ��� │
└───────────────────────────────────────────┴─────────┘
```
[Оригинальная статья](https://clickhouse.yandex/docs/ru/data_types/domains/ipv6) <!--hide-->
../../../en/data_types/domains/overview.md
\ No newline at end of file
# Домены
Домены — это типы данных специального назначения, которые добавляют некоторые дополнительные функции поверх существующего базового типа. На данный момент ClickHouse не поддерживает пользовательские домены.
Вы можете использовать домены везде, где можно использовать соответствующий базовый тип:
* Создание столбца с доменным типом данных.
* Чтение/запись значений из/в столбец с доменным типом данных.
* Используйте его как индекс, если базовый тип можно использовать в качестве индекса.
* Вызов функций со значениями столбца, имеющего доменный тип данных.
* и так далее.
### Дополнительные возможности доменов
* Явное название типа данных столбца в запросах `SHOW CREATE TABLE` и `DESCRIBE TABLE`
* Ввод данных в удобном человеку формате `INSERT INTO domain_table(domain_column) VALUES(...)`
* Вывод данных в удобном человеку формате `SELECT domain_column FROM domain_table`
* Загрузка данных из внешнего источника в удобном для человека формате: `INSERT INTO domain_table FORMAT CSV ...`
### Ограничения
* Невозможно преобразовать базовый тип данных в доменный для индексного столбца с помощью `ALTER TABLE`.
* Невозможно неявно преобразовывать строковые значение в значения с доменным типом данных при вставке данных из другого столбца или таблицы.
* Домен не добавляет ограничения на хранимые значения.
[Оригинальная статья](https://clickhouse.yandex/docs/ru/data_types/domains/overview) <!--hide-->
......@@ -60,7 +60,7 @@ windowFunnel(window)(timestamp, cond1, cond2, cond3, ...)
**Параметры**
- `window` — ширина скользящего окна по времени в секундах.
- `timestamp` — имя столбца, содержащего отметки времени. Тип данных [DateTime](../../data_types/datetime.md#data_type-datetime) или [UInt32](../../data_types/int_uint.md).
- `timestamp` — имя столбца, содержащего отметки времени. Тип данных [Date](../../data_types/date.md), [DateTime](../../data_types/datetime.md#data_type-datetime) или [UInt*](../../data_types/int_uint.md). Заметьте, что в случает хранения меток времени в столбцах с типом `UInt64`, максимально допустимое значение соответствует ограничению для типа `Int64`, т.е. равно `2^63-1`.
- `cond1`, `cond2`... — условия или данные, описывающие цепочку событий. Тип данных — `UInt8`. Значения могут быть 0 или 1.
**Алгоритм**
......
# Справочник функций
## count() {#agg_function-count}
......@@ -260,6 +259,69 @@ GROUP BY timeslot
└─────────────────────┴──────────────────────────────────────────────┘
```
## timeSeriesGroupSum(uid, timestamp, value) {#agg_function-timeseriesgroupsum}
`timeSeriesGroupSum` агрегирует временные ряды в которых не совпадают моменты.
Функция использует линейную интерполяцию между двумя значениями времени, а затем суммирует значения для одного и того же момента (как измеренные так и интерполированные) по всем рядам.
- `uid` уникальный идентификатор временного ряда, `UInt64`.
- `timestamp` имеет тип `Int64` чтобы можно было учитывать милли и микросекунды.
- `value` представляет собой значение метрики.
Функция возвращает массив кортежей с парами `(timestamp, aggregated_value)`.
Временные ряды должны быть отсортированы по возрастанию `timestamp`.
Пример:
```
┌─uid─┬─timestamp─┬─value─┐
│ 1 │ 2 │ 0.2 │
│ 1 │ 7 │ 0.7 │
│ 1 │ 12 │ 1.2 │
│ 1 │ 17 │ 1.7 │
│ 1 │ 25 │ 2.5 │
│ 2 │ 3 │ 0.6 │
│ 2 │ 8 │ 1.6 │
│ 2 │ 12 │ 2.4 │
│ 2 │ 18 │ 3.6 │
│ 2 │ 24 │ 4.8 │
└─────┴───────────┴───────┘
```
```
CREATE TABLE time_series(
uid UInt64,
timestamp Int64,
value Float64
) ENGINE = Memory;
INSERT INTO time_series VALUES
(1,2,0.2),(1,7,0.7),(1,12,1.2),(1,17,1.7),(1,25,2.5),
(2,3,0.6),(2,8,1.6),(2,12,2.4),(2,18,3.6),(2,24,4.8);
SELECT timeSeriesGroupSum(uid, timestamp, value)
FROM (
SELECT * FROM time_series order by timestamp ASC
);
```
И результат будет:
```
[(2,0.2),(3,0.9),(7,2.1),(8,2.4),(12,3.6),(17,5.1),(18,5.4),(24,7.2),(25,2.5)]
```
## timeSeriesGroupRateSum(uid, ts, val) {#agg_function-timeseriesgroupratesum}
Аналогично timeSeriesGroupRateSum, timeSeriesGroupRateSum будет вычислять производные по timestamp для рядов, а затем суммировать полученные производные для всех рядов для одного значения timestamp.
Также ряды должны быть отсотированы по возрастанию timestamp.
Для пример из описания timeSeriesGroupRateSum результат будет следующим:
```
[(2,0),(3,0.1),(7,0.3),(8,0.3),(12,0.3),(17,0.3),(18,0.3),(24,0.3),(25,0.1)]
```
## avg(x) {#agg_function-avg}
Вычисляет среднее.
......@@ -482,4 +544,171 @@ FROM ontime
Вычисляет коэффициент корреляции Пирсона: `Σ((x - x̅)(y - y̅)) / sqrt(Σ((x - x̅)^2) * Σ((y - y̅)^2))`.
## simpleLinearRegression
Выполняет простую (одномерную) линейную регрессию.
```
simpleLinearRegression(x, y)
```
Параметры:
- `x` — Столбец со значениями зависимой переменной.
- `y` — столбец со значениями наблюдаемой переменной.
Возвращаемые значения:
Параметры `(a, b)` результирующей прямой `x = a*y + b`.
**Примеры**
```sql
SELECT arrayReduce('simpleLinearRegression', [0, 1, 2, 3], [0, 1, 2, 3])
```
```text
┌─arrayReduce('simpleLinearRegression', [0, 1, 2, 3], [0, 1, 2, 3])─┐
│ (1,0) │
└───────────────────────────────────────────────────────────────────┘
```
```sql
SELECT arrayReduce('simpleLinearRegression', [0, 1, 2, 3], [3, 4, 5, 6])
```
```text
┌─arrayReduce('simpleLinearRegression', [0, 1, 2, 3], [3, 4, 5, 6])─┐
│ (1,3) │
└───────────────────────────────────────────────────────────────────┘
```
## stochasticLinearRegression {#agg_functions-stochasticlinearregression}
Функция реализует стохастическую линейную регрессию. Поддерживает пользовательские параметры для скорости обучения, коэффициента регуляризации L2, размера mini-batch и имеет несколько методов обновления весов ([simple SGD](https://en.wikipedia.org/wiki/Stochastic_gradient_descent), [Momentum](https://en.wikipedia.org/wiki/Stochastic_gradient_descent#Momentum), [Nesterov](https://mipt.ru/upload/medialibrary/d7e/41-91.pdf)).
### Параметры {#agg_functions-stochasticlinearregression-parameters}
Есть 4 настраиваемых параметра. Они передаются в функцию последовательно, однако не обязательно указывать все, используются значения по умолчанию, однако хорошая модель требует некоторой настройки параметров.
```text
stochasticLinearRegression(1.0, 1.0, 10, 'SGD')
```
1. Скорость обучения — коэффициент длины шага, при выполнении градиентного спуска. Слишком большая скорость обучения может привести к бесконечным весам модели. По умолчанию `0.00001`.
2. Коэффициент регуляризации l2. Помогает предотвратить подгонку. По умолчанию `0.1`.
3. Размер mini-batch задаёт количество элементов, чьи градиенты будут вычислены и просуммированы при выполнении одного шага градиентного спуска. Чистый стохастический спуск использует один элемент, однако использование mini-batch (около 10 элементов) делает градиентные шаги более стабильными. По умолчанию `15`.
4. Метод обновления весов, можно выбрать один из следующих: `SGD`, `Momentum`, `Nesterov`. `Momentum` и `Nesterov` более требовательные к вычислительным ресурсам и памяти, однако они имеют высокую скорость схождения и остальные методы стохастического градиента. По умолчанию `SGD`.
### Использование {#agg_functions-stochasticlinearregression-usage}
`stochasticLinearRegression` используется на двух этапах: постоение модели и предсказание новых данных. Чтобы постоить модель и сохранить её состояние для дальнейшего использования, мы используем комбинатор `-State`.
Для прогнозирования мы используем функцию [evalMLMethod](../functions/machine_learning_functions.md#machine_learning_methods-evalmlmethod), которая принимает в качестве аргументов состояние и свойства для прогнозирования.
<a name="stochasticlinearregression-usage-fitting"></a>
1. Построение модели
Пример запроса:
```sql
CREATE TABLE IF NOT EXISTS train_data
(
param1 Float64,
param2 Float64,
target Float64
) ENGINE = Memory;
CREATE TABLE your_model ENGINE = Memory AS SELECT
stochasticLinearRegressionState(0.1, 0.0, 5, 'SGD')(target, param1, param2)
AS state FROM train_data;
```
Здесь нам также нужно вставить данные в таблицу `train_data`. Количество параметров не фиксировано, оно зависит только от количества аргументов, перешедших в `linearRegressionState`. Все они должны быть числовыми значениями.
Обратите внимание, что столбец с целевым значением (которое мы хотели бы научиться предсказывать) вставляется в качестве первого аргумента.
2. Прогнозирование
После сохранения состояния в таблице мы можем использовать его несколько раз для прогнозирования или смёржить с другими состояниями и создать новые, улучшенные модели.
```sql
WITH (SELECT state FROM your_model) AS model SELECT
evalMLMethod(model, param1, param2) FROM test_data
```
Запрос возвращает столбец прогнозируемых значений. Обратите внимание, что первый аргумент `evalMLMethod` это объект `AggregateFunctionState`, далее идут столбцы свойств.
`test_data` — это таблица, подобная `train_data`, но при этом может не содержать целевое значение.
### Примечания {#agg_functions-stochasticlinearregression-notes}
1. Объединить две модели можно следующим запросом:
```sql
SELECT state1 + state2 FROM your_models
```
где таблица `your_models` содержит обе модели. Запрос вернёт новый объект `AggregateFunctionState`.
2. Пользователь может получать веса созданной модели для своих целей без сохранения модели, если не использовать комбинатор `-State`.
```sql
SELECT stochasticLinearRegression(0.01)(target, param1, param2) FROM train_data
```
Подобный запрос строит модель и возвращает её веса, отвечающие параметрам моделей и смещение. Таким образом, в приведенном выше примере запрос вернет столбец с тремя значениями.
**Смотрите также**
- [stochasticLogisticRegression](#agg_functions-stochasticlogisticregression)
- [Отличие линейной от логистической регрессии.](https://stackoverflow.com/questions/12146914/what-is-the-difference-between-linear-regression-and-logistic-regression)
## stochasticLogisticRegression {#agg_functions-stochasticlogisticregression}
Функция реализует стохастическую логистическую регрессию. Её можно использовать для задачи бинарной классификации, функция поддерживает те же пользовательские параметры, что и stochasticLinearRegression и работает таким же образом.
### Параметры {#agg_functions-stochasticlogisticregression-parameters}
Параметры те же, что и в stochasticLinearRegression:
`learning rate`, `l2 regularization coefficient`, `mini-batch size`, `method for updating weights`.
Смотрите раздел [parameters](#agg_functions-stochasticlinearregression-parameters).
```text
stochasticLogisticRegression(1.0, 1.0, 10, 'SGD')
```
1. Построение модели
Смотрите раздел `Построение модели` в описании [stochasticLinearRegression](#stochasticlinearregression-usage-fitting) .
Прогнозируемые метки должны быть в диапазоне [-1, 1].
2. Прогнозирование
Используя сохраненное состояние, можно предсказать вероятность наличия у объекта метки `1`.
```sql
WITH (SELECT state FROM your_model) AS model SELECT
evalMLMethod(model, param1, param2) FROM test_data
```
Запрос возвращает столбец вероятностей. Обратите внимание, что первый аргумент `evalMLMethod` это объект `AggregateFunctionState`, далее идут столбцы свойств.
Мы также можем установить границу вероятности, которая присваивает элементам различные метки.
```sql
SELECT ans < 1.1 AND ans > 0.5 FROM
(WITH (SELECT state FROM your_model) AS model SELECT
evalMLMethod(model, param1, param2) AS ans FROM test_data)
```
Тогда результатом будут метки.
`test_data` — это таблица, подобная `train_data`, но при этом может не содержать целевое значение.
**Смотрите также**
- [stochasticLinearRegression](#agg_functions-stochasticlinearregression)
- [Отличие линейной от логистической регрессии](https://moredez.ru/q/51225972/)
[Оригинальная статья](https://clickhouse.yandex/docs/ru/query_language/agg_functions/reference/) <!--hide-->
......@@ -3,7 +3,7 @@
Создание базы данных db\_name.
```sql
CREATE DATABASE [IF NOT EXISTS] db_name
CREATE DATABASE [IF NOT EXISTS] db_name [ON CLUSTER cluster]
```
`База данных` - это просто директория для таблиц.
......
......@@ -25,7 +25,7 @@ greatCircleDistance(lon1Deg, lat1Deg, lon2Deg, lat2Deg)
**Пример**
``` sql
```sql
SELECT greatCircleDistance(55.755831, 37.617673, -55.755831, -37.617673)
```
......@@ -55,10 +55,9 @@ pointInEllipses(x, y, x₀, y₀, a₀, b₀,...,xₙ, yₙ, aₙ, bₙ)
`1`, если точка внутри хотя бы одного из эллипсов, `0`, если нет.
**Пример**
``` sql
```sql
SELECT pointInEllipses(55.755831, 37.617673, 55.755831, 37.617673, 1.0, 2.0)
```
......@@ -78,7 +77,7 @@ pointInPolygon((x, y), [(a, b), (c, d) ...], ...)
**Входные значения**
- `(x, y)` — координаты точки на плоскости. Тип данных — [Tuple](../../data_types/tuple.md- `[(a, b), (c, d) ...]` — вершины многоугольника. Тип данных — [Array](../../data_types/array.md). Каждая вершина представлена парой координат `(a, b)`. Вершины следует указывать в порядке обхода по или против часовой стрелки. Минимальное количество вершин — 3. Многоугольник должен быть константным.
- `(x, y)` — координаты точки на плоскости. Тип данных — [Tuple](../../data_types/tuple.md) — кортеж из двух чисел.
- `[(a, b), (c, d) ...]` — вершины многоугольника. Тип данных — [Array](../../data_types/array.md). Каждая вершина представлена парой координат `(a, b)`. Вершины следует указывать в порядке обхода по или против часовой стрелки. Минимальное количество вершин — 3. Многоугольник должен быть константным.
- функция поддерживает также многоугольники с дырками (вырезанными кусками). Для этого случая, добавьте многоугольники, описывающие вырезанные куски, дополнительными аргументами функции. Функция не поддерживает неодносвязные многоугольники.
......@@ -87,16 +86,70 @@ pointInPolygon((x, y), [(a, b), (c, d) ...], ...)
`1`, если точка внутри многоугольника, `0`, если нет.
Если точка находится на границе многоугольника, функция может возвращать как 0, так и 1.
**Пример**
``` sql
```sql
SELECT pointInPolygon((3., 3.), [(6, 0), (8, 4), (5, 8), (0, 2)]) AS res
```
```
┌─res─┐
│ 1 │
└─────┘
```
## geohashEncode
Кодирует широту и долготу в строку geohash, смотрите [http://geohash.org/](http://geohash.org/), [https://en.wikipedia.org/wiki/Geohash](https://en.wikipedia.org/wiki/Geohash).
```
geohashEncode(longitude, latitude, [precision])
```
**Входные значения**
- longitude — долгота. Диапазон — `[-180°, 180°].`
- latitude — широта. Диапазон — `[-90°, 90°].`
- precision — длина результирующей строки, по умолчанию `12`. Опционально. Целое число в диапазоне `[1, 12]`. Любое значение меньше, чем `1` или больше `12` автоматически преобразуются в `12`.
**Возвращаемые значения**
- Строка с координатой, закодированной модифицированной версией алфавита base32.
**Пример**
```sql
SELECT geohashEncode(-5.60302734375, 42.593994140625, 0) AS res
```
```
┌─res──────────┐
│ ezs42d000000 │
└──────────────┘
```
## geohashDecode
Декодирует любую строку, закодированную в geohash, на долготу и широту.
**Входные значения**
- encoded string — строка, содержащая geohash.
**Возвращаемые значения**
- (longitude, latitude) — широта и долгота. Кортеж из двух значений типа `Float64`.
**Пример**
```sql
SELECT geohashDecode('ezs42') AS res
```
```
┌─res─────────────────────────────┐
│ (-5.60302734375,42.60498046875) │
└─────────────────────────────────┘
```
[Оригинальная статья](https://clickhouse.yandex/docs/ru/query_language/functions/geo/) <!--hide-->
......@@ -10,7 +10,7 @@
В функции высшего порядка может быть передана лямбда-функция, принимающая несколько аргументов. В этом случае, в функцию высшего порядка передаётся несколько массивов одинаковых длин, которым эти аргументы будут соответствовать.
Для некоторых функций, например [arrayCount](#higher_order_functions-array-count) или [arraySum](#higher_order_functions-array-count), первый аргумент (лямбда-функция) может отсутствовать. В этом случае, подразумевается тождественное отображение.
Для некоторых функций, например [arrayCount](#higher_order_functions-array-count) или [arraySum](#higher_order_functions-array-sum), первый аргумент (лямбда-функция) может отсутствовать. В этом случае, подразумевается тождественное отображение.
Для функций, перечисленных ниже, лямбда-функцию должна быть указана всегда:
......@@ -19,7 +19,7 @@
- [arrayFirst](#higher_order_functions-array-first)
- [arrayFirstIndex](#higher_order_functions-array-first-index)
### arrayMap(func, arr1, ...) {#higher_order_functions-array-count}
### arrayMap(func, arr1, ...) {#higher_order_functions-array-map}
Вернуть массив, полученный на основе результатов применения функции `func` к каждому элементу массива `arr`.
......@@ -78,7 +78,7 @@ SELECT
Обратите внимание, что у функции `arrayFilter` первый аргумент (лямбда-функция) не может быть опущен.
### arrayCount(\[func,\] arr1, ...)
### arrayCount(\[func,\] arr1, ...) {#higher_order_functions-array-count}
Вернуть количество элементов массива `arr`, для которых функция func возвращает не 0. Если func не указана - вернуть количество ненулевых элементов массива.
### arrayExists(\[func,\] arr1, ...)
......@@ -87,7 +87,7 @@ SELECT
### arrayAll(\[func,\] arr1, ...)
Вернуть 1, если для всех элементов массива `arr`, функция `func` возвращает не 0. Иначе вернуть 0.
### arraySum(\[func,\] arr1, ...)
### arraySum(\[func,\] arr1, ...) {#higher_order_functions-array-sum}
Вернуть сумму значений функции `func`. Если функция не указана - просто вернуть сумму элементов массива.
### arrayFirst(func, arr1, ...) {#higher_order_functions-array-first}
......
......@@ -10,21 +10,27 @@
4. В JSON-е нет пробельных символов вне строковых литералов.
## visitParamHas(params, name)
Проверить наличие поля с именем name.
## visitParamExtractUInt(params, name)
Распарсить UInt64 из значения поля с именем name. Если поле строковое - попытаться распарсить число из начала строки. Если такого поля нет, или если оно есть, но содержит не число, то вернуть 0.
## visitParamExtractInt(params, name)
Аналогично для Int64.
## visitParamExtractFloat(params, name)
Аналогично для Float64.
## visitParamExtractBool(params, name)
Распарсить значение true/false. Результат - UInt8.
## visitParamExtractRaw(params, name)
Вернуть значение поля, включая разделители.
Примеры:
......@@ -35,6 +41,7 @@ visitParamExtractRaw('{"abc":{"def":[1,2,3]}}', 'abc') = '{"def":[1,2,3]}'
```
## visitParamExtractString(params, name)
Распарсить строку в двойных кавычках. У значения убирается экранирование. Если убрать экранированные символы не удалось, то возвращается пустая строка.
Примеры:
......@@ -48,4 +55,147 @@ visitParamExtractString('{"abc":"hello}', 'abc') = ''
На данный момент, не поддерживаются записанные в формате `\uXXXX\uYYYY` кодовые точки не из basic multilingual plane (они переводятся не в UTF-8, а в CESU-8).
Следующие функции используют [simdjson](https://github.com/lemire/simdjson) который разработан по более сложны требования для разбора JSON. Упомянутое выше предположение 2 по-прежнему применимо.
## JSONHas(json[, indices_or_keys]...)
Если значение существует в документе JSON, то возвращается `1`.
Если значение не существует, то возвращается `0`.
Примеры:
```
select JSONHas('{"a": "hello", "b": [-100, 200.0, 300]}', 'b') = 1
select JSONHas('{"a": "hello", "b": [-100, 200.0, 300]}', 'b', 4) = 0
```
`indices_or_keys` — это список из нуля или более аргументов каждый из них может быть либо строкой либо целым числом.
* Строка — это доступ к объекту по ключу.
* Положительное целое число — это доступ к n-му члену/ключу с начала.
* Отрицательное целое число — это доступ к n-му члену/ключу с конца.
Адресация элементов по индексу начинается с 1, следовательно элемент 0 не существует.
Вы можете использовать целые числа, чтобы адресовать как массивы JSON, так и JSON-объекты.
Примеры:
```
select JSONExtractKey('{"a": "hello", "b": [-100, 200.0, 300]}', 1) = 'a'
select JSONExtractKey('{"a": "hello", "b": [-100, 200.0, 300]}', 2) = 'b'
select JSONExtractKey('{"a": "hello", "b": [-100, 200.0, 300]}', -1) = 'b'
select JSONExtractKey('{"a": "hello", "b": [-100, 200.0, 300]}', -2) = 'a'
select JSONExtractString('{"a": "hello", "b": [-100, 200.0, 300]}', 1) = 'hello'
```
## JSONLength(json[, indices_or_keys]...)
Возвращает длину массива JSON или объекта JSON.
Если значение не существует или имеет неверный тип, то возвращается `0`.
Примеры:
```
select JSONLength('{"a": "hello", "b": [-100, 200.0, 300]}', 'b') = 3
select JSONLength('{"a": "hello", "b": [-100, 200.0, 300]}') = 2
```
## JSONType(json[, indices_or_keys]...)
Возвращает тип значения JSON.
Если значение не существует, то возвращается `Null`.
Примеры:
```
select JSONType('{"a": "hello", "b": [-100, 200.0, 300]}') = 'Object'
select JSONType('{"a": "hello", "b": [-100, 200.0, 300]}', 'a') = 'String'
select JSONType('{"a": "hello", "b": [-100, 200.0, 300]}', 'b') = 'Array'
```
## JSONExtractUInt(json[, indices_or_keys]...)
## JSONExtractInt(json[, indices_or_keys]...)
## JSONExtractFloat(json[, indices_or_keys]...)
## JSONExtractBool(json[, indices_or_keys]...)
Парсит JSON и извлекает значение. Эти функции аналогичны функциям `visitParam`.
Если значение не существует или имеет неверный тип, то возвращается `0`.
Примеры:
```
select JSONExtractInt('{"a": "hello", "b": [-100, 200.0, 300]}', 'b', 1) = -100
select JSONExtractFloat('{"a": "hello", "b": [-100, 200.0, 300]}', 'b', 2) = 200.0
select JSONExtractUInt('{"a": "hello", "b": [-100, 200.0, 300]}', 'b', -1) = 300
```
## JSONExtractString(json[, indices_or_keys]...)
Парсит JSON и извлекает строку. Эта функция аналогична функции `visitParamExtractString`.
Если значение не существует или имеет неверный тип, то возвращается пустая строка.
У значения убирается экранирование. Если убрать экранированные символы не удалось, то возвращается пустая строка.
Примеры:
```
select JSONExtractString('{"a": "hello", "b": [-100, 200.0, 300]}', 'a') = 'hello'
select JSONExtractString('{"abc":"\\n\\u0000"}', 'abc') = '\n\0'
select JSONExtractString('{"abc":"\\u263a"}', 'abc') = '☺'
select JSONExtractString('{"abc":"\\u263"}', 'abc') = ''
select JSONExtractString('{"abc":"hello}', 'abc') = ''
```
## JSONExtract(json[, indices_or_keys...], return_type)
Парсит JSON и извлекает значение с заданным типом данных.
Это обобщение предыдущих функций `JSONExtract<type>`.
Это означает
`JSONExtract(..., 'String')` выдает такой же результат, как `JSONExtractString()`,
`JSONExtract(..., 'Float64')` выдает такой же результат, как `JSONExtractFloat()`.
Примеры:
```
SELECT JSONExtract('{"a": "hello", "b": [-100, 200.0, 300]}', 'Tuple(String, Array(Float64))') = ('hello',[-100,200,300])
SELECT JSONExtract('{"a": "hello", "b": [-100, 200.0, 300]}', 'Tuple(b Array(Float64), a String)') = ([-100,200,300],'hello')
SELECT JSONExtract('{"a": "hello", "b": [-100, 200.0, 300]}', 'b', 'Array(Nullable(Int8))') = [-100, NULL, NULL]
SELECT JSONExtract('{"a": "hello", "b": [-100, 200.0, 300]}', 'b', 4, 'Nullable(Int64)') = NULL
SELECT JSONExtract('{"passed": true}', 'passed', 'UInt8') = 1
SELECT JSONExtract('{"day": "Thursday"}', 'day', 'Enum8(\'Sunday\' = 0, \'Monday\' = 1, \'Tuesday\' = 2, \'Wednesday\' = 3, \'Thursday\' = 4, \'Friday\' = 5, \'Saturday\' = 6)') = 'Thursday'
SELECT JSONExtract('{"day": 5}', 'day', 'Enum8(\'Sunday\' = 0, \'Monday\' = 1, \'Tuesday\' = 2, \'Wednesday\' = 3, \'Thursday\' = 4, \'Friday\' = 5, \'Saturday\' = 6)') = 'Friday'
```
## JSONExtractKeysAndValues(json[, indices_or_keys...], value_type)
Разбор пар ключ-значение из JSON, где значение имеет тип данных ClickHouse.
Пример:
```
SELECT JSONExtractKeysAndValues('{"x": {"a": 5, "b": 7, "c": 11}}', 'x', 'Int8') = [('a',5),('b',7),('c',11)];
```
## JSONExtractRaw(json[, indices_or_keys]...)
Возвращает часть JSON.
Если значение не существует или имеет неверный тип, то возвращается пустая строка.
Пример:
```
select JSONExtractRaw('{"a": "hello", "b": [-100, 200.0, 300]}', 'b') = '[-100, 200.0, 300]'
```
[Оригинальная статья](https://clickhouse.yandex/docs/ru/query_language/functions/json_functions/) <!--hide-->
# Функции машинного обучения
## evalMLMethod (prediction) {#machine_learning_methods-evalmlmethod}
Предсказание с использованием подобранных регрессионных моделей.
### Stochastic Linear Regression
Агрегатная функция [stochasticLinearRegression](../agg_functions/reference.md#agg_functions-stochasticlinearregression) реализует стохастический градиентный спуск, использую линейную модель и функцию потерь MSE.
### Stochastic Logistic Regression
Агрегатная функция [stochasticLogisticRegression](../agg_functions/reference.md#agg_functions-stochasticlogisticregression) реализует стохастический градиентный спуск для задачи бинарной классификации.
......@@ -97,7 +97,7 @@ nav:
- 'Buffer': 'operations/table_engines/buffer.md'
- 'JDBC': 'operations/table_engines/jdbc.md'
- 'ODBC': 'operations/table_engines/odbc.md'
- 'SQL Reference':
- 'hidden': 'query_language/index.md'
- 'SELECT': 'query_language/select.md'
......@@ -136,6 +136,7 @@ nav:
- 'arrayJoin': 'query_language/functions/array_join.md'
- 'Working with geographical coordinates': 'query_language/functions/geo.md'
- 'Working with Nullable arguments': 'query_language/functions/functions_for_nulls.md'
- 'Machine Learning Functions': 'query_language/functions/machine_learning_functions.md'
- 'Other': 'query_language/functions/other_functions.md'
- 'Aggregate Functions':
- 'Introduction': 'query_language/agg_functions/index.md'
......
......@@ -136,6 +136,7 @@ nav:
- 'arrayJoin': 'query_language/functions/array_join.md'
- 'Working with geographical coordinates': 'query_language/functions/geo.md'
- 'Working with Nullable arguments': 'query_language/functions/functions_for_nulls.md'
- 'Machine Learning Functions': 'query_language/functions/machine_learning_functions.md'
- 'Other': 'query_language/functions/other_functions.md'
- 'Aggregate Functions':
- 'Introduction': 'query_language/agg_functions/index.md'
......@@ -186,6 +187,7 @@ nav:
- 'Restrictions on Query Complexity': 'operations/settings/query_complexity.md'
- 'Settings': 'operations/settings/settings.md'
- 'Settings Profiles': 'operations/settings/settings_profiles.md'
- 'Constraints on Settings': 'operations/settings/constraints_on_settings.md'
- 'Utilities':
- 'Overview': 'operations/utils/index.md'
- 'clickhouse-copier': 'operations/utils/clickhouse-copier.md'
......
......@@ -136,6 +136,7 @@ nav:
- 'Функция arrayJoin': 'query_language/functions/array_join.md'
- 'Функции для работы с географическими координатами': 'query_language/functions/geo.md'
- 'Функции c Nullable агрументами': 'query_language/functions/functions_for_nulls.md'
- 'Функции машинного обучения': 'query_language/functions/machine_learning_functions.md'
- 'Прочие функции': 'query_language/functions/other_functions.md'
- 'Агрегатные функции':
- 'Введение': 'query_language/agg_functions/index.md'
......
......@@ -135,6 +135,7 @@ nav:
- 'arrayJoin函数': 'query_language/functions/array_join.md'
- 'GEO函数': 'query_language/functions/geo.md'
- 'Nullable处理函数': 'query_language/functions/functions_for_nulls.md'
- 'Machine Learning Functions': 'query_language/functions/machine_learning_functions.md'
- '其他函数': 'query_language/functions/other_functions.md'
- 'Aggregate functions':
- 'Introduction': 'query_language/agg_functions/index.md'
......@@ -185,6 +186,7 @@ nav:
- 'Restrictions on query complexity': 'operations/settings/query_complexity.md'
- 'Settings': 'operations/settings/settings.md'
- 'Settings profiles': 'operations/settings/settings_profiles.md'
- 'Constraints on Settings': 'operations/settings/constraints_on_settings.md'
- 'Utilities':
- 'Overview': 'operations/utils/index.md'
- 'clickhouse-copier': 'operations/utils/clickhouse-copier.md'
......
../../../en/operations/settings/constraints_on_settings.md
\ No newline at end of file
# 机器学习函数
## evalMLMethod (prediction)
## evalMLMethod (prediction) {#machine_learning_methods-evalmlmethod}
使用拟合回归模型的预测请使用`evalMLMethod`函数。 请参阅`linearRegression`中的链接。
## Stochastic Linear Regression
`stochasticLinearRegression`聚合函数使用线性模型和MSE损失函数实现随机梯度下降法。 使用`evalMLMethod`来预测新数据。
请参阅示例和注释[此处](../agg_functions/reference.md#linearregression)
请参阅示例和注释[此处](../agg_functions/reference.md#agg_functions-stochasticlinearregression)
## Stochastic Logistic Regression
`stochasticLogisticRegression`聚合函数实现了二元分类问题的随机梯度下降法。 使用`evalMLMethod`来预测新数据。
请参阅示例和注释[此处](../agg_functions/reference.md#logisticregression)
请参阅示例和注释[此处](../agg_functions/reference.md#agg_functions-stochasticlogisticregression)
......@@ -76,7 +76,7 @@ SELECT visibleWidth(NULL)
如果将`NULL`作为参数传递给函数,那么它返回`Nullable(Nothing)`类型,它对应于ClickHouse中的内部`NULL`
## blockSize()
## blockSize() {#function-blocksize}
获取Block的大小。
在ClickHouse中,查询始终工作在Block(包含列的部分的集合)上。此函数允许您获取调用其的块的大小。
......@@ -305,7 +305,7 @@ SELECT
返回行所在的Block的序列号。
## rowNumberInBlock
## rowNumberInBlock {#function-rownumberinblock}
返回行所在Block中行的序列号。 针对不同的Block始终重新计算。
......@@ -641,7 +641,7 @@ SELECT replicate(1, ['a', 'b', 'c'])
获取聚合函数的状态。返回聚合结果(最终状态)。
## runningAccumulate
## runningAccumulate {#function-runningaccumulate}
获取聚合函数的状态并返回其具体的值。这是从第一行到当前行的所有行累计的结果。
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册