将之前计算的特征重要性表示为条形图。
xgb.plot.importance()使用基础 R 图形,而xgb.ggplot.importance()使用 "ggplot"。
用法
xgb.ggplot.importance(
importance_matrix = NULL,
top_n = NULL,
measure = NULL,
rel_to_first = FALSE,
n_clusters = seq_len(10),
...
)
xgb.plot.importance(
importance_matrix = NULL,
top_n = NULL,
measure = NULL,
rel_to_first = FALSE,
left_margin = 10,
cex = NULL,
plot = TRUE,
...
)参数
- importance_matrix
一个由
xgb.importance()返回的data.table。- top_n
包含在图中最重要的特征的最大数量。
- measure
要绘制的重要性度量的名称。当为
NULL时,树模型将使用 'Gain',gblinear 模型将使用 'Weight'。- rel_to_first
重要性值是否应表示为相对于排名最高的特征,详见“详细信息”。
- n_clusters
一个数值向量,包含条形可能聚类数量的最小值和最大值范围。
- ...
传递给
graphics::barplot()的其他参数(除了horiz、border、cex.names、names.arg和las)。仅用于xgb.plot.importance()。- left_margin
调整左边距大小以适应特征名称。当为
NULL时,使用现有的par("mar")。- cex
作为
cex.names参数传递给graphics::barplot()。- plot
是否显示条形图?默认为
TRUE。
值
返回值取决于函数
xgb.plot.importance():隐式返回一个 "data.table",其中包含按重要性排序的n_top个特征。如果plot = TRUE,这些值也会以条形图形式绘制。xgb.ggplot.importance():一个可自定义的 "ggplot" 对象。例如,要更改标题,请设置+ ggtitle("A GRAPH NAME")。
详细信息
该图将每个特征表示为水平条,其长度与特征的重要性成比例。特征按重要性递减排序。它适用于 "gblinear" 和 "gbtree" 模型。
当 rel_to_first = FALSE 时,值将按 importance_matrix 中的方式绘制。对于 "gbtree" 模型,这意味着归一化到总和为 1(“特征对整个模型的贡献度是多少?”)。对于线性模型,rel_to_first = FALSE 将显示系数的实际值。设置 rel_to_first = TRUE 可以从“特征对最重要特征的贡献度是多少?”的角度来看待情况。
"ggplot" 后端对重要性值执行一维聚类,条形颜色对应于具有相似重要性值的不同聚类。
示例
data(agaricus.train)
## Keep the number of threads to 2 for examples
nthread <- 2
data.table::setDTthreads(nthread)
model <- xgboost(
agaricus.train$data, factor(agaricus.train$label),
nrounds = 2,
max_depth = 3,
nthreads = nthread
)
importance_matrix <- xgb.importance(model)
xgb.plot.importance(
importance_matrix, rel_to_first = TRUE, xlab = "Relative importance"
)
gg <- xgb.ggplot.importance(
importance_matrix, measure = "Frequency", rel_to_first = TRUE
)
gg
gg + ggplot2::ylab("Frequency")