🚀 Jumpstart 2027: Custom, Secure AI Workflows to Adopt Now. Reserve your spot →

Chris Parmer

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.
Five small charts made with scikit-learn: a 2026 ERCOT load forecast with its P10 to P90 band, a fraud cost curve across thresholds, toxicity model scores with random and scaffold folds, taxi trip-time error by hour and 5,878 retail customers in four segments

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 panels of raw data: ERCOT daily mean load from 2021 to 2026 rising each summer, card transaction amounts for fraud and legitimate transactions, Tox21 compounds tested and active per assay, taxi pickups by weekday and hour, and the online retailer's monthly revenue peaking each November

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.

Left, ERCOT load in the week of July 22, 2026, with the actual load, the P50 forecast and a P10 to P90 band; right, the daily peak from January to October 2026, actual and forecast
from sklearn.ensemble import HistGradientBoostingRegressor
forecast = {q: HistGradientBoostingRegressor(loss="quantile", quantile=q, max_iter=500, learning_rate=0.05)
.fit(train[features], train.y).predict(test[features]) * test.level
for 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.

Cost on the test set at every decision threshold from 0.002 to 1: total cost, missed fraud and reviews of false alerts, with the cheapest threshold at 0.013 and the default 0.5 marked
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.

Cross-validated ROC AUC for 12 Tox21 assays, with random folds and with folds split by scaffold; the scaffold score is lower on every assay
scaffold = [MurckoScaffold.MurckoScaffoldSmiles(mol=m) for m in mols] # RDKit
scaffold_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.

Mean absolute error of predicted taxi trip time by pickup hour for February 2025, for the pipeline and for January's median per zone pair
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.

Left, 5,878 online retail customers by orders and spend on log scales, colored by segment; right, each segment's share of customers and of revenue
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.

Model Desk Energy tab for the week of July 20, 2026: actual peak 91.1 GW, forecast peak 88.9 GW, 1.6% average error, 83% of hours inside the P10 to P90 band, three models run in 314 ms

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

Model Desk Fraud tab with a review cost of 10: cheapest threshold 0.013, 115 of 148 frauds caught, 70 false alerts, total cost 4,701 against 5,195 at 0.5

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.

Model Desk Toxicity tab for bisphenol A: predicted activity above 0.7 in NR-ER, NR-ER-LBD, SR-ARE and SR-MMP, next to the random and scaffold cross-validation scores for each assay

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

Model Desk Trips tab from Midtown Center to JFK Airport on a Tuesday: 32 minutes at 4 a.m., 58 minutes at 4 p.m., 1,485 January trips on that pair

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

Model Desk Customers tab placing a customer with 6 orders, ÂŁ1,500 spent and a last order 30 days ago among the recent occasional buyers, on a scatter of all 5,878 customers

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

Model Desk Versions tab: a table comparing scikit-learn 1.8.0 and 1.9.1 for each step

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.

FAQ

bluesly
x
instagram
youtube
medium
fcaebook

Product

© 2026
Plotly. All rights reserved.
Cookie Preferences
aicpa/soc2