Skip to main content
Softmax converts a vector of numbers into a probability distribution: every element of the result is between 0 and 1, and the elements add up to 1. ClickHouse has no built-in softmax function, but you can build one from array functions and wrap it in a SQL user-defined function:
The examples round the results to four digits to keep the output short. Without rounding, the last digits of the Float64 values can differ between ClickHouse versions.

How it works

The softmax of the element x[i] is exp(x[i]) divided by the sum of exp(x[j]) over all elements. The function does it in three steps:
  1. arrayMax(x) finds the largest element.
  2. arrayMap calculates exp(toFloat64(v) - toFloat64(arrayMax(x))) for every element v.
  3. The resulting array is divided by its sum, which arraySum returns. Dividing an array by a number divides every element.
Subtracting the maximum does not change the result, because the same factor appears in the numerator and in the denominator. It keeps the function numerically stable: the largest argument of exp is 0, so exp cannot overflow. Without it, large inputs produce inf and then nan:
The function accepts an array of any numeric type and returns 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 more arrayMap. To normalize along the columns instead, transpose the array before and after with arrayTranspose (available from ClickHouse 26.4):
In 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 in system.functions:
Use CREATE OR REPLACE FUNCTION to change a definition and DROP FUNCTION to remove it: