Demo for creating customized multi-class objective function
from
matplotlib
import
pyplot
as
plt
import
xgboost
as
xgb
(
1994
)
kRows
=
100
kCols
=
10
kClasses
=
4
kRounds
=
10
X
=
(
kRows
,
kCols
)
y
=
(
0
,
4
,
size
=
kRows
)
m
=
xgb
.
DMatrix
(
X
,
y
)
def
softmax
(
x
:
)
->
:
"""Softmax function with x as input vector."""
e
=
(
x
)
return
e
/
(
e
)
def
softprob_obj
(
predt
:
,
data
:
xgb
.
DMatrix
)
->
[
,
]:
"""Loss function. Computing the gradient and upper bound on the
Hessian with a diagonal structure for XGBoost (note that this is
not the true Hessian).
Reimplements the `multi:softprob` inside XGBoost.
"""
labels
=
data
.
get_label
()
if
data
.
get_weight
()
.
size
==
0
:
weights
=
((
kRows
,
1
),
dtype
=
float
)
else
:
weights
=
data
.
get_weight
()
assert
predt
.
shape
==
(
kRows
,
kClasses
)
grad
=
((
kRows
,
kClasses
),
dtype
=
float
)
hess
=
((
kRows
,
kClasses
),
dtype
=
float
)
eps
=
1e-6
for
r
in
range
(
predt
.
shape
[
0
]):
target
=
labels
[
r
]
p
=
softmax
(
predt
[
r
,
:])
for
c
in
range
(
predt
.
shape
[
1
]):
assert
target
>=
0
or
target
<=
kClasses
g
=
p
[
c
]
-
1.0
if
c
==
target
else
p
[
c
]
g
=
g
*
weights
[
r
]
h
=
max
((
2.0
*
p
[
c
]
*
(
1.0
-
p
[
c
])
*
weights
[
r
])
.
item
(),
eps
)
grad
[
r
,
c
]
=
g
hess
[
r
,
c
]
=
h
return
grad
,
hess
def
predict
(
booster
:
xgb
.
Booster
,
X
:
xgb
.
DMatrix
)
->
:
"""A customized prediction function that converts raw prediction to
target class.
"""
predt
=
booster
.
predict
(
X
,
output_margin
=
True
)
out
=
(
kRows
)
for
r
in
range
(
predt
.
shape
[
0
]):
i
=
(
predt
[
r
])
out
[
r
]
=
i
return
out
def
merror
(
predt
:
,
dtrain
:
xgb
.
DMatrix
)
->
[
str
,
]:
y
=
dtrain
.
get_label
()
assert
predt
.
shape
==
(
kRows
,
kClasses
)
out
=
(
kRows
)
for
r
in
range
(
predt
.
shape
[
0
]):
i
=
(
predt
[
r
])
out
[
r
]
=
i
assert
y
.
shape
==
out
.
shape
errors
=
(
kRows
)
errors
[
y
!=
out
]
=
1.0
return
"PyMError"
,
(
errors
)
/
kRows
def
plot_history
(
custom_results
:
[
str
,
],
native_results
:
[
str
,
]
)
->
None
:
axs
:
fig
,
axs
=
plt
.
subplots
(
2
,
1
)
ax0
=
axs
[
0
]
ax1
=
axs
[
1
]
pymerror
=
custom_results
[
"train"
][
"PyMError"
]
merror
=
native_results
[
"train"
][
"merror"
]
x
=
(
0
,
kRounds
,
1
)
ax0
.
plot
(
x
,
pymerror
,
label
=
"Custom objective"
)
ax0
.
legend
()
ax1
.
plot
(
x
,
merror
,
label
=
"multi:softmax"
)
ax1
.
legend
()
plt
.
show
()
def
main
(
args
:
)
->
None
:
intercept
=
(
shape
=
(
kClasses
,),
fill_value
=
1
/
kClasses
)
custom_results
:
[
str
,
]
=
{}
booster_custom
=
xgb
.
train
(
{
"num_class"
:
kClasses
,
"base_score"
:
intercept
,
"disable_default_eval_metric"
:
True
,
},
m
,
num_boost_round
=
kRounds
,
obj
=
softprob_obj
,
custom_metric
=
merror
,
evals_result
=
custom_results
,
evals
=
[(
m
,
"train"
)],
)
predt_custom
=
predict
(
booster_custom
,
m
)
native_results
:
[
str
,
]
=
{}
booster_native
=
xgb
.
train
(
{
"num_class"
:
kClasses
,
"base_score"
:
intercept
,
"objective"
:
"multi:softmax"
,
"eval_metric"
:
"merror"
,
},
m
,
num_boost_round
=
kRounds
,
evals_result
=
native_results
,
evals
=
[(
m
,
"train"
)],
)
predt_native
=
booster_native
.
predict
(
m
)
assert
(
predt_custom
==
predt_native
)
(
custom_results
[
"train"
][
"PyMError"
],
native_results
[
"train"
][
"merror"
]
)
if
args
.
plot
!=
0
:
plot_history
(
custom_results
,
native_results
)
if
__name__
==
"__main__"
:
parser
=
(
description
=
"Arguments for custom softmax objective function demo."
)
parser
.
add_argument
(
"--plot"
,
type
=
int
,
default
=
1
,
help
=
"Set to 0 to disable plotting the evaluation history."
,
)
args
=
parser
.
parse_args
()
main
(
args
)