FastHTML x scikit-learnFastHTML x scikit-learn

[scikit-learn](https://scikit-learn.org) has an under-appreciated feature that lets you render a pipeline in HTML. This interactive representation works great for exploring the graph and details of your model. I will show you how to render this in [FastHTML](https://fastht.ml/) so you can have cool ways to visualize models in your web app. Let's take the simple case of a pipeline that scales data with [StandardScaler](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html) and trains a tree ensemble using [HistGradientBoostingClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.HistGradientBoostingClassifier.html). from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.ensemble import HistGradientBoostingClassifier pipe = make_pipeline(StandardScaler(with_mean=False), HistGradientBoostingClassifier(max_depth=6, learning_rate=0.01))
Now with FastHTML we can visualize this pipeline. We first apply scikit-learn's [estimator_html_repr](https://scikit-learn.org/stable/modules/generated/sklearn.utils.estimator_html_repr.html), which outputs the HTML representation. This is then rendered with FastHTML's [NotStr](https://docs.fastht.ml/ref/defining_xt_component.html#notstr). from fasthtml.common import * from sklearn.utils import estimator_html_repr NotStr(estimator_html_repr(pipe))
If you are experimenting in a Jupyter Notebook you can use `show` from `fasthtml.common` to render in your notebook. show(NotStr(estimator_html_repr(pipe)))
And there it is:
Pipeline(steps=[('scaler', StandardScaler(with_mean=False)),
                ('lr',
                 HistGradientBoostingClassifier(learning_rate=0.01,
                                                max_depth=6))])
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

By expanding the nodes you can see which hyperparameters were chosen. The `i` icon shows if the pipeline is fitted, and the `?` icons provide links to documentation.
That's it! This FastHTML one-liner works on even the most intricate scikit-learn pipelines. I will do a follow up showing how to render full [skops model cards](https://skops.readthedocs.io/en/stable/auto_examples/plot_model_card.html#sphx-glr-auto-examples-plot-model-card-py). These cards feature not only the model, but can include metrics, feature importance, plots, metadata and tables. Hope you learned something new. Until next time!
Back to TIL (Today I Learned) Overview