softmax function, but you can build one from array functions and wrap it in a SQL user-defined function:
Float64 values can differ between ClickHouse versions.
How it works
The softmax of the elementx[i] is exp(x[i]) divided by the sum of exp(x[j]) over all elements. The function does it in three steps:
arrayMax(x)finds the largest element.arrayMapcalculatesexp(toFloat64(v) - toFloat64(arrayMax(x)))for every elementv.- The resulting array is divided by its sum, which
arraySumreturns. Dividing an array by a number divides every element.
exp is 0, so exp cannot overflow. Without it, large inputs produce inf and then nan:
Array(Float64). The array must not contain NULL elements.
toFloat64 converts both values before the subtraction, so that the difference is calculated in floating point for integer arrays as well. Without the conversion, the difference of two 64-bit integers is calculated in Int64 and wraps around when the elements are far apart: toUInt64(0) - toUInt64('18446744073709551615') returns 1, and the smaller element would get the larger probability. The price of the conversion is that integers with an absolute value above 2^53 are rounded to the nearest Float64, so two such elements that differ by 1 can get the same probability.
Two-dimensional arrays
A SQL user-defined function can call another one, so softmax over each row of a two-dimensional array is one morearrayMap. To normalize along the columns instead, transpose the array before and after with arrayTranspose (available from ClickHouse 26.4):
by_rows, every inner array adds up to 1. In by_columns, the elements at the same position of the inner arrays add up to 1.
Use it on a table
Manage the functions
SQL user-defined functions are stored on the server and stay available after a restart. List them with their definitions insystem.functions:
CREATE OR REPLACE FUNCTION to change a definition and DROP FUNCTION to remove it: