scikit-learn 源码阅读指南

March 17, 2024

读源码前:Cython 基础

Cython 的文件类型

.pyx:与 .py 类似,是存放实现的源文件。

.pxi:可以包含实现和声明。原笔记将它列为旧式做法。

.pxd:主要用于声明。 与同名 .pyx 或 .py 文件配套时,它为模块提供 Cython 接口,便于其他 Cython 模块通过比 Python 调用更高效的方式与之通信。 它也可以包含内联实现。 例如:

cdef inline int int_min(int a, int b):
    return b if b < a else a

.pxi 与 .pxd 的区别:

详细来说,.pxd 是声明文件,可以声明 C 扩展模块中的类、方法等(通常由同名 .pyx 实现)。它主要包含声明,没有一般的可执行语句。Cython 的 cimport 可以像 Python 的 import 一样导入这些名称。两个独立模块从同一个 .pxd 导入时,会得到同一组对象。

.pxi 是按文本插入的包含文件,类似 C 的 #include,可以包含插入位置允许的任何 Cython 代码。实现也会复制到每个引用位置,例如共用的 cdef inline 函数。如果 a.pxi 声明类 A,而 b.pyx 和 c.pyx 都包含它,就会得到两个不同的类 b.A 和 c.A。C 库(包括 Python/C API)的接口过去常用 .pxi 声明,因为这类声明不隶属某个特定模块。每次使用都要重新解析。

支持 cimport * 后,外部声明就不必再用 .pxi 来组织。

.pyd、.so:Python 的 C 或 C++ 扩展编译后的产物。

# setup.py
from distutils.core import setup, Extension

module1 = Extension('demo',
                    sources = ['demo.c'])

setup (name = 'PackageName',
       version = '1.0',
       description = 'This is a demo package',
       ext_modules = [module1])

具备这里的 setup.py 和 demo.c 后,运行 python setup.py build 就会编译 demo.c,在 build 目录下生成名为 demo 的扩展模块。具体位置可能是 build/lib.system 一类的子目录,文件名随系统而异,例如 demo.so 或 demo.pyd。

参考资料

  1. Cython 3.1.0a0 documentation » Tutorials » pxd files (n.d.). cython documentation. Retrieved April 3, 2024, from https://cython.readthedocs.io/en/latest/src/tutorial/pxd_files.html

  2. Cython 3.1.0a0 documentation » Users Guide » FAQ (n.d.). cython documentation. Retrieved April 3, 2024, from https://cython.readthedocs.io/en/latest/src/userguide/faq.html#what-is-the-difference-between-a-pxd-and-pxi-file-when-should-either-be-used https://cython.readthedocs.io/en/latest/src/userguide/faq.html#what-is-better-a-single-big-module-or-multiple-separate-modules

  3. 3.10.13 Documentation » Extending and Embedding the Python Interpreter » 4. Building C and C++ Extensions(n.d.). python documentation. Retrieved April 3, 2024, from https://docs.python.org/3.10/extending/building.html#building-c-and-c-extensions-with-distutils

延伸阅读

  1. rrr2. (31 Mar, 2019). Cython 的 .pyx .pyd 文件格式. CSDN. [Blog post]. Retrieved April 3, 2024, from https://blog.csdn.net/qq_35608277/article/details/88937904

Cython 的 def 与 cdef

主要差别在于调用方。def 函数可由 Python 和 Cython 调用,cdef 函数面向 Cython 和 C 调用。

cpdef 函数: Cython 会为 cpdef 生成一个便于 Cython 快速调用的 cdef 函数,以及一个供 Python 调用的 def 包装函数。后者在内部调用前者。参数类型要同时满足 cdef 和 def 的限制。

参考资料

  • DavidW(2017 年 2 月 1 日)答:cdef 函数不能嵌套定义,因为 C 函数指针没有可存放捕获变量的位置。比如在 def g(a) 内定义引用 a 的 cdef 函数就是非法的。cdef 也不能接收 *args 或 kwargs,因为它们不容易转换为 C 签名。它的好处是参数可用指针等没有 Python 对应物的类型,也可显式指定返回类型;省略时返回 Python 对象,即 C 中的 PyObject。def 必须能从 Python 调用,始终返回 Python 对象。例如 cdef int h(int a) 可以取指针的第一个元素并返回整数。cdef 能编译成简单的 C 调用,因此调用开销较小。Stack Overflow。https://stackoverflow.com/questions/28362009/definition-of-def-cdef-and-cpdef-in-cython/41976772#41976772

meson.build 与 Meson 构建系统

与 CMake 类似,Meson 会选择适合的后端来实际构建。例如 GNU/Linux 上用 Ninja,Windows 上可用 Visual Studio,macOS 上可用 Xcode。

例如:

# scikit-learn/sklearn/ensemble/meson.build
py.extension_module(
  '_gradient_boosting',
  ['_gradient_boosting.pyx'] + utils_cython_tree,
  dependencies: [np_dep],
  cython_args: cython_args,
  subdir: 'sklearn/ensemble',
  install: true
)

subdir('_hist_gradient_boosting')

subdir() 告诉构建系统下一步应进入哪个子目录继续构建。

延伸阅读

  1. QQVQQ.... (24 April, 2023.). Meson构建系统的使用. CSDN. [Blog post]. Retrieved April 3, 2024, from https://blog.csdn.net/hfy1237/article/details/130261785

  2. espresso_yu. (20 Sept, 2020). Meson构建系统(一). CSDN. [Blog post]. Retrieved April 3, 2024, from https://blog.csdn.net/u010074726/article/details/108695256

面向对象中的 mixin

scikit-learn 大量使用 mixin(混入类)。

Mixin 是多重继承的一种特定用法。常见场景有两类:

  1. 希望给一个类提供许多可以按需组合的功能。
  2. 希望在多个不同的类里复用同一项功能。

Mixin 的设计意图之一,就是减少直接使用多重继承时的混乱。

参考资料

  1. Jason Baker(2009 年 2 月 13 日)答:mixin 尤其适用于想给一个类提供许多可选功能,或想让许多类复用同一功能的场景。Stack Overflow。https://stackoverflow.com/questions/533631/what-is-a-mixin-and-why-is-it-useful/547714#547714

  2. Wealong. (July 22, 2015). 如楼上很多答主一样,谈到Mixin就不得不谈到多重继承,因为Mixin的出现就是为了解决多重继承的问题,那么多重继承有什么问题呢?在《松本行弘的程序世界》一书中,作者列举了以下三点:结构复杂化:如果是单一继承,一个类的父类是什么,父类的父类是什么,都很明确,因为只有单一的继承关系,然而如果是多重继承的话,一个类有多个父类,这些父类又有自己的父类,那么类之间的关系就很复杂了。优先顺序模糊:假如我有A,C类同时继承了基类,B类继承了A类,然后D类又同时继承了B和C类,所以D类继承父类的方法的顺序应该是D、B、A、C还是D、B、C、A,或者是其他的顺序,很不明确。功能冲突:因为多重继承有多个父类,所以当不同的父类中有相同的方法是就会产生冲突。如果B类和C类同时又有相同的方法时,D继承的是哪个方法就不明确了,因为存在两种可能性。当然你可以说有些语言解决了这个问题,但是并不是所有语言都想要去纠结这个问题。所以为能够利用多继承的优点又解决多继承的问题,提出了规格继承和实现继承这两样东西。简单来讲,规格继承指的是一堆方法名的集合,而实现继承除了方法名还允许有方法的实现。Java 选择了规格继承,在 Java 中叫 interface(不过Java8中已经有默认方法了),而 Ruby 选择了实现继承,也可以叫Mixin,在 Ruby 中叫 module。从某种程度上来说,继承强调 I am,Mixin 强调 I can。当你 implement 了这个接口或者 include 这个 module 的时候,然后就你行你上。. [Answer]. zhihu. https://www.zhihu.com/question/20778853/answer/55983839

  3. Anonymous User. (Mar 5, 2022). Mixin的规矩当我们用SomeMixin去命名一个类并进行合理实现时,一般意味着:不认为它是个基类(但在语言层面它就是一个可被继承的基类),因此不会在其中去写属于实际类内涵的属性和方法;纯粹的Mixin不需要依赖基类的属性或方法 —— 椰果不是一种奶茶它能独立地实现一些功能,通常只写方法和方法必须的内部变量,Mixin内部的方法间往往有相互调用的关系,形成一个联系紧密的功能集合 —— 椰果可以单独吃写实际类时继承这个Mixin,就会获得它的功能;实际类不覆盖所继承Mixin的属性和方法,因此不需要也不会调用super()函数去取Mixin中的方法 —— 倒进去了,杯子里就有椰果,椰果也还是椰果可能被同时继承的Mixin之间没有重复的方法或属性,因此不用关心继承的顺序 —— 椰果是椰果、牛奶是牛奶多重继承基类和Mixin构成我们想要的类——加好各种原料奶茶就可以喝了(注意:比喻可以帮助理解,但并不精确). [Answer]. zhihu. https://www.zhihu.com/question/20778853/answer/2374758411

项目整体结构

基类

可以把 sklearn 看成一棵树,估计器是果实,支撑它们的树干则是少数几个基类。常见的有 BaseEstimator、BaseSGD、ClassifierMixin 和 RegressorMixin。

BaseEstimator

底层的 BaseEstimator 主要提供 set_params 和 get_params 两个方法。

ClassifierMixin

Mixin 可以理解为通过混入一个类给其他类增加方法。这里讨论的分类和回归混入类提供 score,继承它们的类仍需自行实现 fit、predict 等方法。

参考资料

  1. chandlertu. (2020, Mar 23). Scikit-Learn 源码研读 (第二期)基类的实现细节 [Blog post]. Retrieved from https://www.cnblogs.com/learn-the-hard-way/p/12532888.html#baseestimator

决策树与集成学习

决策树的 Cython 与 Python 实现

_tree.pyx 包含树模型的主要结构,负责树的节点和层次构建,由 Cython 类 Tree 封装。生成节点有两种办法,分别由 DepthFirstTreeBuilder 和 BestFirstTreeBuilder 实现。二者继承 TreeBuilder,以复用 _check_input:检查输入类型并转换为连续的内存布局,例如用 np.asfortranarray 和 np.ascontiguousarray,加快计算和索引。

在 sklearn/tree/tree.py 和 sklearn/base.py 中,BaseDecisionTree 继承 BaseEstimator,后者给预测器提供 get_params 等基础接口。ClassifierMixin 和 RegressorMixin 提供 score 方法。

AdaBoost

weight_boosting.py 在这里阅读的实现中,AdaBoost 对外提供 AdaBoostClassifier 和 AdaBoostRegressor。它们扩展基本算法以支持多分类和回归,均继承 BaseWeightBoosting 和 BaseEnsemble。 一个细节是,二分类 AdaBoost 对基学习器有优于随机猜测(准确率超过 50%)的要求。推导依赖这个条件,因此源码也会检查这一限制。

梯度提升决策树(GBDT)

基本调用顺序是 fit() → fit_stages() → fit_stage。 省略实现细节后,接口如下:

def fit(self, X, y, sample_weight=None, monitor=None):
    """Fit the gradient boosting model.    
    Parameters
    ----------
    X : {array-like, sparse matrix} of shape (n_samples, n_features)
        The input samples. Internally, it will be converted to
        ``dtype=np.float32`` and if a sparse matrix is provided
        to a sparse ``csr_matrix``.

    y : array-like of shape (n_samples,)
        Target values (strings or integers in classification, real numbers
        in regression)
        For classification, labels must correspond to classes.

    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights. If None, then samples are equally weighted. Splits
        that would create child nodes with net zero or negative weight are
        ignored while searching for a split in each node. In the case of
        classification, splits are also ignored if they would result in any
        single class carrying a negative weight in either child node.

    monitor : callable, default=None
        The monitor is called after each iteration with the current
        iteration, a reference to the estimator and the local variables of
        ``_fit_stages`` as keyword arguments ``callable(i, self,
        locals())``. If the callable returns ``True`` the fitting procedure
        is stopped. The monitor can be used for various things such as
        computing held-out estimates, early stopping, model introspect, and
        snapshotting.

    Returns
    -------
    self : object
        Fitted estimator.
    """

    self.fit_stages()
    
def _fit_stages(
    self,
    X,
    y,
    raw_predictions,
    sample_weight,
    random_state,
    X_val,
    y_val,
    sample_weight_val,
    begin_at_stage=0,
    monitor=None,
):
    """Iteratively fits the stages.

    For each stage it computes the progress (OOB, train score)
    and delegates to ``_fit_stage``.
    Returns the number of stages fit; might differ from ``n_estimators``
    due to early stopping.
    """
    for i in range(begin_at_stage, self.n_estimators):
      # fit next stage of trees
      raw_predictions = self._fit_stage()

def _fit_stage(
    self,
    i,
    X,
    y,
    raw_predictions,
    sample_weight,
    sample_mask,
    random_state,
    X_csc=None,
    X_csr=None,
):
    """Fit another stage of ``n_trees_per_iteration_`` trees."""

参考资料

  1. Rrui_739. (May 30, 2019). sklearn源码解读:1.10 Decision Trees & 1.11 Ensemble methods. CSDN. [Blog post]. Retrieved April 3, 2024, from https://blog.csdn.net/Rrui7739/article/details/90669812
  2. scikit-learn/sklearn/ensemble/_gb.py - BaseGradientBoosting._fit_stage. branch main. commit b38b7f3. https://github.com/scikit-learn/scikit-learn/blob/main/sklearn/ensemble/_gb.py

© 2024 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2024-03-17). scikit-learn 源码阅读指南. https://caiborui.com/blog/2024-03-17-en-sklearn-source-code-review-zhtrans

@misc{borui2024-209e9b54,
  author = {borui},
  title = {{scikit-learn 源码阅读指南}},
  year = {2024},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2024-03-17-en-sklearn-source-code-review-zhtrans}
}