Collection of examples for using sklearn interface
fetch_california_housing
,
,
,
,
)
from
sklearn.metrics
import
,
from
sklearn.model_selection
import
,
,
import
xgboost
as
xgb
rng
=
(
31337
)
print
(
"Zeros and Ones from the Digits dataset: binary classification"
)
digits
=
(
n_class
=
2
)
y
=
digits
[
"target"
]
X
=
digits
[
"data"
]
kf
=
(
n_splits
=
2
,
shuffle
=
True
,
random_state
=
rng
)
for
train_index
,
test_index
in
kf
.
split
(
X
):
xgb_model
=
xgb
.
XGBClassifier
(
n_jobs
=
1
)
.
fit
(
X
[
train_index
],
y
[
train_index
])
predictions
=
xgb_model
.
predict
(
X
[
test_index
])
actuals
=
y
[
test_index
]
print
(
(
actuals
,
predictions
))
print
(
"Iris: multiclass classification"
)
iris
=
()
y
=
iris
[
"target"
]
X
=
iris
[
"data"
]
kf
=
(
n_splits
=
2
,
shuffle
=
True
,
random_state
=
rng
)
for
train_index
,
test_index
in
kf
.
split
(
X
):
xgb_model
=
xgb
.
XGBClassifier
(
n_jobs
=
1
)
.
fit
(
X
[
train_index
],
y
[
train_index
])
predictions
=
xgb_model
.
predict
(
X
[
test_index
])
actuals
=
y
[
test_index
]
print
(
(
actuals
,
predictions
))
print
(
"California Housing: regression"
)
try
:
X
,
y
=
(
return_X_y
=
True
)
except
:
X
,
y
=
(
n_samples
=
20640
,
n_features
=
8
,
random_state
=
1234
)
kf
=
(
n_splits
=
2
,
shuffle
=
True
,
random_state
=
rng
)
for
train_index
,
test_index
in
kf
.
split
(
X
):
xgb_model
=
xgb
.
XGBRegressor
(
n_jobs
=
1
)
.
fit
(
X
[
train_index
],
y
[
train_index
])
predictions
=
xgb_model
.
predict
(
X
[
test_index
])
actuals
=
y
[
test_index
]
print
(
(
actuals
,
predictions
))
print
(
"Parameter optimization"
)
xgb_model
=
xgb
.
XGBRegressor
(
n_jobs
=
1
)
clf
=
(
xgb_model
,
{
"max_depth"
:
[
2
,
4
],
"n_estimators"
:
[
50
,
100
]},
verbose
=
1
,
n_jobs
=
1
,
cv
=
3
,
)
clf
.
fit
(
X
,
y
)
print
(
clf
.
best_score_
)
print
(
clf
.
best_params_
)
print
(
"Pickling sklearn API models"
)
(
clf
,
open
(
"best_calif.pkl"
,
"wb"
))
clf2
=
(
open
(
"best_calif.pkl"
,
"rb"
))
print
(
(
clf
.
predict
(
X
),
clf2
.
predict
(
X
)))
X
=
digits
[
"data"
]
y
=
digits
[
"target"
]
X_train
,
X_test
,
y_train
,
y_test
=
(
X
,
y
,
random_state
=
0
)
clf
=
xgb
.
XGBClassifier
(
n_jobs
=
1
,
early_stopping_rounds
=
10
,
eval_metric
=
"auc"
)
clf
.
fit
(
X_train
,
y_train
,
eval_set
=
[(
X_test
,
y_test
)])