
Chris Parmer
2026-11-14
scikit-learn demo
Machine learning in Python, with Dash and Plotly
TL;DR
- scikit-learn is Python's standard library for machine learning on tables, with one fit and predict API for regression, classification, clustering, preprocessing and validation. David Cournapeau started it in 2007 as a Google Summer of Code project, and a team at INRIA made the first public release in 2010.
- This demo runs five models on public data from five industries: a grid load forecast with prediction intervals, a cost-based decision threshold, toxicity models validated on unseen chemistry, taxi trip times from a polars DataFrame and customer segments.
- Version 1.9 (June 2026; 1.9.1 in September) adds metric_at_thresholds for choosing a decision threshold, experimental callbacks for monitoring fits, and dataframe support through narwhals.
- All five models run in Model Desk, a Dash app that re-scores them when you move a control, with the prompts to build it yourself at the end.

What is scikit-learn?
Most modeling work at a utility, a bank, a drug company or a retailer starts as a table: rows of hours, transactions, compounds, trips or customers, and a column you want to predict or explain. The algorithm is rarely the hard part. Most of the effort goes into encoding messy inputs, validating the model the way it will actually be used, and turning its scores into decisions.
scikit-learn covers all of that with one API. Every model, transformer and clusterer has fit, and you chain them into a Pipeline that cross-validates as one object, so preprocessing never sees the test data. It's the modeling half of our guide to Python packages for data, next to statsmodels for models you explain and test. Below are five things you'd do with it, each on a public dataset from a different industry.
The data: five public datasets, from 5,878 customers to 7.1 million taxi trips
Dataset
Industry
Source
Rows
Target
ERCOT hourly load, 2021 to October 2026, with weather in five Texas cities
Energy
50,923 hours
Load in MW
Card transactions, two days in September 2013
Finance
Worldline and ULB, OpenML 1597
284,807
Fraud (492)
Tox21 compounds in 12 toxicity assays
Pharma
7,823
Active or not
NYC yellow taxi trips, January and February 2025
Transportation
7.1 million
Trip minutes
Online Retail II orders, December 2009 to December 2011
Retail
779,425 order lines
None (clustering)
They arrive as Excel, JSON, ARFF, CSV and Parquet. fetch_openml(data_id=1597, as_frame=True) downloads and caches the OpenML dataset, and the rest are ordinary pandas or polars reads, since scikit-learn takes NumPy arrays and pandas or polars dataframes alike.

Five scikit-learn examples
1. Energy: forecast hourly grid load with prediction intervals
HistGradientBoostingRegressor(loss="quantile") fits one model per quantile, so you get a P10 to P90 band instead of a single line. Trees can't extrapolate past loads they've seen, and Texas load keeps setting records, so the model predicts load divided by the previous week's average instead of load itself.

from sklearn.ensemble import HistGradientBoostingRegressorforecast = {q: HistGradientBoostingRegressor(loss="quantile", quantile=q, max_iter=500, learning_rate=0.05).fit(train[features], train.y).predict(test[features]) * test.levelfor q in (0.1, 0.5, 0.9)}
- Trained on 2021 to 2025 and scored on 2026, the median forecast was off by 2.1% on average, against 4.1% for repeating yesterday's load. It used observed weather, so with weather forecasts as inputs it would do somewhat worse.
2. Finance: choose a fraud threshold by cost with metric_at_thresholds
A default cutoff of 0.5 ignores what each kind of error costs. metric_at_thresholds, new in 1.9, runs any metric at every threshold, and sample weights turn it into a cost: a missed fraud costs its amount, and a false alert costs a review.

from sklearn.metrics import metric_at_thresholds# cost_parts(y_true, y_pred, sample_weight) returns (weighted missed frauds, false alerts)w = np.where(y == 1, amount, 10) # a fraud weighs its amount, a false alert a review (10 is assumed)values, thresholds = metric_at_thresholds(y, model.predict_proba(X)[:, 1], cost_parts, sample_weight=w)
- The cheapest threshold, 0.013, catches more frauds than 0.5 at the price of more alerts, and lowers the total cost. The review cost is our assumption, so the app has a slider for it.
3. Pharma: validate toxicity models on unseen chemistry with GroupKFold
Random folds put near-copies of a molecule in both training and test, which flatters the model. Grouping compounds by their Bemis-Murcko scaffold (computed with RDKit) keeps each chemical series in one fold, the way a model meets a new series in a real discovery program.

scaffold = [MurckoScaffold.MurckoScaffoldSmiles(mol=m) for m in mols] # RDKitscaffold_auc = cross_val_score(rf, X, y, cv=GroupKFold(5), groups=scaffold, scoring="roc_auc")
- Split by scaffold, every one of the 12 assays scores lower, 0.74 against 0.82 for the area under the ROC curve (AUC) on average, which is the more honest estimate for new compounds.
4. Transportation: predict taxi trip times from a polars DataFrame
The 32,202 pickup and dropoff zone pairs in January are far too many for one-hot encoding. TargetEncoder replaces each with a cross-fitted average of the target, and in 1.9 the whole pipeline takes and returns polars, the dataframe library in our polars demo.

pipe = make_pipeline(make_column_transformer((TargetEncoder(target_type="continuous", cv=KFold(5, shuffle=True)), ["pu", "do", "pair"]),remainder="passthrough"),HistGradientBoostingRegressor(max_iter=300)).set_output(transform="polars")
- Trained on January and tested on February's 3.5 million trips, it was off by 3.3 minutes on average, against 3.9 for January's median per zone pair.
5. Retail: segment customers with KMeans
Recency, frequency and spend (RFM) summarize each customer in three numbers. They're heavily skewed, so a log transform and scaling come before KMeans in one pipeline.

seg = make_pipeline(FunctionTransformer(np.log1p), StandardScaler(), KMeans(4, n_init=10))rfm["segment"] = seg.fit_predict(rfm[["recency", "frequency", "monetary"]])
- The loyal regulars, 19% of customers, brought in 72% of the revenue. We used four clusters, although two scored a little higher on silhouette, because four map to actions a marketing team can take.
scikit-learn also covers dimensionality reduction, anomaly detection, calibration, imputation, feature selection, hyperparameter search and model inspection through the same API.
What's new in scikit-learn 1.9
1.9.0 came out in June 2026 and 1.9.1 in September, with about 150 contributors listed in the release notes:
- metric_at_thresholds runs any metric at every distinct threshold of a score, with sample weights.
- Callbacks (experimental): ProgressBar and ScoringMonitor, attached with set_callbacks, for LogisticRegression, the search classes, Pipeline and StandardScaler.
- narwhals for dataframes: polars and other dataframe libraries work for input and set_output without the deprecated interchange protocol.
- Faster fits: float32 gradients in LogisticRegression(solver="lbfgs"), and faster Lasso and ElasticNet with strong L1 penalties.
- Trees: every regression criterion now handles missing values, and monotonic_cst works with them.
Before you upgrade, note that 1.9 needs Python 3.11 and installs narwhals, SVC(probability=True) is deprecated in favor of CalibratedClassifierCV, and TargetEncoder's shuffle and random_state give way to cv.
pip install -U scikit-learn
Testing 1.9 against 1.8
We ran every step on 1.8.0 and 1.9.1 in environments that differed only in scikit-learn:
- polars 2 works on 1.9. With polars 2.1, the taxi pipeline failed on 1.8.0 and fit on 1.9.1 about as fast as from pandas, with identical predictions.
- Float32 logistic regression is faster: 0.90 s against 1.46 s on 1.1 million rows.
- Other results moved only slightly, because 1.9 changed how gradient boosting picks bin edges and how random forests draw samples. KMeans segments were identical.
- One thing to watch: on 1.9.1, HistGradientBoostingClassifier raised a ValueError on data with columns that are entirely missing, which 1.8.0 accepted. Drop all-missing columns before fitting.
Demo App: Model Desk
We built a Dash app called Model Desk that runs all five models in callbacks, and deployed it privately to Plotly Cloud.

The Energy tab runs the quantile models on any week of 2026, here the week with the year's highest hour.

The Fraud tab reruns metric_at_thresholds whenever you move the review-cost slider, so an operations lead can see how the cheapest threshold shifts as the cost of a review changes.

The Toxicity tab fingerprints any compound you type as a SMILES string with RDKit and runs all 12 assay models on it.

The Trips tab predicts the trip time for every pickup hour on a route, such as Midtown to JFK on a Tuesday.

The Customers tab places a customer you describe into a segment with predict.

The Versions tab has the 1.8 and 1.9 test results from the section above.
Running scikit-learn on Plotly Cloud and Dash Enterprise
What we learned deploying Model Desk applies the same way on Dash Enterprise:
- Pin scikit-learn in requirements.txt. Fitted models saved with joblib only load reliably on the version that trained them.
- Round scores before metric_at_thresholds in a callback. It calls your metric once per distinct score, so rounding to three decimals took it from 17.4 s to 0.03 s.
- Predict in one batch. The Trips tab sends all 24 hours in one predict call instead of 24 calls.
- Limit threads when processes share CPUs. Two jobs that each used every core slowed our training script badly, and OMP_NUM_THREADS=2 fixed it.
Prompts to build it yourself
The five charts:
Prompt: With scikit-learn 1.9 and Plotly: (1) ERCOT hourly load with Open-Meteo weather, quantile HistGradientBoostingRegressor at P10/P50/P90 on load over last week's mean, train to 2025, score 2026; (2) OpenML 1597 card fraud, metric_at_thresholds weighted by amount and a review cost; (3) Tox21 RDKit fingerprints, RandomForest AUC with StratifiedKFold vs GroupKFold on scaffolds; (4) NYC taxi trips as polars, TargetEncoder on zones and pair, train January, score February; (5) UCI Online Retail II, log1p, StandardScaler, KMeans(4) on RFM.
The Model Desk app:
Prompt: Build a Dash app called Model Desk on the same data, with models saved by joblib. Tabs: Energy (pick a 2026 week, run the quantile models), Fraud (a review-cost slider re-runs metric_at_thresholds), Toxicity (SMILES in, 12 assay predictions out), Trips (zones and weekday, predict all 24 hours), Customers (place a customer by RFM), Versions (1.8.0 vs 1.9.1). Inter, light theme, Plotly purple.