python - 如何修改 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())])
解决方案
主要方法是sklearn.utils.estimator_html_repr
;请参阅它的API 文档、用户指南和此文件中的代码。
该函数调用str(estimator)
,因此这是大多数估算器为 html 生成输出的地方(如您在示例中看到的,带有DummyPipeline
打印"__str__"
)。元估计器(如管道)在这部分代码中得到检查,并且它本身在其方法Pipeline
中得到一些特殊处理。_sk_visual_block_
因此,根据您想要更改的具体内容,您可能需要在很多地方进行更改。我之前已经对文件中的_STYLE
常量进行了猴子修补estimator_html_repr.py
;由于没有太多的复合估计器,这可以很好地工作。
推荐阅读
- here-api - HERE Android SDK, Violation Notes 不重新调整违规注释数组
- python - 如何将字典列表转换为字节?
- android - 如何在应用程序中制作虚拟购物车?
- r - 从 UserId 生成 SessionId 和 TimeStamps 的差异,而不对 UserID 进行排序
- ruby-on-rails - Rails 6 和 Google Maps for Rails
- python - PySpark 将字符串化的字典数组分解为行
- java - Java中的可抛出方法覆盖
- julia - 如何将可选参数传递给 Julia 中的运算符
- ios - 为什么以模拟器为目标时,框架包路径解析为 DerivedData 构建目录?
- java - 在所有网络请求完成或其中一个失败后如何执行操作?