LightGBM icon indicating copy to clipboard operation
LightGBM copied to clipboard

Categorical features with 2 levels

Open rgranvil opened this issue 9 years ago • 4 comments

Based on the output of lgb.dump, LightGBM appears to be treating categorical variables with 2 levels as continuous variables. I don't think this would have an impact on the model, but what is the reason for this treatment?

Lgb.dump output splitting on "vs" (a categorical variable with two levels):

{"tree_index":1,"num_leaves":2,
"num_cat":0,
"shrinkage":0.10000000000000001,
"tree_structure":{
"split_index":0,
"split_feature":0,
"split_gain":496.52788575304061,
"threshold":1.5,
"decision_type":"<=",
"default_left":true,
"missing_type":"None",
"internal_value":0,
"internal_count":32,
"left_child":{
"leaf_index":0,
"leaf_parent":0,
"leaf_value":-0.34739582008785674,
"leaf_count":18
}

Lgb.dump output splitting on "gear" (a categorical variable with three levels):

{"tree_index":2,"num_leaves":2,
"num_cat":1,
"shrinkage":0.10000000000000001,
"tree_structure":{
"split_index":0,
"split_feature":1,
"split_gain":406.72514060137144,
"threshold":"2||3",
"decision_type":"==",
"default_left":false,
"missing_type":"None",
"internal_value":0,
"internal_count":32,
"left_child":{
"leaf_index":0,
"leaf_parent":0,
"leaf_value":0.33488575700013079,
"leaf_count":17
}

Code:

library(lightgbm)
data(mtcars)
mtcars$vs <- as.numeric(as.factor(mtcars$vs))
mtcars$gear <- as.numeric(as.factor(mtcars$gear))
lgb.data <- lgb.Dataset(
  data = as.matrix(mtcars[, c("vs", "gear")])
  ,label = mtcars$mpg
  ,categorical_feature = c("vs", "gear")
)
lgb.model <- lgb.train(
  data = lgb.data
  ,nround = 2
  ,num_leaves = 2
  ,min_data = 1
  ,learning_rate = 0.1
  ,obj = "regression_l2"
)
writeLines(lgb.dump(lgb.model))

rgranvil avatar Aug 11 '17 19:08 rgranvil

A categorical variable with 2 different values is the same as a binary feature, therefore continuous treatment is more appropriate for speed.

ping @guolinke in case

Laurae2 avatar Aug 11 '17 19:08 Laurae2

It creates some complications when parsing the lgb.dump file to generate scoring code when the variable types are changing. Is it possible to keep the continuous treatment in model training for speed, but output the dump file in categorical format? This would maintain consistency between the function inputs and function outputs.

rgranvil avatar Aug 11 '17 19:08 rgranvil

@rgranvil can you try latest code ?

guolinke avatar Aug 12 '17 01:08 guolinke

@guolinke Works well now. Thanks.

rgranvil avatar Aug 15 '17 01:08 rgranvil