check_is_fitted#

sklearn.utils.validation.check_is_fitted(estimator, attributes=None, *, msg=None, all_or_any=<built-in function all>)[source]#

对估算器执行 is_fitted 验证。

通过检查拟合属性(以尾部下划线结尾)是否存在来检查估计器是否已拟合,否则会引发带有给定消息的 NotFittedError

如果估计器没有设置任何带有尾部下划线的属性,它可以定义一个返回布尔值的 __sklearn_is_fitted__ 方法来指定估计器是否已拟合。有关如何使用此 API 的示例,请参阅 __sklearn_is_fitted__ 作为开发人员 API

如果未传递任何 attributes,并且估计器是无状态的,则此函数将通过。估计器可以通过设置 requires_fit 标签来指示其为无状态。有关更多信息,请参阅 估计器标签。请注意,如果传递了 attributes,则会忽略 requires_fit 标签。

参数:
estimatorestimator instance

将执行检查的估计器实例。

attributesstr, list or tuple of str, default=None

作为字符串或字符串列表/元组提供的属性名称。例如:["coef_", "estimator_", ...], "coef_"

如果为 None,则当估计器存在一个以尾部下划线结尾且不以双下划线开头的属性时,该估计器被视为已拟合。

msgstr, default=None

默认错误消息是:“此 %(name)s 实例尚未拟合。在使用此估计器之前,请调用具有适当参数的‘fit’。”

对于自定义消息,如果消息字符串中存在“%(name)s”,则会将其替换为估计器名称。

例如:“估计器 %(name)s 必须在稀疏化之前拟合”。

all_or_anycallable, {all, any}, default=all

指定是必须存在所有给定属性还是存在任何一个即可。

Raises:
TypeError

如果估计器是类或不是估计器实例

NotFittedError

如果找不到属性。

示例

>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.utils.validation import check_is_fitted
>>> from sklearn.exceptions import NotFittedError
>>> lr = LogisticRegression()
>>> try:
...     check_is_fitted(lr)
... except NotFittedError as exc:
...     print(f"Model is not fitted yet.")
Model is not fitted yet.
>>> lr.fit([[1, 2], [1, 3]], [1, 0])
LogisticRegression()
>>> check_is_fitted(lr)