如何获取xgboost预测的class个标签?
How to obtain class labels of xgboost predictions?
我正在使用类似于以下示例的 xgboost,其中我 "recode" 一些数值到 0,1,2 中的(数字)值表示 class 标签。请注意,我没有将其转换为因子变量。
然后我使用 xgboost 来拟合模型并生成预测。
library(xgboost)
iris$Species <- runif(nrow(iris))
recode <- function(x){
if(x >= 0 & x <= 0.33){
x <- 0
} else if(x > 0.33 & x <= 0.66){
x <- 1
} else if(x > 0.66){
x <- 2
}
}
train <- xgb.DMatrix(data = as.matrix(iris[,-5]),
label = sapply(iris$Species, FUN = recode))
bst <- xgboost(data = train,
max_depth = 4, eta = 0.5, nrounds = 10,
objective = "multi:softprob",
num_class = 3)
pred <- predict(bst, as.matrix(iris[, -5]), reshape = TRUE)
str(pred)
有没有办法获取预测矩阵的列标签?或者我可以确定它们是根据我重新编码输入的数值排序的吗?
这些列的顺序与您的标签相同,因此是 0,1 和 2。可以肯定的是,您可以做一个混淆矩阵来检查您是否正确预测它:
library(xgboost)
set.seed(100)
iris$Species <- runif(nrow(iris))
train <- xgb.DMatrix(data = as.matrix(iris[,-5]),
label = sapply(iris$Species, FUN = recode))
bst <- xgboost(data = train,
max_depth = 4, eta = 0.5, nrounds = 10,
objective = "multi:softprob",
num_class = 3)
pred <- predict(bst, as.matrix(iris[, -5]), reshape = TRUE)
# which.max tells you which column is most probable
# we convert them back to 0-2, assuming column 1 corresponds to 0
predicted = apply(pred,1,which.max)-1
actual = sapply(iris$Species,recode)
table(predicted,actual)
结果是:
actual
predicted 0 1 2
0 36 2 2
1 4 48 4
2 6 3 45
所以大多数预测为 0,1 或 2 的结果都遵循最可能的 class 预测。
或者如果您使用插入符号:
caret::confusionMatrix(factor(predicted,levels=1:3),factor(actual,levels=1:3))
我正在使用类似于以下示例的 xgboost,其中我 "recode" 一些数值到 0,1,2 中的(数字)值表示 class 标签。请注意,我没有将其转换为因子变量。
然后我使用 xgboost 来拟合模型并生成预测。
library(xgboost)
iris$Species <- runif(nrow(iris))
recode <- function(x){
if(x >= 0 & x <= 0.33){
x <- 0
} else if(x > 0.33 & x <= 0.66){
x <- 1
} else if(x > 0.66){
x <- 2
}
}
train <- xgb.DMatrix(data = as.matrix(iris[,-5]),
label = sapply(iris$Species, FUN = recode))
bst <- xgboost(data = train,
max_depth = 4, eta = 0.5, nrounds = 10,
objective = "multi:softprob",
num_class = 3)
pred <- predict(bst, as.matrix(iris[, -5]), reshape = TRUE)
str(pred)
有没有办法获取预测矩阵的列标签?或者我可以确定它们是根据我重新编码输入的数值排序的吗?
这些列的顺序与您的标签相同,因此是 0,1 和 2。可以肯定的是,您可以做一个混淆矩阵来检查您是否正确预测它:
library(xgboost)
set.seed(100)
iris$Species <- runif(nrow(iris))
train <- xgb.DMatrix(data = as.matrix(iris[,-5]),
label = sapply(iris$Species, FUN = recode))
bst <- xgboost(data = train,
max_depth = 4, eta = 0.5, nrounds = 10,
objective = "multi:softprob",
num_class = 3)
pred <- predict(bst, as.matrix(iris[, -5]), reshape = TRUE)
# which.max tells you which column is most probable
# we convert them back to 0-2, assuming column 1 corresponds to 0
predicted = apply(pred,1,which.max)-1
actual = sapply(iris$Species,recode)
table(predicted,actual)
结果是:
actual
predicted 0 1 2
0 36 2 2
1 4 48 4
2 6 3 45
所以大多数预测为 0,1 或 2 的结果都遵循最可能的 class 预测。
或者如果您使用插入符号:
caret::confusionMatrix(factor(predicted,levels=1:3),factor(actual,levels=1:3))