Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return base score as intercept. #9486

Merged
merged 2 commits into from
Aug 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions python-package/xgboost/sklearn.py
Original file line number Diff line number Diff line change
Expand Up @@ -1359,25 +1359,25 @@ def coef_(self) -> np.ndarray:

@property
def intercept_(self) -> np.ndarray:
"""
Intercept (bias) property

.. note:: Intercept is defined only for linear learners
"""Intercept (bias) property

Intercept (bias) is only defined when the linear model is chosen as base
learner (`booster=gblinear`). It is not defined for other base learner types,
such as tree learners (`booster=gbtree`).
For tree-based model, the returned value is the `base_score`.

Returns
-------
intercept_ : array of shape ``(1,)`` or ``[n_classes]``

"""
if self.get_xgb_params()["booster"] != "gblinear":
raise AttributeError(
f"Intercept (bias) is not defined for Booster type {self.booster}"
)
booster_config = self.get_xgb_params()["booster"]
b = self.get_booster()
return np.array(json.loads(b.get_dump(dump_format="json")[0])["bias"])
if booster_config != "gblinear": # gbtree, dart
config = json.loads(b.save_config())
intercept = config["learner"]["learner_model_param"]["base_score"]
return np.array([float(intercept)], dtype=np.float32)

return np.array(
json.loads(b.get_dump(dump_format="json")[0])["bias"], dtype=np.float32
)


PredtT = TypeVar("PredtT", bound=np.ndarray)
Expand Down
16 changes: 16 additions & 0 deletions tests/python/test_with_sklearn.py
Original file line number Diff line number Diff line change
Expand Up @@ -1507,6 +1507,7 @@ def merror(y_true: np.ndarray, predt: np.ndarray):
# shape check inside the `merror` function
clf.fit(X, y, eval_set=[(X, y)])


def test_weighted_evaluation_metric():
from sklearn.datasets import make_hastie_10_2
from sklearn.metrics import log_loss
Expand Down Expand Up @@ -1544,3 +1545,18 @@ def test_weighted_evaluation_metric():
internal["validation_0"]["logloss"],
atol=1e-6
)


def test_intercept() -> None:
X, y, w = tm.make_regression(256, 3, use_cupy=False)
reg = xgb.XGBRegressor()
reg.fit(X, y, sample_weight=w)
result = reg.intercept_
assert result.dtype == np.float32
assert result[0] < 0.5

reg = xgb.XGBRegressor(booster="gblinear")
reg.fit(X, y, sample_weight=w)
result = reg.intercept_
assert result.dtype == np.float32
assert result[0] < 0.5