RegressorMixin#

class sklearn.base.RegressorMixin[source]#

scikit-learn 中所有回归估算器的 Mixin 类。

此 mixin 定义了以下功能:

  • 通过 estimator_type 标签将估计器类型设置为 "regressor"

  • score 方法,默认使用 r2_score

  • 通过设置回归器类型标签,强制要求 fit 方法必须传入 y(通过 requires_y 标签实现)。

用户指南中阅读更多内容。

示例

>>> import numpy as np
>>> from sklearn.base import BaseEstimator, RegressorMixin
>>> # Mixin classes should always be on the left-hand side for a correct MRO
>>> class MyEstimator(RegressorMixin, BaseEstimator):
...     def __init__(self, *, param=1):
...         self.param = param
...     def fit(self, X, y=None):
...         self.is_fitted_ = True
...         return self
...     def predict(self, X):
...         return np.full(shape=X.shape[0], fill_value=self.param)
>>> estimator = MyEstimator(param=0)
>>> X = np.array([[1, 2], [2, 3], [3, 4]])
>>> y = np.array([-1, 0, 1])
>>> estimator.fit(X, y).predict(X)
array([0, 0, 0])
>>> estimator.score(X, y)
0.0
score(X, y, sample_weight=None)[source]#

返回测试数据的 决定系数

决定系数 \(R^2\) 定义为 \((1 - \frac{u}{v})\),其中 \(u\) 是残差平方和 ((y_true - y_pred)** 2).sum()\(v\) 是总平方和 ((y_true - y_true.mean()) ** 2).sum()。最佳得分为 1.0,得分可能为负数(因为模型可能任意地差)。一个总是预测 y 的期望值而忽略输入特征的常数模型将获得 0.0 的 \(R^2\) 分数。

参数:
Xshape 为 (n_samples, n_features) 的 array-like

测试样本。对于某些估计器,这可能是一个预先计算的核矩阵或一个通用对象列表,形状为 (n_samples, n_samples_fitted),其中 n_samples_fitted 是用于估计器拟合的样本数。

yshape 为 (n_samples,) 或 (n_samples, n_outputs) 的 array-like

X 的真实值。

sample_weightshape 为 (n_samples,) 的 array-like, default=None

样本权重。

返回:
scorefloat

self.predict(X) 相对于 y\(R^2\)

注意事项

在版本 0.23 中,当在回归器上调用 score 时使用的 \(R^2\) 分数使用 multioutput='uniform_average',以与 r2_score 的默认值保持一致。这会影响所有多输出回归器(除了 MultiOutputRegressor)的 score 方法。