首页 > 解决方案 > 如何修改 sklearn 的管道可视化(它用什么代替了 __repr__ 和 __str__?)

问题描述

Sklearn 有一个很好但相当未知的可视化,可以通过sklearn.set_config(display='diagram'). 我正在尝试自定义可视化的输出,但无法弄清楚 html 输出是如何生成的。我知道 python 的魔术方法 __str__ 和 __repr__ 可用于创建某些对象的文本表示。我预计 __repr__ 将用于创建 html 输出。为了测试这个假设,我重写了输出字符串“repr”的方法。如以下代码及其输出所示,调用了 __repr__ 方法,但显然它不用作 html 生成的入口点,因为这将导致单个输出:“repr”。

import sklearn
from sklearn.base import BaseEstimator
from sklearn.pipeline import Pipeline

sklearn.set_config(display='diagram')


class DummyPipeline(Pipeline):
    def __repr__(self, *args):
        print("repr")
        return "__repr__"

    def __str__(self, *args):
        print("str")
        return ("__str__")


class DummyEstimator(BaseEstimator):
    def fit(self, X, y=None):
        pass

    def transform(self, X, y=None):
        pass


DummyPipeline(steps=[('first_estimator', DummyEstimator()), ('second_estimator', DummyEstimator())])

这将返回: 因此问题是:我需要哪种方法来更改 html 表示?
在此处输入图像描述

标签: pythonscikit-learnvisualizationpipeline

解决方案


主要方法是sklearn.utils.estimator_html_repr;请参阅它的API 文档用户指南此文件中的代码。

该函数调用str(estimator),因此这是大多数估算器为 html 生成输出的地方(如您在示例中看到的,带有DummyPipeline打印"__str__")。元估计器(如管道)在这部分代码中得到检查,并且它本身其方法Pipeline中得到一些特殊处理。_sk_visual_block_

因此,根据您想要更改的具体内容,您可能需要在很多地方进行更改。我之前已经对文件中的_STYLE常量进行了猴子修补estimator_html_repr.py;由于没有太多的复合估计器,这可以很好地工作。


推荐阅读