(tmp_path: Path)
| 279 | |
| 280 | @pytest.mark.skipif(**tm.no_sklearn()) |
| 281 | def test_sklearn_model(tmp_path: Path) -> None: |
| 282 | from sklearn.datasets import load_digits |
| 283 | from sklearn.model_selection import train_test_split |
| 284 | |
| 285 | model_path = tmp_path / "digits.model.json" |
| 286 | save_load_model(str(model_path)) |
| 287 | |
| 288 | model_path = tmp_path / "digits.model.ubj" |
| 289 | digits = load_digits(n_class=2) |
| 290 | y = digits["target"] |
| 291 | X = digits["data"] |
| 292 | booster = xgb.train( |
| 293 | {"tree_method": "hist", "objective": "binary:logistic"}, |
| 294 | dtrain=xgb.DMatrix(X, y), |
| 295 | num_boost_round=4, |
| 296 | ) |
| 297 | predt_0 = booster.predict(xgb.DMatrix(X)) |
| 298 | booster.save_model(model_path) |
| 299 | cls = xgb.XGBClassifier() |
| 300 | cls.load_model(model_path) |
| 301 | |
| 302 | proba = cls.predict_proba(X) |
| 303 | assert proba.shape[0] == X.shape[0] |
| 304 | assert proba.shape[1] == 2 # binary |
| 305 | |
| 306 | predt_1 = cls.predict_proba(X)[:, 1] |
| 307 | assert np.allclose(predt_0, predt_1) |
| 308 | |
| 309 | cls = xgb.XGBModel() |
| 310 | cls.load_model(model_path) |
| 311 | predt_1 = cls.predict(X) |
| 312 | assert np.allclose(predt_0, predt_1) |
| 313 | |
| 314 | # mclass |
| 315 | X, y = load_digits(n_class=10, return_X_y=True) |
| 316 | # small test_size to force early stop |
| 317 | X_train, X_test, y_train, y_test = train_test_split( |
| 318 | X, y, test_size=0.01, random_state=1 |
| 319 | ) |
| 320 | clf = xgb.XGBClassifier( |
| 321 | n_estimators=64, tree_method="hist", early_stopping_rounds=2 |
| 322 | ) |
| 323 | clf.fit(X_train, y_train, eval_set=[(X_test, y_test)]) |
| 324 | score = clf.best_score |
| 325 | intercept = clf.intercept_ |
| 326 | clf.save_model(model_path) |
| 327 | |
| 328 | clf = xgb.XGBClassifier() |
| 329 | clf.load_model(model_path) |
| 330 | assert clf.classes_.size == 10 |
| 331 | assert clf.objective == "multi:softprob" |
| 332 | np.testing.assert_allclose(intercept, clf.intercept_) |
| 333 | |
| 334 | np.testing.assert_equal(clf.classes_, np.arange(10)) |
| 335 | assert clf.n_classes_ == 10 |
| 336 | |
| 337 | assert clf.best_score == score |
| 338 |
nothing calls this directly
no test coverage detected