Demo for prediction using individual trees and model slices
CURRENT_DIR
=
(
__file__
)
train
=
(
CURRENT_DIR
,
"../data/agaricus.txt.train"
)
test
=
(
CURRENT_DIR
,
"../data/agaricus.txt.test"
)
def
individual_tree
()
->
None
:
"""Get prediction from each individual tree and combine them together."""
X_train
,
y_train
=
(
train
)
X_test
,
y_test
=
(
test
)
Xy_train
=
xgb
.
QuantileDMatrix
(
X_train
,
y_train
)
n_rounds
=
4
base_score
=
0.5
params
=
{
"max_depth"
:
2
,
"eta"
:
1
,
"objective"
:
"reg:logistic"
,
"tree_method"
:
"hist"
,
"base_score"
:
base_score
,
}
booster
=
xgb
.
train
(
params
,
Xy_train
,
num_boost_round
=
n_rounds
)
scores
=
((
X_test
.
shape
[
0
],),
(
base_score
))
for
i
in
range
(
n_rounds
):
Xy_test
=
xgb
.
DMatrix
(
X_test
,
base_margin
=
scores
)
if
i
==
n_rounds
-
1
:
scores
=
booster
.
predict
(
Xy_test
,
iteration_range
=
(
i
,
i
+
1
),
output_margin
=
False
)
else
:
scores
=
booster
.
predict
(
Xy_test
,
iteration_range
=
(
i
,
i
+
1
),
output_margin
=
True
)
full
=
booster
.
predict
(
xgb
.
DMatrix
(
X_test
),
output_margin
=
False
)
(
scores
,
full
)
def
model_slices
()
->
None
:
"""Inference with each individual tree using model slices."""
X_train
,
y_train
=
(
train
)
X_test
,
y_test
=
(
test
)
Xy_train
=
xgb
.
QuantileDMatrix
(
X_train
,
y_train
)
n_rounds
=
4
base_score
=
0.5
params
=
{
"max_depth"
:
2
,
"eta"
:
1
,
"objective"
:
"reg:logistic"
,
"tree_method"
:
"hist"
,
"base_score"
:
base_score
,
}
booster
=
xgb
.
train
(
params
,
Xy_train
,
num_boost_round
=
n_rounds
)
trees
=
[
booster
[
t
]
for
t
in
range
(
n_rounds
)]
scores
=
((
X_test
.
shape
[
0
],),
(
base_score
))
for
i
,
t
in
enumerate
(
trees
):
Xy_test
=
xgb
.
DMatrix
(
X_test
,
base_margin
=
scores
)
if
i
==
n_rounds
-
1
:
scores
=
t
.
predict
(
Xy_test
,
output_margin
=
False
)
else
:
scores
=
t
.
predict
(
Xy_test
,
output_margin
=
True
)
full
=
booster
.
predict
(
xgb
.
DMatrix
(
X_test
),
output_margin
=
False
)
(
scores
,
full
)
if
__name__
==
"__main__"
:
individual_tree
()
model_slices
()