Skip to content

In development. Expect rough edges and changes. The source code is not public yet.

ClickHouse 9 min read How-to mediumAdept

Forecasting Using ClickHouse Machine Learning Functions

ClickHouse's built-in stochasticLinearRegression and evalMLMethod functions can fit and apply time-series forecasting models entirely in SQL, with no Python or R. Using monthly flight passenger data, a log-transformed target is regressed on a linear trend plus 12 month dummy variables, with no intercept to avoid the dummy variable trap. One model per airline-airport pair is trained in a single GROUP BY query, giving 35 models. Test-set MAE and RMSE are computed in SQL, and a future-dates view extends the forecasts three years out. Wrapping training in a materialized view would let the models retrain continuously as new data arrives.

Assumes: SQL aggregationlinear regression basicstime-series seasonality

Related posts

  • Linear Regression Using ClickHouse Machine Learning Functions

    ClickHouse mediumAdept

    Delivery times can be predicted with a linear regression trained entirely inside ClickHouse using stochasticLinearRegressionState and evalMLMethod, with no Python or Spark involved. The worked example uses 2,293 last-mile orders from one courier in Jilin. Features are built in SQL: geoDistance for pickup-to-delivery distance, one-hot pickup-hour columns, and a randUniform 80/20 train/test split. Distance is standardized for gradient descent and the target is log-transformed to keep predictions positive. The model reaches about 58 min MAE and 78 min RMSE overall, improving to roughly 30 and 42 minutes for deliveries under two hours, while accuracy degrades for longer journeys.

  • ClickHouse forecasting and anomaly detection with time series foundation models

    ClickHouse mediumAdept

    TimesFM 3.0, a pretrained time-series foundation model, can be called from ClickHouse SQL via executable Python UDFs that forward arrays to an HTTP model server, giving zero-shot forecasts and anomaly scores without per-series training. SQL handles aggregation, ordering and time bucketing. aiForecast returns median, q10–q90 bounds and nine native quantiles per step, and aiDetectAnomalies scores rolling held-out windows by normalized forecast error. On Walmart M5 store sales, adding a known-future Christmas event flag as a covariate dropped Christmas anomaly scores below the threshold in nine of ten stores (e.g. TX_2 from 8.65 to 2.71). The weights carry non-commercial restrictions and the demo is for local evaluation only.

  • Probabilistic Time Series Forecasting with 🤗 Transformers

    Hugging Face hardMaster

    An encoder-decoder Transformer can be trained as a global probabilistic forecaster that learns across many related time series and outputs a distribution (Student-t by default) rather than point estimates, with forecasts sampled autoregressively. The walkthrough trains Hugging Face's TimeSeriesTransformerForPrediction from scratch on the Monash tourism_monthly dataset (366 Australian regions, 24-month horizon). It uses GluonTS for lag features, time features, observed-value masks and instance splitting into context/prediction windows. Transformers suit forecasting because they handle missing values via attention masks and train with teacher forcing, but quadratic attention limits window sizes and they can overfit more easily.

  • TimesFM-3: A zero-shot foundation model for multivariate forecasting

    Google Research hardMaster

    TimesFM-3 is a 330M-parameter decoder-only transformer pre-trained on over 1 trillion real and synthetic time points that does zero-shot multivariate forecasting, supporting multiple targets, past-only covariates and known-future covariates. Series are split into 32-step patches with per-series normalization. Future-known covariates use lookahead tokens that concatenate the current patch with future patches. Layers alternate causal temporal attention within each series with full cross-variate attention at each time step. Contiguous Patch Masking replaces autoregressive patch-by-patch decoding, producing the whole horizon and 9 quantiles in one forward pass. It ranks first among pre-trained foundation models on Gift-Eval, FEV-Bench and Time against Chronos-2, Toto 2.0 and TimesFM-2.5, even in univariate mode, and is available on GitHub, Hugging Face and BigQuery's AI.FORECAST.

  • Modeling Machine Learning Data in OLAP databases

    ClickHouse mediumAdept

    ClickHouse can act as the transformation engine and offline store of an ML feature store, with features modeled as timestamped tables and assembled into point-in-time correct training sets. Using a 100m-row web analytics dataset and a bounce-prediction example, the walkthrough builds a deduplicated "feature subset" table with ReplacingMergeTree and a trimmed PRIMARY KEY, then keeps it current with incremental materialized views. Features are tied to entities such as user and domain, computed with GROUP BY aggregations, and joined into feature vectors via ASOF JOIN on key and timestamp proximity. The aim is fast iteration during feature engineering, which usually costs more time than model selection.

The quest for software engineering knowledge.

Look:
Layout: