Skip to content

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

ClickHouse 7 min read How-to mediumAdept

Linear Regression Using ClickHouse Machine Learning Functions

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.

Assumes: SQL basicslinear regressiongradient descent basics

Related posts

  • Forecasting Using ClickHouse Machine Learning Functions

    ClickHouse mediumAdept

    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.

  • Variance Reduction Below the Randomization Grain

    Instacart Tech hardMaster

    Instacart improves CUPED variance reduction for region-day switchback experiments by training an order-level model (gradient boosted trees) on pre-treatment features and aggregating its predictions to the region-day grain as the CUPED covariate. Across 10 lateness experiments, order-level CUPED cut variance by 18-40% versus 5-10% for region-day CUPED, shortening experiment runtimes by about a third on average. Features must be unaffected by treatment, and a placebo mean-difference test on the aggregated prediction catches contamination, as with ETA model experiments that shift which orders get placed. The approach applies wherever interference forces coarse cluster randomization but outcomes are observed at a finer unit.

  • Reducing experiment duration with predicted control variates

    Etsy Code as Craft mediumAdept

    Etsy upgraded its experimentation platform's variance reduction from CUPED to CUPAC, which feeds pre-experiment features (over 100, up from 3) into LightGBM models whose predictions serve as the covariate in a linear CUPED-style adjustment. Average variance reduction rose from 7% to 27%, with a range of 2% to 77% depending on metric stability. That cuts average experiment duration by almost 3 days. The pipeline runs as an Airflow DAG: BigQuery computes features, Dataflow runs batch predictions, Spark fits the regression, and t-tests follow. Because per-metric models are costly to train and maintain, Etsy still encourages CUPED for team-specific metrics and plans to automate CUPED's pre-experiment data collection.

  • 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.

  • How to Scale K-Means Clustering with just ClickHouse SQL

    ClickHouse mediumAdept

    K-Means clustering can be implemented entirely in ClickHouse SQL by computing centroids incrementally with avgForEachState aggregate states stored in an AggregatingMergeTree table, fed by a Materialized View over a Null-engine table. Each iteration is a single INSERT INTO SELECT that assigns every point to its nearest previous centroid via L2Distance, so memory stays bounded and the work scales across a cluster. Querying pre-aggregated centroids is over 1700x faster than a raw GROUP BY on 100M rows. Clustering 170M NYC taxi rides takes under 3 minutes, versus over 100 minutes and 90GB of RAM with scikit-learn on the same resources.

The quest for software engineering knowledge.

Look:
Layout: