Skip to content

Commit 5086dec

Browse files
authored
[R] Reshape predictions for custom eval metric when they are 2D (dmlc#10323)
1 parent 95ba099 commit 5086dec

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

R-package/R/utils.R

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ xgb.iter.eval <- function(bst, evals, iter, feval) {
213213
res <- sapply(seq_along(evals), function(j) {
214214
w <- evals[[j]]
215215
## predict using all trees
216-
preds <- predict(bst, w, outputmargin = TRUE, iterationrange = "all")
216+
preds <- predict(bst, w, outputmargin = TRUE, reshape = TRUE, iterationrange = "all")
217217
eval_res <- feval(preds, w)
218218
out <- eval_res$value
219219
names(out) <- paste0(evnames[j], "-", eval_res$metric)

R-package/tests/testthat/test_custom_objective.R

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,3 +147,34 @@ test_that("custom objective with multi-class works", {
147147

148148
expect_equal(custom_predt, builtin_predt)
149149
})
150+
151+
test_that("custom metric with multi-target passes reshaped data to feval", {
152+
x <- as.matrix(iris[, -5])
153+
y <- as.numeric(iris$Species) - 1
154+
dtrain <- xgb.DMatrix(data = x, label = y)
155+
156+
multinomial.ll <- function(predt, dtrain) {
157+
expect_equal(dim(predt), c(nrow(iris), 3L))
158+
y <- getinfo(dtrain, "label")
159+
probs <- apply(predt, 1, softmax) |> t()
160+
probs.y <- probs[cbind(seq(1L, nrow(predt)), y + 1L)]
161+
ll <- sum(log(probs.y))
162+
return(list(metric = "multinomial-ll", value = -ll))
163+
}
164+
165+
model <- xgb.train(
166+
params = list(
167+
objective = "multi:softmax",
168+
num_class = 3L,
169+
base_score = 0,
170+
disable_default_eval_metric = TRUE,
171+
max_depth = 123,
172+
seed = 123
173+
),
174+
data = dtrain,
175+
nrounds = 2L,
176+
evals = list(Train = dtrain),
177+
eval_metric = multinomial.ll,
178+
verbose = 0
179+
)
180+
})

0 commit comments

Comments
 (0)