跳到内容

将先前计算的特征重要性表示为条形图。

  • 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

一个 data.table,由 xgb.importance() 返回。

top_n

要包含在图中排名前列的特征的最大数量。

measure

要绘制的重要性度量名称。当为 NULL 时,树模型使用 'Gain',线性模型使用 'Weight'。

rel_to_first

重要性值是否应表示为相对于排名最高的特征,详见详细信息。

n_clusters

一个数值向量,包含条形图可能簇数量的最小和最大范围。

...

传递给 graphics::barplot() 的其他参数(除了 horiz, border, cex.names, names.arglas)。仅在 xgb.plot.importance() 中使用。

left_margin

调整左侧边距大小以适应特征名称。当为 NULL 时,使用现有的 par("mar")

cex

作为 cex.names 参数传递给 graphics::barplot()

plot

是否应显示条形图?默认为 TRUE

返回值

返回值取决于调用的函数

  • xgb.plot.importance(): 不可见地返回一个包含按重要性排序的 n_top 特征的 "data.table"。如果 plot = TRUE,这些值也会被绘制成条形图。

  • xgb.ggplot.importance(): 一个可定制的 "ggplot" 对象。例如,要更改标题,设置 + ggtitle("图形名称")

详细信息

图表将每个特征表示为一个水平条,其长度与特征的重要性成比例。特征按重要性降序排列。它适用于 "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")