跳到内容

创建一个特征重要性data.table

用法

xgb.importance(
  model = NULL,
  feature_names = getinfo(model, "feature_name"),
  trees = NULL
)

参数

model

xgb.Booster类的对象。

特征名称

用于覆盖模型特征名称的字符向量。默认值为NULL(使用原始特征名称)。

trees

一个整数向量,包含应纳入重要性计算的(基于1的)树索引(仅适用于“gbtree”增强器)。默认值(NULL)解析所有树。这可能很有用,例如,在多分类中分别获取每个类的特征重要性。

一个包含以下列的data.table

对于树模型

  • Features:模型中使用的特征名称。

  • Gain:每个特征基于其分割的总增益对模型的贡献分数。百分比越高表示重要性越高。

  • Cover:与此特征相关的观测数量的度量。

  • Frequency:特征在树中被使用的百分比。

对于线性模型

  • Features:模型中使用的特征名称。

  • Weight:此特征的线性系数。

  • Class:类标签(仅适用于多分类模型)。对于xgboost类的对象(由xgboost()生成),它将是一个factor,而对于xgb.Booster类的对象(由xgb.train()生成),它将是一个从零开始的整数向量。

如果未提供feature_namesmodel没有feature_names,则将使用特征的索引代替。由于索引是从模型转储(基于C++代码)中提取的,因此它从0开始(如在C/C++或Python中),而不是从1开始(R中通常如此)。

详细信息

此函数适用于线性和树模型。

对于线性模型,重要性是线性系数的绝对大小。为了获得有意义的线性模型重要性排名,特征需要处于相同的尺度(在使用L1或L2正则化时也建议这样做)。

示例

# binary classification using "gbtree":
data("ToothGrowth")
x <- ToothGrowth[, c("len", "dose")]
y <- ToothGrowth$supp
model_tree_binary <- xgboost(
  x, y,
  nrounds = 5L,
  nthreads = 1L,
  booster = "gbtree",
  max_depth = 2L
)
xgb.importance(model_tree_binary)

# binary classification using "gblinear":
model_tree_linear <- xgboost(
  x, y,
  nrounds = 5L,
  nthreads = 1L,
  booster = "gblinear",
  learning_rate = 0.3
)
xgb.importance(model_tree_linear)

# multi-class classification using "gbtree":
data("iris")
x <- iris[, c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")]
y <- iris$Species
model_tree_multi <- xgboost(
  x, y,
  nrounds = 5L,
  nthreads = 1L,
  booster = "gbtree",
  max_depth = 3
)
# all classes clumped together:
xgb.importance(model_tree_multi)
# inspect importances separately for each class:
num_classes <- 3L
nrounds <- 5L
xgb.importance(
  model_tree_multi, trees = seq(from = 1, by = num_classes, length.out = nrounds)
)
xgb.importance(
  model_tree_multi, trees = seq(from = 2, by = num_classes, length.out = nrounds)
)
xgb.importance(
  model_tree_multi, trees = seq(from = 3, by = num_classes, length.out = nrounds)
)

# multi-class classification using "gblinear":
model_linear_multi <- xgboost(
  x, y,
  nrounds = 5L,
  nthreads = 1L,
  booster = "gblinear",
  learning_rate = 0.2
)
xgb.importance(model_linear_multi)